blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
213 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
246 values
content
stringlengths
2
10.3M
authors
sequencelengths
1
1
author_id
stringlengths
0
212
f9223c6f436ea5266d96716ea00fab8e54ef1232
f61aa4d5791fc858e52db956f447cfd0af5182cf
/for_loop_with_range.py
d3a11bce07fa0ab64713d62c00d4dc30278ae539
[]
no_license
AshutoshPanwar/Python_udemy_course
70abda4418c4532dd886a2b98c0bfb0bc8fbc138
7b4698f47a9a80b4cbe07e2334ccc6bc1427118c
refs/heads/master
2023-04-19T00:02:48.129265
2021-05-05T10:23:52
2021-05-05T10:23:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
229
py
x = range(5) print(x) for i in x: print(i) x = range(3,9) print(x) for i in x: print(i) x = range(0,10,2) print(x) for i in x: print(i) x = range(10,0,-1) print(x) for i in x: print(i)
62057c8eb956315f5f52fa00e9a3237b9e78aa7e
c1faf35b2fe1beda6c839031465195ea58b4c495
/panelserverextension.py
eae784198ae449200859acbf4742f46ee152c279
[]
no_license
makwingchi/philly-route-finder
ff9f6001a39a7d838ff143ee5445cc848f456205
c807c76290772f4b31bd0cdaab7a1ab6e505d8e7
refs/heads/master
2020-05-22T10:19:23.003297
2019-07-14T15:25:46
2019-07-14T15:25:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
206
py
from subprocess import Popen def load_jupyter_server_extension(nbapp): """serve the app.ipynb directory with bokeh server""" Popen(["panel", "serve", "app.ipynb", "--allow-websocket-origin=*"])
90d5f61f2f9b83db77223e3d0283d7bd46995393
741fdf35f1e890f9e4b2c878fe4febf5ca49ca2c
/venv/lib/python3.7/__future__.py
13fc49f811ca3a58d28b3f073dd5c98abb0ed602
[]
no_license
kkhuong/provablecard-backend
39f1430060aa656e178ce86bca92912b0d4ec6ca
45d91571ba1091a9c9a62ad2cc4ee9ac56e5fb77
refs/heads/main
2023-08-07T03:44:31.124974
2021-09-22T23:03:23
2021-09-22T23:03:23
403,407,838
0
0
null
2021-09-22T23:03:24
2021-09-05T20:36:14
Python
UTF-8
Python
false
false
52
py
/Users/kkhuong/anaconda3/lib/python3.7/__future__.py
30a24a821f8d90d74d6bc66e4f16cf66c480df7d
2e368bbce5f867db9046f45130bbbae06e3fbe1d
/SPOJ/AGGRCOW.py
44da59577a4cdeef35588a178d747d50f505ec7f
[]
no_license
Andresrodart/Hobbies
2b66c5adc8054b5f8e4c58129f49b0af420383ec
f1d29f3d30104d41aa80b7cea0aae7730a2cf6d8
refs/heads/master
2022-10-24T18:33:31.707102
2022-10-22T00:10:15
2022-10-22T00:10:15
172,858,524
0
0
null
null
null
null
UTF-8
Python
false
false
661
py
def binary(lis, N, minElement, maxElement): mid = int((minElement + maxElement)/2) aux = False if minElement > maxElement or mid == 0: return 0 for i in range(N - 1): if mid <= lis[i] - lis[i - 1] - 1: aux = True if aux == True: return min(mid, binary(lis, N, minElement, mid - 1)) else: return binary(lis, N, minElement, mid - 1) cases = int(input()) for _ in range(cases): N, C = map(int, input().split()) stallLocation = [] for each in range(N): stallLocation.append(int(input())) if N == C: print(1) else: stallLocation.sort() print(binary(stallLocation, N, 2, stallLocation[-1]))
502a997a737c69b83cae42436b5cfb34b54b79a6
c3a3559c13ae03c608e1a499296e6591b30e2a65
/apis/admin.py
3b090b7af1014def36b7378b2123e21d0380ea6a
[]
no_license
shohansk/powerup
6a7f9f90672777bf8c358184880b7b1e666cbd1f
dbb935f2ca7a933061abb941c241c3e96746b6d3
refs/heads/master
2023-08-05T13:07:37.676846
2021-10-05T20:33:49
2021-10-05T20:33:49
412,752,830
0
0
null
null
null
null
UTF-8
Python
false
false
265
py
from django.contrib import admin from .models import * # Register your models here. #admin.site.register(Article) @admin.register(Article) class ArticleModel(admin.ModelAdmin): list_filter=('tittle','description') list_display=('tittle','description')
5e41d186eacaeca5c998b2f0448d52b60e251c6b
0e563cc19a6d7817c353c4d1903ae2ee37ccaa72
/Functional_Programming.py
9db92732b5fda6c74ce338fbd2ba8261259da556
[]
no_license
AaliyanK/AdvancedPython-
fa25efcc4d1459b470afe804d51af7eed6ee56a8
0e7f4e2de35f85ca6376d651df085e29ae059aa1
refs/heads/master
2021-03-29T01:55:45.975840
2020-03-17T08:18:59
2020-03-17T08:18:59
247,913,651
1
0
null
null
null
null
UTF-8
Python
false
false
3,854
py
# Functional programming - packaging of code like OOP - seperate data/functions # PURE FUNCTION - input a list and function does something to result in a different output # given the same input, pure functions should always return the same output # should not produce any side effects - changes in variables, changing things in the outside function # Useful functions - map/filter/zip/reduce # MAP - will return the same number of items my_list = [1,2,3] def multiply(item): return item*2 print(list(map(multiply,[1,2,3]))) # map(input function, data we want the change) # GREAT replacement for "for loops" - map iterates over the data we input # map will return item*2 each time - returns a list # IMPORTANT! map wont change anything from the outside world - pure function print(list(map(multiply,my_list))) print(my_list) # will still output [1,2,3] print(" ") # FILTER - can return less than what we input def only_odd(item): return item % 2 != 0 # Odd if remainder of two nums is NOT 0 - return odds only print(list(filter(only_odd,[1,2,3,4,5,6,7]))) # output is filtered and will only return odd! # ZIP - need two lists/iterables and need to zip them together list1 = [1,2,3] list2 = [4,5,6] print(list(zip(list1,list2))) # GRABS FIRST ITEM IN EACH list then pairs them in a tuple, does the same for the second items # Can be used in a database where there is a list of names and a list of phone numbers # we use zip to chain together the entries in the respective order print(" ") # REDUCE def accum(acc,item): print(acc,item) return acc+item from functools import reduce print(reduce(accum,list1,0)) # (function,list,intial) - list is the "item" initial is the "acc" print(" ") # EXERCISE #1 Capitalize all of the pet names and print the list my_pets = ['sisi', 'bibi', 'titi', 'carla'] def cap(item): return item.capitalize() print(list(map(cap,my_pets))) #2 Zip the 2 lists into a list of tuples, but sort the numbers from lowest to highest. my_strings = ['a', 'b', 'c', 'd', 'e'] my_numbers = [5,4,3,2,1] my_numbers.sort() print(list(zip(my_strings,my_numbers))) #3 Filter the scores that pass over 50% scores = [73, 20, 65, 19, 76, 100, 88] def filt(item): return item>50 print(list(filter(filt,scores))) print(" ") # LAMBDA Expressions - anonymous functions - use lambda when we only need to use a function once # lambda argument: action(input) lamlist = [1,2,3] print(list(map(lambda item: item*2,lamlist))) # same thing as: def multiply(item = lamlist): # return item*2 print(" ") # LAMBDA EXERCISE - square a list square = [5,4,3] print(list(map(lambda item: item**2,square))) # List sorting import operator a = [(0,2),(4,3),(9,9), (10,-1)] print(list(map(lambda item: sorted(item),a))) print(" ") # LIST COMPREHENSIONS - quick ways of creating dicts/sets/lists # INSTEAD OF FOR LOOP LIKE: listcomp = [] for char in 'hello': listcomp.append(char) print(listcomp) # DO THIS - listcomp = [variable for variable in iterable] listcomp= [char for char in 'hello'] print(listcomp) mylist2 = [num for num in range(0,100)] # will just output a list mylist3 = [num**2 for num in range(0,100)] # [action for variable in range] - will do an action mylist4 = [num**2 for num in range(0,100) if num%2==0] # add an if statement print(" ") # dictionary comprehensions simpledict = { 'a':1, 'b':2 } my_dict = {key:value**2 for key,value in simpledict.items() if value%2==0} # doing an action on the values if something occurs print(my_dict) listdict = {num:num**2 for num in [1,2,3]} # num is the index, we create a dict with key being num and value being num squared # LIST COMPREHENSIONS EX some_list = ['a','b','c','b','d','m','n','n'] duplicates = set([item for item in some_list if some_list.count(item)>1]) # USE SET WHEN WE DONT WANT REPITIONS print(duplicates)
d2d4b145a119464517178bf68e6c701759415581
b64dda470d8738476cc9e12d681887d0fa43e483
/IPL/urls.py
86856c93c0578d45348b6b73a448c32c497368dd
[]
no_license
Sky-Akash001/IPL2
e03be810582958270f32212a6756d2a836e21fdb
80ff8aeb2c36617fc6819e4194fa1b682d1b3073
refs/heads/master
2023-03-21T00:21:51.927475
2021-03-15T11:59:44
2021-03-15T11:59:44
347,951,957
0
0
null
null
null
null
UTF-8
Python
false
false
916
py
"""IPL 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 from predictions import views urlpatterns = [ path('', views.index,name='index'), path('home', views.home,name='home'), path('result', views.result,name='result'), path('test', views.news,name='news'), ]
98c3f17ac4c25ff7ff6cef9610b9bc3f69064b48
9e87c4502713bfd4dfb113c6bb48a752597a0431
/gss/bin/modes/enhance.py
edd711f6ff1f8b632ea746f1b3fe7304b948a092
[ "MIT" ]
permissive
desh2608/gss
ef9eabea233bd436da5ea79bfc51ba2f7562c2e1
9594ccb0efc72ad591504bfe195c82aeafd397b8
refs/heads/master
2023-08-20T04:50:10.913415
2023-08-13T17:05:26
2023-08-13T17:05:26
454,553,727
62
7
MIT
2023-07-20T13:46:15
2022-02-01T21:16:15
Python
UTF-8
Python
false
false
10,459
py
import functools import logging import time from pathlib import Path import click from lhotse import Recording, SupervisionSet, load_manifest_lazy from lhotse.audio import set_audio_duration_mismatch_tolerance from lhotse.cut import CutSet from lhotse.utils import fastcopy from gss.bin.modes.cli_base import cli from gss.core.enhancer import get_enhancer from gss.utils.data_utils import post_process_manifests logging.basicConfig( format="%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s", datefmt="%Y-%m-%d:%H:%M:%S", level=logging.INFO, ) logger = logging.getLogger(__name__) @cli.group() def enhance(): """Commands for enhancing single recordings or manifests.""" pass def common_options(func): @click.option( "--channels", "-c", type=str, default=None, help="Channels to use for enhancement. Specify with comma-separated values, e.g. " "`--channels 0,2,4`. All channels will be used by default.", ) @click.option( "--bss-iterations", "-i", type=int, default=10, help="Number of iterations for BSS", show_default=True, ) @click.option( "--use-wpe/--no-wpe", default=True, help="Whether to use WPE for GSS", show_default=True, ) @click.option( "--context-duration", type=float, default=15.0, help="Context duration in seconds for CACGMM", show_default=True, ) @click.option( "--use-garbage-class/--no-garbage-class", default=False, help="Whether to use the additional noise class for CACGMM", show_default=True, ) @click.option( "--min-segment-length", type=float, default=0.0, help="Minimum segment length to retain (removing very small segments speeds up enhancement)", show_default=True, ) @click.option( "--max-segment-length", type=float, default=15.0, help="Chunk up longer segments to avoid OOM issues", show_default=True, ) @click.option( "--max-batch-duration", type=float, default=20.0, help="Maximum duration of a batch in seconds", show_default=True, ) @click.option( "--max-batch-cuts", type=int, default=None, help="Maximum number of cuts in a batch", show_default=True, ) @click.option( "--num-workers", type=int, default=1, help="Number of workers for parallel processing", show_default=True, ) @click.option( "--num-buckets", type=int, default=2, help="Number of buckets per speaker for batching (use larger values if you set higer max-segment-length)", show_default=True, ) @click.option( "--enhanced-manifest", "-o", type=click.Path(), default=None, help="Path to the output manifest containing details of the enhanced segments.", ) @click.option( "--profiler-output", type=click.Path(), default=None, help="Path to the profiler output file.", ) @click.option( "--force-overwrite", is_flag=True, default=False, help="If set, we will overwrite the enhanced audio files if they already exist.", ) @functools.wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper @enhance.command(name="cuts") @click.argument( "cuts_per_recording", type=click.Path(exists=True), ) @click.argument( "cuts_per_segment", type=click.Path(exists=True), ) @click.argument( "enhanced_dir", type=click.Path(), ) @common_options @click.option( "--duration-tolerance", type=float, default=None, help="Maximum mismatch between channel durations to allow. Some corpora like CHiME-6 " "need a large value, e.g., 2 seconds", ) def cuts_( cuts_per_recording, cuts_per_segment, enhanced_dir, channels, bss_iterations, use_wpe, context_duration, use_garbage_class, min_segment_length, max_segment_length, max_batch_duration, max_batch_cuts, num_workers, num_buckets, enhanced_manifest, profiler_output, force_overwrite, duration_tolerance, ): """ Enhance segments (represented by cuts). CUTS_PER_RECORDING: Lhotse cuts manifest containing cuts per recording CUTS_PER_SEGMENT: Lhotse cuts manifest containing cuts per segment (e.g. obtained using `trim-to-supervisions`) ENHANCED_DIR: Output directory for enhanced audio files """ if profiler_output is not None: import atexit import cProfile import pstats print("Profiling...") pr = cProfile.Profile() pr.enable() def exit(): pr.disable() print("Profiling completed") pstats.Stats(pr).sort_stats("cumulative").dump_stats(profiler_output) atexit.register(exit) if duration_tolerance is not None: set_audio_duration_mismatch_tolerance(duration_tolerance) enhanced_dir = Path(enhanced_dir) enhanced_dir.mkdir(exist_ok=True, parents=True) cuts = load_manifest_lazy(cuts_per_recording) cuts_per_segment = load_manifest_lazy(cuts_per_segment) if channels is not None: channels = [int(c) for c in channels.split(",")] cuts_per_segment = CutSet.from_cuts( fastcopy(cut, channel=channels) for cut in cuts_per_segment ) # Paranoia mode: ensure that cuts_per_recording have ids same as the recording_id cuts = CutSet.from_cuts(cut.with_id(cut.recording_id) for cut in cuts) logger.info("Aplying min/max segment length constraints") cuts_per_segment = cuts_per_segment.filter( lambda c: c.duration > min_segment_length ).cut_into_windows(duration=max_segment_length) logger.info("Initializing GSS enhancer") enhancer = get_enhancer( cuts=cuts, bss_iterations=bss_iterations, context_duration=context_duration, activity_garbage_class=use_garbage_class, wpe=use_wpe, ) logger.info(f"Enhancing {len(frozenset(c.id for c in cuts_per_segment))} segments") begin = time.time() num_errors, out_cuts = enhancer.enhance_cuts( cuts_per_segment, enhanced_dir, max_batch_duration=max_batch_duration, max_batch_cuts=max_batch_cuts, num_workers=num_workers, num_buckets=num_buckets, force_overwrite=force_overwrite, ) end = time.time() logger.info(f"Finished in {end-begin:.2f}s with {num_errors} errors") if enhanced_manifest is not None: logger.info(f"Saving enhanced cuts manifest to {enhanced_manifest}") out_cuts = post_process_manifests(out_cuts, enhanced_dir) out_cuts.to_file(enhanced_manifest) @enhance.command(name="recording") @click.argument( "recording", type=click.Path(exists=True), ) @click.argument( "rttm", type=click.Path(exists=True), ) @click.argument( "enhanced_dir", type=click.Path(), ) @click.option( "--recording-id", type=str, default=None, help="Name of recording (will be used to get corresponding segments from RTTM)", ) @common_options def recording_( recording, rttm, enhanced_dir, recording_id, channels, bss_iterations, use_wpe, context_duration, use_garbage_class, min_segment_length, max_segment_length, max_batch_duration, max_batch_cuts, num_workers, num_buckets, enhanced_manifest, profiler_output, force_overwrite, ): """ Enhance a single recording using an RTTM file. RECORDING: Path to a multi-channel recording RTTM: Path to an RTTM file containing speech activity ENHANCED_DIR: Output directory for enhanced audio files """ if profiler_output is not None: import atexit import cProfile import pstats print("Profiling...") pr = cProfile.Profile() pr.enable() def exit(): pr.disable() print("Profiling completed") pstats.Stats(pr).sort_stats("cumulative").dump_stats(profiler_output) atexit.register(exit) enhanced_dir = Path(enhanced_dir) enhanced_dir.mkdir(exist_ok=True, parents=True) cut = Recording.from_file(recording, recording_id=recording_id).to_cut() if channels is not None: channels = [int(c) for c in channels.split(",")] cut = fastcopy(cut, channel=channels) supervisions = SupervisionSet.from_rttm(rttm).filter( lambda s: s.recording_id == cut.id ) # Modify channel IDs to match the recording supervisions = SupervisionSet.from_segments( fastcopy(s, channel=cut.channel) for s in supervisions ) cut.supervisions = supervisions # Create a cuts manifest with a single cut for the recording cuts = CutSet.from_cuts([cut]) # Create segment-wise cuts cuts_per_segment = cuts.trim_to_supervisions( keep_overlapping=False, keep_all_channels=True ) logger.info("Aplying min/max segment length constraints") cuts_per_segment = cuts_per_segment.filter( lambda c: c.duration > min_segment_length ).cut_into_windows(duration=max_segment_length) logger.info("Initializing GSS enhancer") enhancer = get_enhancer( cuts=cuts, bss_iterations=bss_iterations, context_duration=context_duration, activity_garbage_class=use_garbage_class, wpe=use_wpe, ) logger.info(f"Enhancing {len(frozenset(c.id for c in cuts_per_segment))} segments") begin = time.time() num_errors, out_cuts = enhancer.enhance_cuts( cuts_per_segment, enhanced_dir, max_batch_duration=max_batch_duration, max_batch_cuts=max_batch_cuts, num_workers=num_workers, num_buckets=num_buckets, force_overwrite=force_overwrite, ) end = time.time() logger.info(f"Finished in {end-begin:.2f}s with {num_errors} errors") if enhanced_manifest is not None: logger.info(f"Saving enhanced cuts manifest to {enhanced_manifest}") out_cuts = post_process_manifests(out_cuts, enhanced_dir) out_cuts.to_file(enhanced_manifest)
9f6ac6ecefb20871f98905fe6225b28a48eaf51d
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/9szPm9Mg5D2vJyTvf_14.py
c4b1eb7103a2e128742d7e447be9653582eade63
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
681
py
""" Write a function that takes three arguments `(x, y, z)` and returns a list containing `x` sublists (e.g. `[[], [], []]`), each containing `y` number of item `z`. * `x` Number of sublists contained within the main list. * `y` Number of items contained within each sublist. * `z` Item contained within each sublist. ### Examples matrix(3, 2, 3) ➞ [[3, 3], [3, 3], [3, 3]] matrix(2, 1, "edabit") ➞ [["edabit"], ["edabit"]] matrix(3, 2, 0) ➞ [[0, 0], [0, 0], [0, 0]] ### Notes * The first two arguments will always be integers. * The third argument is either a string or an integer. """ def matrix(x, y, z): return [[z] * y] * x
dd9fe308a2e6dd027278533f1be405f235583281
207ef888d9ba6f73378756c0c0b1f22864b15c93
/myapp10.py
420f42a67946444cbfdacc2a5aae3c76e33e35ec
[]
no_license
ochim/python-lessons
935ef6977e8c12c4babb04aa4b76106a02ab337a
1eb1bd9fd9eb84a1fb746776405e7520da1b7f47
refs/heads/master
2021-01-20T02:37:43.973892
2017-04-26T03:21:10
2017-04-26T03:21:10
89,432,010
0
0
null
null
null
null
UTF-8
Python
false
false
194
py
# method # def say_hi(): def say_hi(name, age = 20): # print("Hi") print ("hi {0} ({1})".format(name, age)) say_hi('tom',23) say_hi("bob",25) say_hi("jobs") say_hi(age=18, name="rick")
d2bec8330e7194b82322663dff6a7e4aebb23fa0
a8ec4d66072edaa8ab090c2956a989aa8429d6b6
/Q2/rent_cawler/rent_crawler/crawlers.py
7abc6bbb3c049bc10db7e1a100458e4c959448a3
[]
no_license
sileverfall/takeHomeExam_ca
b57cc399c4e0945c34739d2b7fd52f3c728f0f15
c34d5b810720c5788efd5f42c397df17b70e05cf
refs/heads/master
2021-04-11T04:45:33.724861
2020-03-28T16:05:52
2020-03-28T16:05:52
248,993,155
0
0
null
null
null
null
UTF-8
Python
false
false
5,624
py
from rent_crawler.config.headers import user_agent_list from rent_crawler.config.region_map import region_map from bs4 import BeautifulSoup as bs from lxml import etree from pprint import pprint from urllib.parse import urlencode import math import json import os import pandas as pd import re import requests import time headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'} client = requests.session() trans = {'押金': 'deposit', '車位': 'parking', '管理費': 'fee', '最短租期': 'at_least', '開伙': 'cooking', '養寵物': 'pet' , '身份要求': 'identification' , '朝向': 'direction', '可遷入日': 'live_date', '法定用途': 'function', '建物面積': 'area', '產權登記': 'registration', '格局': 'addition', '坪數': 'ping', '權狀坪數': 'ping', '樓層': 'floor', '性別要求': 'gender', '型態':'type', '非於政府免付費公開資料可查詢法定用途':'in_law_function' , '非於政府免付費公開資料可查詢建物面積': 'in_law_area', '現況':'current'} def get_var(client,region,headers): index_url='https://rent.591.com.tw/?kind=0&regionid='+region_map[region] res = client.get(index_url,headers=headers) res.encoding = 'utf-8' res.cookies['urlJumpIp']= region_map[region] # print(res.cookies.get_dict()) soup = bs(res.text, "lxml") # print(soup.select('head > meta')) totalRows = soup.select('#container > section.listBox > div > div.listLeft > div.page-limit > div > a.pageNext')[0]['data-total'] CSRF_TOKEN = [i['content'] for i in soup.select('head > meta[name]') if i['name']=="csrf-token"][0] return (totalRows ,CSRF_TOKEN) def get_searchUrl(firstRow,region,headers): params = { 'is_new_list': 1, 'type': 1, 'kind':0, 'searchtype':1, 'region':region_map[region], 'firstRow':(firstRow*30), 'totalRows':get_var(client,region,headers)[0] } base_url = 'https://rent.591.com.tw/home/search/rsList?' url = base_url + urlencode(params) return url def get_searchUrlist(client,region,headers): vars = get_var(client,region,headers) headers['X-CSRF-Token'] = vars[1] times = math.floor(int(vars[0])/30) +1 if int(vars[0])%30 !=0 else math.floor(int(vars[0])/30) searchUrlist=[] for firstRow in range(times): searchUrl = get_searchUrl(firstRow,region,headers) # print(searchUrl) res_search = client.get(searchUrl,headers=headers) res_search.encoding = 'utf-8' data = json.loads(res_search.text) # print(data['data']['data'][0]['post_id']) rent_list = [[i['post_id'],i['region_name'],i['nick_name'],i['region_name']+' '+i['fulladdress'],'https://rent.591.com.tw/rent-detail-'+str(i['post_id'])+'.html'] for i in data['data']['data']] # print(rent_list[0]) searchUrlist.extend(rent_list) return searchUrlist def get_house(searchUrl,headers): houses=[] for url in searchUrl: hid = url[0] region = url[1] name = url[2] address = url[3] detail_url = url[4] res_detail = requests.get(detail_url,headers=headers) soup_detail = bs(res_detail.text, "lxml") try: dialPhone = soup_detail.select('div.userInfo > div > span.dialPhoneNum')[0]['data-value'] except : dialPhone = '' try: hid_tel = soup_detail.select('div.userInfo > div > input#hid_tel')[0]['value'] except: hid_tel = '' try: hid_email = soup_detail.select('div.userInfo > div > input#hid_email')[0]['value'] except: hid_email = '' # if soup_detail.select('div.userInfo > div > span.kfCallName')[0]['data-name']: # name = soup_detail.select('div.userInfo > div > span.kfCallName')[0]['data-name'] # if soup_detail.select('div.userInfo > div > span.dialPhoneNum')[0]['data-value']: # dialPhone = soup_detail.select('div.userInfo > div > span.dialPhoneNum')[0]['data-value'] # if soup_detail.select('div.userInfo > div > input#hid_tel')[0]['value']: # hid_tel = soup_detail.select('div.userInfo > div > input#hid_tel')[0]['value'] # if soup_detail.select('div.userInfo > div > input#hid_email')[0]['value']: # hid_email = soup_detail.select('div.userInfo > div > input#hid_email')[0]['value'] infs = [{trans[j[0].text.replace(' ','')] if j[0].text.replace(' ','') in trans else '':j[1].text.replace(' ','').replace(':','') for j in zip(i.select('div.one'),i.select('div.two'))} for i in soup_detail.select('ul.clearfix.labelList.labelList-1 > li')] attrs = [{trans[''.join(i.text.split(':')[0].split())] if ''.join(i.text.split(':')[0].split()) in trans else '':''.join(i.text.split(':')[1].split()) } for i in soup_detail.select('ul.attr > li')] try: out_rec = { 'hid' : hid, 'region':region, 'address': address, 'name': name , 'dialPhone' : dialPhone , 'hid_tel' : hid_tel, 'hid_email' : hid_email, 'price':soup_detail.select('div.price')[0].text.split('\n')[1], 'url':detail_url } [out_rec.update(inf) for inf in infs] [out_rec.update(attr) for attr in attrs] except Exception as e: print(detail_url) print(e) houses.append(out_rec) return houses
8f9cbe32837705b4ef9ab8d7ce0e86116f300f55
028b90aba19673183e1433cf44d8de631bf915e3
/Python_Tutorials/for_loop.py
99aabd643f7ed1c92b3c168c0ccbd3130e139dc5
[]
no_license
vivekgupta8983/python_tut
5388948964ef6419fb0fea7f734c6b180d72e7a0
a6471c193f46c3ed905315012ef0074f41cc2d71
refs/heads/master
2020-06-29T06:08:12.883359
2019-08-09T12:03:17
2019-08-09T12:03:17
200,458,697
0
0
null
null
null
null
UTF-8
Python
false
false
487
py
""" For loop example for Python """ # string for loop my_string = 'abcabc' for c in my_string: if c == 'a': print('A', end=' ') else: print(c, end=' ') print() # List for loops cars = ['bmw', 'benz', 'honda'] for car in cars: print(car) nums = [1, 2, 3] for n in nums: print(n * 10) # dictionary for loops d = {'one': 1, 'two': 2, 'three': 3} for k in d: print(k + " " + str(d[k])) print("#"*20) for k,v in d.items(): print(k) print(v)
65d52f74844248efbaf7b804d72e1910b77afe4f
9716db44524889e45b7c47cb9808e67a3bc68fcc
/TCPControl.py
a791ed568bfea8e6185fa3aa72a8e9f21b3dcc24
[]
no_license
UDneuroDrive/Hardware-Program
5323fd3821b68a290bf3616d802b9fc9ad898b18
187111f75bb5e6205f06224a5830ed3977162378
refs/heads/master
2020-09-24T10:18:49.443652
2019-12-03T23:56:11
2019-12-03T23:56:11
225,738,495
0
0
null
null
null
null
UTF-8
Python
false
false
2,078
py
#run this file from terminal #must be in the same folder on the Pi as servomotor4.py import motor from socket import * import time from time import ctime import RPi.GPIO as GPIO import Adafruit_PCA9685 #Initializing the I2C communication with servo hat pwm = Adafruit_PCA9685.PCA9685() pwm.set_pwm_freq(50) #Run initial setup motor.setup(pwm) HOST = '' PORT = 21567 BUFSIZE = 1024 ADDR = (HOST,PORT) tcpSerSock = socket(AF_INET,SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.listen(5) while True: try: #print 'waiting for connection' tcpSerSock.settimeout(2) tcpCliSock,addr = tcpSerSock.accept() '...connected from :', addr try: while True: cardata = '' cardata = tcpCliSock.recv(BUFSIZE) if not cardata: break #split the string cardata.split("||") s,t,u,l,r = cardata.split("||") #change back to numeric value steerpi = float(s) speedpi = float(t) UpDownLevel = float(u) LeftRightLevel = float(l) StartStop = int(float(r)) #heart = int(float(h)) motor.test(speedpi,StartStop,pwm) motor.steertest(steerpi, pwm) motor.cameraboi(UpDownLevel, LeftRightLevel, pwm) #Use the above line for the other variables #and write a method in motor.py to match print('Steering Angle: ',steerpi) print('Throttle %: ',speedpi) print('U/D Cam Servo Pulse Width: ', UpDownLevel) print('L/R Cam Servo Pulse Width: ', LeftRightLevel) print('Run Status(1 = Run): ', StartStop) #print 'Heartbeat: ',heart except KeyboardInterrupt: motor.close() GPIO.cleanup() pass except timeout: motor.timeout(pwm) time.sleep(1) tcpSerSock.close()
a8694b72dc9f4ac269b718d8c743574a18cfc288
1fc45a47f0e540941c87b04616f3b4019da9f9a0
/tests/sentry/api/endpoints/test_commit_filechange.py
49eefdcd009d8d4020c56be8b1609185bc95f982
[ "BSD-2-Clause" ]
permissive
seukjung/sentry-8.15.0
febc11864a74a68ddb97b146cc1d2438ef019241
fd3cab65c64fcbc32817885fa44df65534844793
refs/heads/master
2022-10-28T06:39:17.063333
2018-01-17T12:31:55
2018-01-17T12:31:55
117,833,103
0
0
BSD-3-Clause
2022-10-05T18:09:54
2018-01-17T12:28:13
Python
UTF-8
Python
false
false
2,225
py
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.models import Commit, CommitFileChange, Release, ReleaseCommit, Repository from sentry.testutils import APITestCase class CommitFileChangeTest(APITestCase): def test_simple(self): project = self.create_project( name='foo', ) release = Release.objects.create( organization_id=project.organization_id, version='1', ) release.add_project(project) repo = Repository.objects.create( organization_id=project.organization_id, name=project.name, ) commit = Commit.objects.create( organization_id=project.organization_id, repository_id=repo.id, key='a' * 40, ) commit2 = Commit.objects.create( organization_id=project.organization_id, repository_id=repo.id, key='b' * 40, ) ReleaseCommit.objects.create( organization_id=project.organization_id, release=release, commit=commit, order=1, ) ReleaseCommit.objects.create( organization_id=project.organization_id, release=release, commit=commit2, order=0, ) CommitFileChange.objects.create( organization_id=project.organization_id, commit=commit, filename='.gitignore', type='M' ) CommitFileChange.objects.create( organization_id=project.organization_id, commit=commit2, filename='/static/js/widget.js', type='A' ) url = reverse('sentry-api-0-release-commitfilechange', kwargs={ 'organization_slug': project.organization.slug, 'version': release.version, }) self.login_as(user=self.user) response = self.client.get(url) assert response.status_code == 200, response.content assert len(response.data) == 2 assert response.data[0]['filename'] == '.gitignore' assert response.data[1]['filename'] == '/static/js/widget.js'
a29b7038e5dac455d40ad782b66da3e5b49c9846
ae28569fe6804d20de3856cdc9006e98f2db6496
/Item.py
adce20be72cf61cf7d542ed01c0dda3a61b7ae1f
[]
no_license
Eredost/Save-Macgyver
d75131951d692deb1843622511500285d99d9190
ddf49a332bfd68c6bba5edc1f615a212b89dcfac
refs/heads/master
2021-09-06T07:10:15.868332
2018-02-03T16:05:09
2018-02-03T16:05:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,812
py
#-*-coding:UTF-8 -*- """This module load items, place randomly on the window and check the player position""" import random class Item: """This class initialize a random place for items and initialize it on pygame window, create a inventory and fills it according to the position of the character""" def __init__(self, item1, item2, item3, level, character): """Takes items pictures, the level where they will be incremented and the character to recover his position""" self.items = [item1, item2, item3] self.level = level self.character = character self.items_pos = [] self.inventory = [] #INIT RANDOM NUMBERS AND ADD IT IN A LIST TO PLACE ITEMS for item in self.items: self.items_pos.append(random.randint(0, len(self.level.blank_cases))) def placement(self, window): """We get the list of blank cases of the level and with the random numbers, we place them on the game window. We check the player position and if it is on the place of an object, it is added in his inventory and no longer display on screen""" value = 0 for item in self.items: #WE SAVE THE POSITION X AND Y OF BLANK CASES IN VARIABLES blank_case_x = self.level.blank_cases[self.items_pos[value]][0] blank_case_y = self.level.blank_cases[self.items_pos[value]][1] if item not in self.inventory: window.blit(item, (blank_case_x, blank_case_y)) #IF PLAYER POS IS SAME THAN ITEM POSITION if self.character.pos_x == blank_case_x and \ self.character.pos_y == blank_case_y: self.inventory.append(item) value += 1
e8519a97fb7a10b34702f8bc053774cc1ae0a89f
6cc2b7d5b30ac94103770412d4647fa5d80edac5
/bot.py
9cb2b6cad121be952d80edcb6d518cf8443dc0a8
[]
no_license
shers003/firstRedditbot
0eab61c5ee068dec9007331c71c82d833eabd821
d2cf521a0475468720a0ec74667421951017a934
refs/heads/master
2023-02-17T03:00:52.973903
2021-01-18T14:51:13
2021-01-18T14:51:13
326,768,508
0
0
null
null
null
null
UTF-8
Python
false
false
11,640
py
#My first attempt at making a reddit bot #04-01-2021 #I'm well excited #praw import praw as pw #dotenv from dotenv import load_dotenv import os load_dotenv() #sub class of prasws Reddit class class Bot(pw.Reddit): ''' A reddit bot class ''' ####### Bot Properties ####### ############################## @property def keyWords(self): file = open('keyWords.txt', 'r') keywords = [] word = '' count = 0 while True: count += 1 word = file.readline() word = word.strip('\n') if word == '': break else: keywords.append(word) file.close() return keywords @property def my_comment_ids(self): ''' Property returns list of comments ids ''' file = open('my_comment_ids.txt', 'r') replied_to = [] name = ' ' count = 0 while True: count += 1 name = file.readline() name = name.strip('\n') if name == '': break else: replied_to.append(name) file.close() return replied_to @property def commentTxt(self): file = open('commentTxt.txt', 'r') txt = file.read() file.close() return txt @property def replied_to(self): ''' Property returns list of comments ids ''' file = open('replied_to.txt', 'r') replied_to = [] name = ' ' count = 0 while True: count += 1 name = file.readline() name = name.strip('\n') if name == '': break else: replied_to.append(name) file.close() return replied_to ## Bot Properties setters #### ############################## @commentTxt.setter def commentTxt(self, txt): file = open('commentTxt.txt', 'w') txt = file.write(txt) file.close() @keyWords.setter def new_keyWord(self, word): if word == None: return 'Not valid' elif word == '': return 'Not valid' else: file = open('keyWords.txt', 'a') file.write(word+'\n') file.close() @replied_to.setter def new_replied_to(self, newId): if newId == None: return 'Not valid' elif newId == '': return 'Not valid' else: file = open('replied_to.txt', 'a') file.write(newId+'\n') file.close() @replied_to.setter def new_my_comment_id(self, newId): if newId == None: return 'Not valid' elif newId == '': return 'Not valid' else: file = open('my_comment_ids.txt', 'a') file.write(newId+'\n') file.close() ####### Bot Methods ########## ############################## def __init__(self, client_id, client_secret, user_agent, username = None, password = None ): ''' this is the bots constructor ''' try: super(Bot, self).__init__( client_id = client_id, client_secret = client_secret, user_agent = user_agent, username = username, password = password ) except: print('Failed to authenticate') print('/*************\\ \n') else: print('Signed in as:',self.user.me()) print('read_only:',self.read_only) print('/*************\\ \n') def lookForKeyWords(self, name, numPost = 10, numCom = 10): ''' This method returns a list of comments that had the keyword ''' print('\n\n\t\tSearching',name,'\n\n') subreddit = self.subreddit(name) try: subreddit.id except: print('Invalid subreddit') return matches matches = [] keywords = self.keyWords for submit in subreddit.hot(limit = numPost): print('New post:\n') print('Title:',submit.title,'\n') comments = submit.comments for word in keywords: for i in range(numCom): try: if word in comments[i].body.lower(): comment = comments[i] info = [comment.id, comment.author, word] matches.append(info) print('Matched comment') else: print('Comment not matched') except IndexError as e: print(e) break return matches def sendComments(self, matches): ''' will send a comment to the matches ''' for match in matches: try: comId = match[0] comAuthor = str(match[1]) matchedWord = str(match[2]) except IndexError: print('Was an index error with: ',end='') print(match) continue except Exception as e: print(e,':',match) continue if comId in self.replied_to: print('already replied to',comId) continue else: reply = self.commentTxt #added this try to combat rate error try: comment = self.comment(comId) self.new_replied_to = comId comment.reply(reply) comment.upvote() self.new_my_comment_id = comment.id print('replied to user:',comAuthor,comId) except Exception as e: print('Error occured with comment:',comId,'\n',e) def replyToReplies(self, rep): for comId in self.my_comment_ids: comment = self.comment(comId) print(len(comment.replies)) if len(comment.replies) != 0: if comment.replies[0].id in self.my_comment_ids: reply = rep comment.replies[0].reply(reply) print('Replied to:',comId) else: print('Already replied to:',comId) else: print('no reply for:',comId) def main(bot): ''' Main code for console ''' print('\t\tWelcome to my reddit bot\n\n') userInput = None while userInput != '0': print('''\nHere are your options: 0.Exit 1.Scan a subreddit and comment 2.Check for replies 3.See keywords 4.Add keyword 5.view comment 6.change comment ''') userInput = input('Enter choice: ') if userInput == '1': sub = input('Which reddit: ') matches = bot.lookForKeyWords(sub) print('\n\nNumber of matches',str(len(matches))) for match in matches: print(match) bot.sendComments(matches) elif userInput == '2': msg = input('Enter a Reply for the replies') if msg == None: msg = 'I am just a freindly reddit bot' bot.replyToReplies(msg) elif userInput == '3': for word in bot.keyWords: print(word,end=' ') elif userInput == '4': keyword = input('Enter new word: ') bot.new_keyWord = keyword print('Keyword added') elif userInput == '5': print(bot.commentTxt) elif userInput == '6': newTxt = input('Enter new comment: ') if newTxt != '': bot.commentTxt = newTxt print('Commented changed to:',newTxt) elif userInput == '0': print('Bye') #initalsing instance of Reddit class bot = Bot( client_id = os.getenv("client_id"), client_secret = os.getenv("client_secret"), user_agent = os.getenv("user_agent"), username = os.getenv("redditUsername"), password = os.getenv("redditPassword")) main(bot) input('Enter to exit') ############################################## ############# GUI CODE ####################### ############################################## ''' from tkinter import * class App(Frame): def __init__(self, master, bot): super(App, self).__init__(master) self.bot = bot self.grid() self.setupGui() def setupGui(self): #Title Label(self, text = os.getenv("redditUsername") ).grid(row = 0, column = 1, sticky = W) #see comment text button Button(self, text = 'See Comment', command = self.getComment ).grid(row = 1, column = 0, sticky = W) #set comment text button Button(self, text = 'Set Comment', command = self.setComment ).grid(row = 2, column = 0, sticky = W) #Comment text box self.commentEntry = Text(self, width = 40, height = 5, wrap = WORD) self.commentEntry.grid(row = 1, column = 1, columnspan = 3, sticky = W) #see keywords text button Button(self, text = 'See Keywords', command = self.getKeywords ).grid(row = 3, column = 0, sticky = W) #Add keywords button Button(self, text = 'Add Keywords', command = self.AddKeywords ).grid(row = 4, column = 0, sticky = W) #Keywords textbox self.keyWordEntry = Text(self, width = 40, height = 5, wrap = WORD) self.keyWordEntry.grid(row = 3, column = 1, columnspan = 3, sticky = W) self.addKeywordEntry = Entry(self,) self.addKeywordEntry.grid(row = 4, column = 1, sticky = W) def getComment(self): txt = self.bot.commentTxt self.commentEntry.delete(0.0, END) self.commentEntry.insert(0.0, txt) def setComment(self): newTxt = self.commentEntry.get(0.0, END) self.bot.commentTxt = newTxt self.commentEntry.delete(0.0, END) def getKeywords(self): self.keyWordEntry.delete(0.0, END) keywords = self.bot.keyWords for word in keywords: self.keyWordEntry.insert(END, word) self.keyWordEntry.insert(END, ' ') def AddKeywords(self): self.keyWordEntry.delete(0.0, END) word = self.addKeywordEntry.get() self.bot.new_keyWord = word root = Tk() root.title('Reddit Bot') app = App(root, bot) root.mainloop() '''
d37b7814d33e64ec6efd273404e647d346e57d42
40c28ca3a8efd25f5ce5a0bfa549a8b1ba6bc958
/pelion_test_lib/tools/external_conn.py
b6eda62d9022f51d777eb8ed247fb0df07bbade6
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
teetak01/pelion-e2e-python-test-library
fc231ed7e72bf1c0cc8e7d01d3a728a6c48d53a2
5eddd591847b5363e9f6364ac40974715906fe0c
refs/heads/master
2022-12-10T03:47:23.255125
2020-08-20T11:40:32
2020-08-20T11:40:32
290,125,183
0
0
Apache-2.0
2020-08-25T05:48:03
2020-08-25T05:48:03
null
UTF-8
Python
false
false
4,946
py
# pylint: disable=broad-except """ Copyright 2019-2020 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import importlib import logging import json log = logging.getLogger(__name__) class ExternalConnection: """ External connection class """ def __init__(self): self.client = None self.resource = None self.__initialize_resource() def __initialize_resource(self): """ Connect to external resource and flash it """ try: with open('external_connection.json', 'r') as config_file: configs = json.load(config_file) except IOError: error_msg = 'Could not load the external connection configs' log.error(error_msg) raise Exception(error_msg) expiration_time = configs.get('expiration_time', 1200) allocation_timeout = configs.get('allocation_timeout', 500) local_allocation = configs.get('local_allocation', False) on_release = configs.get('on_release', 'erase') try: self.remote_module = importlib.import_module(configs['module']) except ImportError as error: log.error('Unable to load external "{}" module!'.format(configs['module'])) log.error(str(error)) self.remote_module = None raise error self.client = self.remote_module.create(host=configs['host'], port=configs['port'], user=configs['user'], passwd=configs['password']) description = {'resource_type': configs['resource_type'], 'platform_name': configs['platform_name'], 'tags': configs['resource_tags']} self.resource = self.client.allocate(description, expiration_time, allocation_timeout, local_allocation) if self.resource: self.resource.open_connection(self.remote_module.SerialParameters(baudrate=configs['baudrate'])) try: self.resource.on_release(on_release) except Exception as ex: log.debug('External connection on release event setting error: {}'.format(ex)) self.flash(configs['binary'], force_flash=True) else: self.close() error_msg = 'Could not allocate external resource' log.error(error_msg) assert False, error_msg def readline(self): """ Read line :return: One line from serial stream """ try: if self.resource: output = self.resource.readline() return output raise Exception('External resource does not exist') except Exception as ex: log.debug('External connection read error: {}'.format(ex)) return None def write(self, data): """ Write data :param data: Data to send """ try: if self.resource: self.resource.write(data) else: raise Exception('External resource does not exist') except Exception as ex: log.debug('External connection write error: {}'.format(ex)) def reset(self): """ Reset resource """ try: if self.resource: self.resource.reset() else: raise Exception('External resource does not exist') except Exception as ex: log.debug('External connection reset error: {}'.format(ex)) def flash(self, filename, force_flash=False): """ Flash resource :param filename: Path to binary :param force_flash: Force flash True/False """ try: if self.resource: log.info('Flashing resource with "{}"'.format(filename)) self.resource.flash(filename, forceflash=force_flash) else: raise Exception('External resource does not exist') except Exception as ex: log.debug('External connection flash error: {}'.format(ex)) def close(self): """ Close connection """ try: if self.resource: self.resource.release() if self.client: self.client.disconnect() except Exception as ex: log.debug('External connection closing error: {}'.format(ex))
d5cd7cfe45515f1a0899cf0344254ae70d9a69c6
8ef8e6818c977c26d937d09b46be0d748022ea09
/cv/3d_detection/pointnet2/pytorch/mmdetection3d/mmdet/version.py
0e03a9d35749aef5d396e532d5ab8c5a0bae223f
[ "Apache-2.0" ]
permissive
Deep-Spark/DeepSparkHub
eb5996607e63ccd2c706789f64b3cc0070e7f8ef
9d643e88946fc4a24f2d4d073c08b05ea693f4c5
refs/heads/master
2023-09-01T11:26:49.648759
2023-08-25T01:50:18
2023-08-25T01:50:18
534,133,249
7
6
Apache-2.0
2023-03-28T02:54:59
2022-09-08T09:07:01
Python
UTF-8
Python
false
false
529
py
# Copyright (c) OpenMMLab. All rights reserved. __version__ = '2.24.0' short_version = __version__ def parse_version_info(version_str): version_info = [] for x in version_str.split('.'): if x.isdigit(): version_info.append(int(x)) elif x.find('rc') != -1: patch_version = x.split('rc') version_info.append(int(patch_version[0])) version_info.append(f'rc{patch_version[1]}') return tuple(version_info) version_info = parse_version_info(__version__)
e899adf45b545c621a8fdd0259a32756768af161
de311a98efad18542b5ff87bd962957404eb3635
/blog/admin.py
1d264e7bb3d2dc9583f82e09eea5000845957f93
[]
no_license
aggressxve/my-first-blog
6b8a5a49ed18b36bafeee74436350fce5dbf94ac
4ee010ef5c6715bd3196cfb2e9eec03216f41722
refs/heads/master
2022-11-05T16:22:50.939627
2020-05-28T21:26:23
2020-05-28T21:26:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
143
py
from django.contrib import admin from .models import Post admin.site.register(Post) #Hace posible ver los modelos Post en la página del admin
63e3fa0e7d86c5133e69ba329a533e4edfdc34c1
0d4ec25fb2819de88a801452f176500ccc269724
/sub_two_binaries.py
d4f6682fa6bf8cad577240ddabce0a9eaa7818a1
[]
no_license
zopepy/leetcode
7f4213764a6a079f58402892bd0ede0514e06fcf
3bfee704adb1d94efc8e531b732cf06c4f8aef0f
refs/heads/master
2022-01-09T16:13:09.399620
2019-05-29T20:00:11
2019-05-29T20:00:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
596
py
class Solution: def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ s = "" a,b = a[::-1], b[::-1] la,lb = len(a), len(b) l = max(la, lb) i = 0 carry = 0 while i<l or carry==1: b1 = int(a[i] if i<la else 0) b2 = int(b[i] if i<lb else 0) curbit = b1^b2^carry carry = (b1&b2)|(carry&(b1|b2)) s += str(curbit) # print(curbit, carry) i+=1 return s[::-1] a,b="000", "000000" print(Solution().addBinary(a,b))
93c12e2a331418525af23fd8dcef829c87bdcb39
508ebe7c64faa6ac4498e5d4e7dbd38c405e908e
/d03/DefDemo2.py
44f2b3bc6782a6dd557510aa5a78c11c03b63638
[]
no_license
YuukiHi7/Python0709
34acdd3190c4c9862b596de42bd9bc235c4f18e5
68284f9140ad198ad8cad933dfa5d05e53a9ee34
refs/heads/master
2022-11-24T12:58:37.132550
2020-07-14T14:03:01
2020-07-14T14:03:01
278,379,789
0
0
null
null
null
null
UTF-8
Python
false
false
135
py
def printBMI(h, w): bmi = w / ((h / 100) ** 2) print("%.2f" % bmi) printBMI(170, 60) printBMI(180, 63) printBMI(8848, 156000)
cc5695f1470140f25b2cb77800818102059fa4d6
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/kdhgEC2ECXAfoXWQP_1.py
18cfc39baa91a8ce324e7628429be8a4c0702226
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
1,119
py
""" In this challenge, you have to obtain a sentence from the elements of a given matrix. In the matrix, each word of the sentence follows a columnar order from the top to the bottom, instead of the usual left-to-right order: it's time for **transposition**! Given a matrix `mtx`, implement a function that returns the complete sentence as a string, with the words separated by a space between them. ### Examples transpose_matrix([ ["Enter"], ["the"], ["Matrix!"] ]) ➞ "Enter the Matrix!" transpose_matrix([ ["The", "are"], ["columns", "rows."] ]) ➞ "The columns are rows." transpose_matrix([ ["You", "the"], ["must", "table"], ["transpose", "order."] ]) ➞ "You must transpose the table order." ### Notes * All given matrices are regular, as to say that each column has the same length. * Punctuation is already given, you just have to add the spaces in the returned string. """ def transpose_matrix(mtx): result = "" for i in range(len(mtx[0])): for j in mtx: result += j[i]+" " return result[:-1]
7144fa783f63ad2515e8c682849e12400d6df0b0
06ff1c8056cf5408e6acd5396d4c2ea4fb50cd92
/02Fabryka/Students/2019/JarzembinskiBartlomiej/factory_with_class_registration_reflection/food_store.py
bfaa1ab6718a1a0fe0b1b674d581c7eeade619c4
[]
no_license
kasa4565/DesignPatterns
b654dc8072940634ffcae52d297dc7da5d93c0b2
56dfac636b49266aa86f5b61cce0f9fb76a2b859
refs/heads/master
2020-08-23T08:10:09.661667
2019-08-15T07:54:30
2019-08-15T07:54:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
737
py
from menu.food import Food from threading import Lock class FoodStore: _instances = {} _threading_lock = Lock() _registered_products = {} def __new__(cls): if type(object.__new__(cls)).__name__ not in cls._instances: with cls._threading_lock: if type(object.__new__(cls)).__name__ not in cls._instances: cls._instances[type(object.__new__(cls)).__name__] = object.__new__(cls) return cls._instances[type(object.__new__(cls)).__name__] @classmethod def register_product(cls, food_type, food_class): cls._registered_products[food_type] = food_class @classmethod def order_food(cls, food_type): klasa = cls._registered_products[food_type] food = klasa() return food
9a996997ae3b80d18109ce7c1d13e7c1ad21d73d
c2de6f699faa6cd79897c57895677d35f28bcea4
/arena.py
a3955b65b1d853c6ac3dfe3a4f04e10f52793956
[]
no_license
RippleEcho/Darwin-Bot
679f43ee3fc2e1fbc53e2e31d37f05d03194816c
57e9f5c2457a3f39952c3dce47813266ba6efcdf
refs/heads/master
2022-05-26T19:16:32.694138
2020-05-01T16:39:30
2020-05-01T16:39:30
259,056,334
0
1
null
null
null
null
UTF-8
Python
false
false
3,901
py
from repbot import repbot from datetime import datetime import random import math class arena: def __init__(self): self.A=0 def setup(self,N,M,R,G,F): if(F): TS=datetime.now().strftime('%Y-%m-%d') file=open(TS+" Minds.txt" ,"a+") #file.write(TS) #file.write("\n") file.close() B=[] C=[] for n in range(N): B.append(self.genbot()) for g in range(G): C.clear() for n in range(N): C.append(M) K=self.tourn(B,C,R,file) W=K.index(max(K)) A=sorted(K) A.reverse() if(max(K)>=sum(K)/2 or A[0] >= A[1]*1.5): #print("writen to file") file=open(TS+" Minds.txt" ,"a+") file.write("Score: "+str(max(K))+" / "+str(sum(K))+"\n") file.write("Gen: "+str(g)+" / "+str(G)+"\n") file.write(str(B[W].mind)+"\n\n") file.close() if(g<G-1): B=self.evolve(B,K) print(B[W].mind) def genbot(self): BMS="" random.seed() for h in range(216): BMS=BMS+str(random.randint(0,5)) return repbot(BMS) def tourn(self,B,C,R,F): for N in range(R): D=self.Round(B,C) C=self.Judge(B,D,sum(C)) W=C.index(max(C)) H,Q=0,0 A=sorted(C) A.reverse() for q in range(int(len(B)/4)): Q+=A[q] for h in range(int(len(B)/2)): H+=A[h] print(A) #print("Top sing: " +str(max(C))+" / "+str(sum(C))) #print("Top quar: " +str(Q)+" / "+str(sum(C))) #print("Top half: " +str(H)+" / "+str(sum(C))) #print(B[W].sout(B[W].mind)) #print(B[W].reduce()) return C def evolve(self,B,C): #in:bots, bot counts #out:new bots R=int(len(B)/8) for h in range(R*2): L=C.index(min(C)) B.pop(L) C.pop(L) W=C.index(max(C)) for g in range(R): B.append(repbot(B[W].sout(B[W].muta()))) for f in range(R): B.append(self.genbot()) return B def Round(self,B,C): #in:bots, bot counts #out:points for bots E=[] P=[] for N in range(len(B)): P.append(0) #print(C) for M in range(C[N]): E.append((B[N],N)) F=random.sample(E,len(E)) S=[] for t in range(0,len(F),2): u=random.randint(90,110) r=self.Match(F[t][0],F[t+1][0],u) S.append(r[0]) S.append(r[1]) for T in range(len(F)): P[F[T][1]]+=S[T] return P def Judge(self,B,P,T): #in: bots, points, pool size #out: new copy nums S=sum(P) c=[] if(S==0): for g in range(len(B)): c.append(int(T/len(B))) return c for g in range(len(B)): c.append(int(math.floor(P[g]/S)*T)) while(sum(c)<T): d=random.randint(0,len(B)) v=1.00 for h in range(len(B)): if(P[h]==0): k=1.00 else: k=float(c[h]/P[h])*float(T/(len(B))) if(k<v and P[h]!=0): d=h v=k c[d]+=1 return c def Match(self, A, B, N): AT=0 BT=0 AM=[] BM=[] while (N>0): N-=1 AX=A.work(AM,BM) BX=B.work(BM,AM) if(AX+BX<6): AT+=AX BT+=BX AM.append(AX) BM.append(BX) return(AT,BT) a=arena() a.setup(64,16,128,1024,True)
3da334d08f98f8cf06aa4794ea35ab1bdecc8c8a
8c8159691382ab8759ec637a97ef107ba898ad4c
/Recursive/removeInvalidParentheses.py
44953cd000adfcd6e1707c07b5da6c12c0038303
[]
no_license
windhaunting/Coding_practices
3c89cddaeb13bfe36eab7ff664d6e16d0e86d46f
8375988ac391376159438877b6729bb94340106b
refs/heads/master
2021-02-05T21:40:07.858445
2020-02-28T19:25:29
2020-02-28T19:25:29
243,836,816
0
1
null
null
null
null
UTF-8
Python
false
false
690
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 16 16:43:09 2018 @author: fubao """ #301. Remove Invalid Parentheses ''' Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. Note: The input string may contain letters other than the parentheses ( and ). Examples: "()())()" -> ["()()()", "(())()"] "(a)())()" -> ["(a)()()", "(a())()"] ")(" -> [""] ''' #reference: http://zxi.mytechroad.com/blog/searching/leetcode-301-remove-invalid-parentheses/ class Solution(object): def removeInvalidParentheses(self, s): """ :type s: str :rtype: List[str] """
367cc3c27826f4a4d5675273b24b2261a1f42cd0
b0d934c531647353c6be4800f336ad7440f8486e
/homework/workbench/ecoli_vs_salmonella_map/organize.py
7dce7a771dd43da37675a48e2e921ec78619b0ae
[]
no_license
riemaxi/data
d2a8a43cee7fa3889be0e618064bec24f2ae1286
d165c6075aaf4857d2787b6aaa35c32e45292575
refs/heads/master
2021-01-20T13:56:41.530472
2019-03-14T17:09:02
2019-03-14T17:09:02
90,539,168
0
0
null
null
null
null
UTF-8
Python
false
false
946
py
#!/usr/bin/env python3 import dataset as ds import math def stdv(mean,n, lst): return math.sqrt( sum([(float(c)-mean)**2 for c in lst])/(n-1) ) def level(s,c,maxc, stdvc): return stdvc/(abs(maxc - c) + stdvc) # Creates the header for the next step: filter # The header is composed by three values separated by tabs: maximum, mean and standard deviation for the mapping size path = 'report.map' report = 'heatmap.txt' lst = [] c = 0 maxc = float('-inf') for line in open(path): rid, qid, cnt, rs, re, qs,qe, score = line.strip().split('\t') cnt = int(cnt) maxc = max(maxc, cnt) c += cnt lst += [(rid, qid, cnt, float(score))] # prints the header n = len(lst) stdvc = stdv(c/n,n,[f[2] for f in lst]) # prints the list with open(report,'w') as file: for rid, qid, cnt , score in lst: if cnt>0: rec = '{}\t{}\t{:0.4f}'.format(rid, qid, 100 * (score/cnt) * level(score,cnt,maxc, stdvc)) file.write(rec + '\n') print(rec)
913bbc59abbd821c216bcbc35c9af61164b9c8fd
f60dceca03f3fdf0ea7d9d5aec97255db282651f
/Raspberry/modules/Classifieur.py
5895f76033831de6b39f87225042524adcaabada
[]
no_license
Alois41/cat-feeder
5812144e2e0233f650d7382f9ebdc36ce909e6c4
28af5329ade86dff07cc33cbba27dc7e1227e9e1
refs/heads/master
2023-02-19T04:55:23.308851
2021-01-20T10:01:16
2021-01-20T10:01:16
331,250,190
0
0
null
null
null
null
UTF-8
Python
false
false
475
py
import torch import torch.nn as nn from torchvision import transforms import ast model = torch.hub.load('pytorch/vision:v0.6.0', 'mobilenet_v2', pretrained=True) model.eval() preprocess = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) file = open("../classes", "r") contents = file. read() classes = ast.literal_eval(contents)
40d3da02df59b62aa82d58dea2b9128eec39654b
f4655d85ac03e7f6999e590bdfad81adcc0399b8
/predicates/dictionaries/tagger/sqlparsing.py
e95c8a72010dae06dac3cdb1245c3b9c601a1270
[]
no_license
petezh/RR-NLP-Tools
3ad767de5b56a8ac7a59c7f2e41da8918db98570
ee7094b5660b3e92e8ff1b114029afe1964642fc
refs/heads/master
2020-06-06T16:47:59.501188
2019-08-29T20:55:39
2019-08-29T20:55:39
192,795,569
3
1
null
null
null
null
UTF-8
Python
false
false
904
py
import sqlite3 con = sqlite3.connect("data.db") cur = con.cursor() buildVerbTable("test verbs.csv", "verbs") buildDataTable("testdata.csv", "data") def buildVerbTable(in_csv, out_table): tableBuild="CREATE TABLE IF NOT EXISTS "+out_table+""" ( word VARCHAR(50), form1 VARCHAR(50), form2 VARCHAR(50), form3 VARCHAR(50), form4 VARCHAR(50), form5 VARCHAR(50), form6 VARCHAR(50), form7 VARCHAR(50), form8 VARCHAR(50), form9 VARCHAR(50)) """ cur.execute(tableBuild) for row in csv.reader(open(in_csv, 'r')): cur.execute('INSERT INTO '+out_table+' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', tuple(row[1:])) def buildDataTable(in_csv, out_table): tableBuild="CREATE TABLE "+out_table+""" ( sentence VARCHAR(300)) """ cur.execute(tableBuild) for row in csv.reader(open(in_csv, 'r')): cur.execute('INSERT INTO '+out_table+' VALUES (?)',[row[0]])
c5d4fd9d5264c1d3d95f7b448f79aaa0a7128412
756afdbd0edfec18b32d4d842a1263ae6f12fd46
/create_room.py
ca38a653904bb256c53ad6bd3e0e2de52675b7df
[]
no_license
LoukaOctave/devasc-skills
93e3dcf0294494fd36453f3fd662a709ceedda67
438bbe0f8d53bd2216e7850c1373cdc351742124
refs/heads/main
2023-07-15T18:46:23.844782
2021-08-19T22:03:45
2021-08-19T22:03:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,128
py
import requests ### Edit these variables room_name = 'netacad_devasc_skills_LO' new_member_email = '[email protected]' ### # Gets access token from file with open('token') as t: access_token = t.read() t.close() # Created a room url = 'https://webexapis.com/v1/rooms' headers = { 'Authorization': 'Bearer {}'.format(access_token), 'Content-Type': 'application/json' } params = {'title': room_name} res = requests.post(url, headers=headers, json=params) if res.status_code == 200: print('Room "' + res.json()['title'] + '" created') room_id = res.json()['id'] with open('latest_room', 'w') as r: r.write(room_id) else: print(res.json()) room_id = '' # Adds a user to that room url = 'https://webexapis.com/v1/memberships' headers = { 'Authorization': 'Bearer {}'.format(access_token), 'Content-Type': 'application/json' } params = {'roomId': room_id, 'personEmail': new_member_email} res = requests.post(url, headers=headers, json=params) if res.status_code == 200: print('User ' + res.json()['personDisplayName'].title() + ' added to room') else: print(res.json())
0b4285bff2df5cd19b3e3e2f31c78b854999b8f5
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/65/usersdata/185/34920/submittedfiles/investimento.py
c02de528254c4d919d01652089a4c2aa1ade2813
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
515
py
# -*- coding: utf-8 -*- from __future__ import division i0=float(input('digite o valor do investimesnto:')) taxa=float(input('digite o valor da taxa:')) i1=(i0+(i0*taxa)) i2=(i1+(i1*taxa)) i3=(i2+(i2*taxa)) i4=(i3+(i3*taxa)) i5=(i4+(i4*taxa)) i6=(i5+(i5*taxa)) i7=(i6+(i6*taxa)) i8=(i7+(i7*taxa)) i9=(i8+(i8*taxa)) i10=(i9+(i9*taxa)) print('%.2f' %i1) print('%.2f' %i2) print('%.2f' %i3) print('%.2f' %i4) print('%.2f' %i5) print('%.2f' %i6) print('%.2f' %i7) print('%.2f' %i8) print('%.2f' %i9) print('%.2f' %i10)
a3851be4eb6d2054a8720bb7b9d73755c14c0d53
fceb3c57a882a10fe9c06e3baf8aceb975c66d5a
/EDPwd.py
1a4de5b07b12227a4455ecf6b4d9e4f97b369950
[]
no_license
ESSAMAMI/ThefThor-REST-API
d7d0a30ec43b5c10fa54870de9b7c601c77c8187
8bde89fcc9ba4561557d1a362ab87e145ab0bb58
refs/heads/main
2023-06-05T22:29:28.729796
2021-07-03T13:50:45
2021-07-03T13:50:45
382,623,530
0
0
null
null
null
null
UTF-8
Python
false
false
1,180
py
from cryptography.fernet import Fernet import os import pathlib class EncryptDecryptPwd(): def __init__(self): pass def generate_key(self): """ Generates a key and save it into a file """ key = Fernet.generate_key() with open("secret.key", "wb") as key_file: key_file.write(key) def load_key(self): """ Load the previously generated key """ return open("secret.key", "rb").read() def encrypt_pwd(self, message): """ Encrypts a message """ secret = pathlib.Path("secret.key") if not secret.exists(): self.generate_key() key = self.load_key() encoded_message = message.encode() f = Fernet(key) encrypted_message = f.encrypt(encoded_message) print(encrypted_message) return encrypted_message def decrypt_pwd(self,encrypted_message): """ Decrypts an encrypted message """ key = self.load_key() f = Fernet(key) decrypted_message = f.decrypt(encrypted_message) return decrypted_message
6017ff5d62258b8bdc613d2deb7b6f19177ac641
d01fa1b6668c66236405b799e39e529d1492af7c
/{{cookiecutter.project_slug}}/pages/migrations/0016_sitebranding.py
9068f89e8055a2b76d16b1f85251befee436df7b
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
chrisdev/wagtail-cookiecutter-foundation
426ffd974aa08ab10e4b0e44d5003476c597f2e4
e7d56ee01eb5976588129d7bd4d5fc6dab2d794a
refs/heads/master
2023-08-31T06:05:43.999253
2022-03-31T18:44:37
2022-03-31T18:44:37
33,870,540
189
72
MIT
2023-09-14T03:30:34
2015-04-13T13:36:50
Python
UTF-8
Python
false
false
1,105
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-10-10 14:02 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wagtailimages', '0019_delete_filter'), ('wagtailcore', '0040_page_draft_title'), ('pages', '0015_advert_button_text'), ] operations = [ migrations.CreateModel( name='SiteBranding', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('site_name', models.CharField(blank=True, max_length=250, null=True)), ('logo', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailimages.Image')), ('site', models.OneToOneField(editable=False, on_delete=django.db.models.deletion.CASCADE, to='wagtailcore.Site')), ], options={ 'abstract': False, }, ), ]
65b3b7c3f22755d3319a4ba0322bf2bf04e98c87
bf76559fd0cd55854c39f3fd40aa9eb050905253
/watchbuy.py
d85f9da1f128e27bf393d81cb948e2d57f3c42cc
[]
no_license
JohnCho92/watchbuyers-companion
39728452b4a1368499374e0aa478dc4595486e96
3bfcca7b50f061fa517e41110b6f5017b1059904
refs/heads/master
2020-09-26T07:54:55.807229
2019-11-24T22:59:59
2019-11-24T22:59:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,901
py
''' Watchbuyer's Companion Author: Jasen Chan TODO: - add regular expressions for crown&caliber - show which marketplace has better prices - change prices for new, box, papers etc - OPTIMIZE: this is just a barebones working version of the program; many optimizations can be made on the regexs, and possibly on stringbuilding COMPLETED: - ** fix bug where searches don't work for models chrono24 already has defined... - fix 'orient bambino glitch' - solution: problem was that old regex wouldn't work when there weren't commas in the price; new regex created - when searching e.g. 'omega seamaster', chrono24 will redirect from the search url to another url with the watch brand and model defined - add convert to price string i.e. '12333' -> '$12,333' ''' import re import urllib2 siteRegex = { 'chrono24':{ 'redirect':'\-\-mod\d*(?!\&)', 'totalResults':'(?<=<span class=\"total-count\">)(?<!,)(\d{1,3}(?:,\d{3})*)(?!,)', 'itemSplit':'<div class=\"article-item-container\">[\r\n]*.*[\r\n]*.*[\r\n]*.*[\r\n]*.*[\r\n]*.*[\r\n]*.*[\r\n]*.*[\r\n]*.*[\r\n]*.*[\r\n]*.*[\r\n]*.*[\r\n]*.*[\r\n]*.*', 'priceSplit':'(?<=<span class=\"currency\">\$<\/span>)(?<!,)(\d{1,3}(?:,\d{3})*)(?!,)' } } siteURLs = { 'chrono24':{ 'main':'https://www.chrono24.com/search/index.htm?accessoryTypes=&dosearch=true&query=', 'pageIndex':'&showpage=', 'condition_new':'&usedOrNew=new', 'condition_used':'&usedOrNew=used', 'condition_all':'&usedOrNew=used&usedOrNew=new' } } def commaSeparatedPrice(num): # TODO: make this function take into account decimal places or standardize the way decimal places are handled numList = list(format(num,'0.2f')) counter = 1 numCommas = 0 for i in range(0,len(numList) - 4): # -4 to take into account decimal and padding if counter % 3 == 0: numList.insert(len(numList) - 4 - i - numCommas, ',') counter = 1 numCommas = numCommas + 1 continue counter = counter + 1 return "".join(numList) # convert thousands separated number e.g. '1,234' to int e.g. '1234' def commaStringToInt(value): return int("".join(str(value).split(","))) # get average of a list def getAverage(valueList): return sum(valueList)/len(valueList) # get the median value of a list def getMedian(valueList): valueList.sort() if len(valueList) < 1: return 0 valueList.sort() centerIndexFloat = len(valueList)/2.0 centerIndexInt = len(valueList)/2 if centerIndexFloat > centerIndexInt: return valueList[centerIndexInt] else: return (valueList[centerIndexInt] + valueList[centerIndexInt-1])/2.0 # scrape prices recursively off of a url; currently configured for chrono24; returns a list with 2 values: [# of valid watches found, summed price of all watches] def scrapePrices(searchString,iteration,sourceSite,condition='condition_all',numIncluded=0,totalPrice=0): # reference global variables global allPrices, allPrices_new, allPrices_old # reformat the query from "xx xx xxx" to "xx+xx+xxx" searchStringReformatted = "+".join(searchString.split(' ')) if sourceSite == 'chrono24': targetURL = siteURLs['chrono24']['main'] + searchStringReformatted + siteURLs['chrono24']['pageIndex'] + str(iteration) + siteURLs['chrono24'][condition] #print "Attempting to scrape from page " + targetURL urlData = urllib2.urlopen(targetURL) # handle case where target page gets redirected if sourceSite == 'chrono24': if len(re.findall(siteRegex[sourceSite]['redirect'],urlData.geturl())) > 0: #print "Redirected to " + urlData.geturl() splitUrl = re.split(siteRegex[sourceSite]['redirect'],urlData.geturl()) targetMod = re.search(siteRegex[sourceSite]['redirect'],urlData.geturl()).group(0) targetURL = splitUrl[0] + targetMod + "-" + str(iteration) + splitUrl[1] #print "Attempting to scrape from page " + targetURL urlData = urllib2.urlopen(targetURL) rawData = urlData.read() # create progress update totalResultsCount = re.findall(siteRegex[sourceSite]['totalResults'],rawData) # handle case where page after last has no counts try: totalResultsCount = totalResultsCount[0] except IndexError: totalResultsCount = '0' # display percentage completed if iteration == 1: totalResults = commaStringToInt(totalResultsCount) print "Found a total of " + str(totalResults) + (" watch" if totalResults == 1 else " watches") else: totalResults = commaStringToInt(totalResultsCount) print "Analyzed " + str(numIncluded) + " out of " + str(totalResults) + (" watch" if totalResults == 1 else " watches") + "(" + format(100 * (float(numIncluded)/float((totalResults if totalResults > 0 else 1))),'0.1f') + "%)" # split the target watches on the page with all data; ends at article-price-container div pageItemsSplit = re.findall(siteRegex[sourceSite]['itemSplit'],rawData) #print pageItemsSplit, len(pageItemsSplit) # turn the split items into a single string for further regex analysis pageItemsString = "".join(pageItemsSplit) # parse the prices from the containers rawPrices = re.findall(siteRegex[sourceSite]['priceSplit'],pageItemsString) # reformat the prices from '\d\d,\d\d\d' to int \d\d\d\d\d prices = [commaStringToInt(i) for i in rawPrices] allPrices += prices #print prices, len(prices), iteration, numIncluded, totalPrice print "Analyzing " + str(len(prices)) + " watches on page " + str(iteration) + "..." # if watch prices are returned, recursively call this function again if len(prices) <= 0: return [numIncluded,totalPrice] #print iteration, numIncluded, totalPrice return scrapePrices(searchString, iteration+1, sourceSite, condition, numIncluded + len(prices), totalPrice + sum(prices)) def generateReport(data): print "Average price of " + str(data[0]) + " \'" + query + "\' watch" + ("" if data[0] == 1 else "es") + " is $" + commaSeparatedPrice(data[1]/(data[0] if data[0] > 0 else 1)) #print allPrices #getMedian(allPrices) print "Median price of " + str(data[0]) + " \'" + query + "\' watch" + ("" if data[0] == 1 else "es") + " is $" + commaSeparatedPrice(getMedian(allPrices)) print "Lowest price of " + str(data[0]) + " \'" + query + "\' watch" + ("" if data[0] == 1 else "es") + " is $" + commaSeparatedPrice(allPrices[0] if len(allPrices) > 0 else 0) print "Highest price of " + str(data[0]) + " \'" + query + "\' watch" + ("" if data[0] == 1 else "es") + " is $" + commaSeparatedPrice(allPrices[len(allPrices)-1] if len(allPrices) > 0 else 0) # declare global list with all the prices seen allPrices = [] # get input query query = raw_input("Query: ") # scrape website print "Initiation chrono24 scrape..." # scrape new watches data_new = scrapePrices(query, 1, 'chrono24','condition_new') print "New " + query + " watches" generateReport(data_new) # scrape used watches allPrices = [] data_used = scrapePrices(query, 1, 'chrono24', 'condition_used') print "Used " + query + " watches" generateReport(data_used)
ed7c268914766a48037a427fadc8a0e0ca235bd8
2d568df57271f7db9d9bb7fb95c3f71e3330ff5b
/pygis2/merginShapeFil_gdal.py
56e72398c50cc2a69bb7b694a0f114b9ef8703af
[]
no_license
lamhydro/pygis
a4f493dc57d94e8a4832d4a060a2dce5c1c8d6df
f7567392bdafbcc0c2a6a4ee6ddd2543e08345a1
refs/heads/master
2023-03-14T11:24:25.126186
2021-03-01T03:19:16
2021-03-01T03:19:16
343,274,578
0
0
null
null
null
null
UTF-8
Python
false
false
1,131
py
# Merging shapefiles using GDAL/ORG # Opening ESRI shapefile. Return the shapefile driver of file and its layer. def openingShpFile(file): driver = ogr.GetDriverByName('ESRI Shapefile') shapefile = driver.Open(file, 0) if shapefile is None: print 'Could not open file' sys.exit(1) # Opening a layer return shapefile, shapefile.GetLayer(0) import os, sys from fnmatch import fnmatch if "C:\\Python27\\ArcGIS10.1\\Lib\\site-packages" not in sys.path: sys.path.append("C:\\Python27\\ArcGIS10.1\\Lib\\site-packages") from osgeo import ogr from osgeo import osr # set the working directory locDir = "Z:\\Luis\\STATSGO\\merge_ussoilsAndcasoils" os.chdir(locDir) # Merge two files with different attributes nameMergedFile = 'ussoils_casoils.shp' mergedFile = os.path.join(locDir, nameMergedFile) # - This file 'merge.vrt' is created with the names of the two shapefiles that are going to be merged. merge_vrt = 'Z:\Luis\STATSGO\merge_ussoilsAndcasoils\merge.vrt' cmd = 'ogr2ogr ' +' "' + mergedFile + '" ' + merge_vrt # merge.shp merge.vrt print cmd print os.system(cmd)
952ab841e5c96cbd7cd5c41fa5d8236831707234
aabec0a1423de60561955c8a9cf0e78c6c08e405
/project/views.py
f23b4b9bfbc6650e1f2306fb5bf04e326fbf95de
[]
no_license
BhateB/Project_API
f914d22614403298c85ed30199a33f6f0785d819
fd3f0c2c1aaf75f4f6e6f155b269e3c33b8a4bd0
refs/heads/master
2022-12-10T10:35:13.895400
2019-10-17T12:59:46
2019-10-17T12:59:46
215,604,709
0
0
null
null
null
null
UTF-8
Python
false
false
7,338
py
from django.db.models import Q, F from rest_framework import status from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import TokenAuthentication from rest_framework.response import Response from rest_framework.generics import CreateAPIView, RetrieveUpdateDestroyAPIView from django.shortcuts import get_object_or_404 from django.db import transaction from .serializers import * from marketing.models import Submission from django.contrib.contenttypes.models import ContentType from attachments.models import Attachment from utils_app.mailing import send_email_attachment_multiple from marketing.views import discord_webhook class ProjectView(RetrieveUpdateDestroyAPIView, CreateAPIView): serializer_class = ProjectSerializer create_serializer_class = ProjectCreateSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) @staticmethod def mail(self, request, submission, po_type): try: mail_data = { 'to': ['[email protected]'], 'subject': 'Offer letter', 'template': 'po_created.html', 'context': { 'marketer_name': submission.marketer, 'consultant_name': submission.consultant.consultant.name, 'consultant_email': submission.consultant.consultant.email, 'vendor_name': submission.lead.vendor.name, 'vendor_email': submission.lead.vendor.email, 'vendor_number': submission.lead.vendor.number, 'client_name': submission.client, 'client_address': self.location + self.city, 'type': po_type, 'start': request['start_time'], 'rate': submission.rate, 'payment_term': '', 'invoicing_period': '', 'con_rate': int(submission.consultant.consultant.rate), 'job_title': submission.lead.job_title, 'employer': submission.employer, } } # send_email_attachment_multiple(mail_data) return mail_data except Exception as error: return Response({"error": str(error)}, status=status.HTTP_400_BAD_REQUEST) def get(self, request, *args, **kwargs): project_id = request.query_params.get('project_id', None) query = request.query_params.get('query', None) page = int(request.query_params.get("page", 1)) last, first = page * 10, page * 10 - 10 try: if project_id: project = get_object_or_404(Project, id=project_id) serializer = self.serializer_class(project) return Response({"result": serializer.data}, status=status.HTTP_200_OK) elif query: project = Project.objects.filter( Q(submission__lead__marketer=request.user) & ( Q(submission__consultant__consultant__name__istartswith=query) | Q(submission__client__istartswith=query) ) ) else: project = Project.objects.filter(submission__lead__marketer__team=request.user.team) total = project.count() joined = project.filter(status='joined').count() not_joined = project.filter(status='not_joined').count() extended = project.filter(status='extended').count() data_count = { 'total': total, 'joined': joined, 'not_joined': not_joined, 'extended': extended } data = project[first:last].annotate( consultant_name=F('submission__consultant__consultant__name'), company_name=F('submission__lead__vendor__company__name'), marketer_name=F('submission__lead__marketer__full_name'), client=F('submission__client'), rate=F('submission__rate'), ).values('id', 'client', 'rate', 'consultant_name', 'marketer_name', 'company_name') return Response({"results": data, "counts": data_count}, status=status.HTTP_200_OK) except Exception as error: return Response({"error": str(error)}, status=status.HTTP_400_BAD_REQUEST) @transaction.atomic def create(self, request, *args, **kwargs): sub_id = request.data.get('submission') try: sub = get_object_or_404(Submission, id=sub_id) if sub.status == 'project': return Response({"error": "Project already exist"}, status=status.HTTP_406_NOT_ACCEPTABLE) serializer = self.create_serializer_class(data=request.data, partial=True) if serializer.is_valid(): serializer.save() content_type = ContentType.objects.get(model='project') # file = request.FILES.get('file', None) # if file: # Attachment.objects.create( # object_id=serializer['id'], # content_type=content_type, # attachment_type=request.data['attachment_type'], # attachment_file=file, # creator=request.user # ) project = Project.objects.get(id=serializer.data['id']) sub.status = 'project' sub.consultant.consultant.status = 'on_project' sub.save() text = "**Employer -\t {0} \nMarketer Name - {1} \nConsultant Name - {2} \nClient - \t{3} \n" \ "Technology Role - {4} \nLocation - \t{5} \nStart Date - \t{6} \n"\ .format(project.team, project.marketer, project.consultant, project.submission.client, project.submission.lead.job_title, project.city, str(project.start_time.date())) content = "**Offer**" discord_webhook(project.team, content, text) # self.mail(serializer.data, sub, 'created') return Response({"result": serializer.data}, status=status.HTTP_201_CREATED) return Response({"error": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) except Exception as error: return Response({"error": str(error)}, status=status.HTTP_400_BAD_REQUEST) def update(self, request, *args, **kwargs): try: project = get_object_or_404(Project, id=request.data.get("project_id")) serializer = self.create_serializer_class(project, data=request.data, partial=True) if serializer.is_valid(): serializer.save() sub = get_object_or_404(Submission, id=serializer.data["submission"]) self.mail(serializer.data, sub, 'updated') return Response({"result": serializer.data}, status=status.HTTP_201_CREATED) return Response({"error": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) except Exception as error: return Response({"error": str(error)}, status=status.HTTP_400_BAD_REQUEST)
682e1e44855b34b074466e3e4fd9684b1ef7e368
2d165722d96188714421aea64899081d227b88f3
/husky/build/catkin_generated/stamps/Project/_setup_util.py.stamp
896fd636cc3780ae3b210b43db0b4b5c4f699bfc
[]
no_license
anoop-ra/final
80dea439a1848388fe098fa6c3acc26f6ffce05e
e97822b659463efce42cc453b84ad0a54d0f74c5
refs/heads/master
2020-03-25T00:32:04.026194
2018-08-01T18:09:42
2018-08-01T18:09:42
143,191,085
0
0
null
null
null
null
UTF-8
Python
false
false
12,437
stamp
#!/usr/bin/python # -*- coding: utf-8 -*- # Software License Agreement (BSD License) # # Copyright (c) 2012, Willow Garage, Inc. # All rights reserved. # # 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 Willow Garage, Inc. 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. '''This file generates shell code for the setup.SHELL scripts to set environment variables''' from __future__ import print_function import argparse import copy import errno import os import platform import sys CATKIN_MARKER_FILE = '.catkin' system = platform.system() IS_DARWIN = (system == 'Darwin') IS_WINDOWS = (system == 'Windows') # subfolder of workspace prepended to CMAKE_PREFIX_PATH ENV_VAR_SUBFOLDERS = { 'CMAKE_PREFIX_PATH': '', 'LD_LIBRARY_PATH' if not IS_DARWIN else 'DYLD_LIBRARY_PATH': ['lib', os.path.join('lib', 'x86_64-linux-gnu')], 'PATH': 'bin', 'PKG_CONFIG_PATH': [os.path.join('lib', 'pkgconfig'), os.path.join('lib', 'x86_64-linux-gnu', 'pkgconfig')], 'PYTHONPATH': 'lib/python2.7/dist-packages', } def rollback_env_variables(environ, env_var_subfolders): ''' Generate shell code to reset environment variables by unrolling modifications based on all workspaces in CMAKE_PREFIX_PATH. This does not cover modifications performed by environment hooks. ''' lines = [] unmodified_environ = copy.copy(environ) for key in sorted(env_var_subfolders.keys()): subfolders = env_var_subfolders[key] if not isinstance(subfolders, list): subfolders = [subfolders] value = _rollback_env_variable(unmodified_environ, key, subfolders) if value is not None: environ[key] = value lines.append(assignment(key, value)) if lines: lines.insert(0, comment('reset environment variables by unrolling modifications based on all workspaces in CMAKE_PREFIX_PATH')) return lines def _rollback_env_variable(environ, name, subfolders): ''' For each catkin workspace in CMAKE_PREFIX_PATH remove the first entry from env[NAME] matching workspace + subfolder. :param subfolders: list of str '' or subfoldername that may start with '/' :returns: the updated value of the environment variable. ''' value = environ[name] if name in environ else '' env_paths = [path for path in value.split(os.pathsep) if path] value_modified = False for subfolder in subfolders: if subfolder: if subfolder.startswith(os.path.sep) or (os.path.altsep and subfolder.startswith(os.path.altsep)): subfolder = subfolder[1:] if subfolder.endswith(os.path.sep) or (os.path.altsep and subfolder.endswith(os.path.altsep)): subfolder = subfolder[:-1] for ws_path in _get_workspaces(environ, include_fuerte=True, include_non_existing=True): path_to_find = os.path.join(ws_path, subfolder) if subfolder else ws_path path_to_remove = None for env_path in env_paths: env_path_clean = env_path[:-1] if env_path and env_path[-1] in [os.path.sep, os.path.altsep] else env_path if env_path_clean == path_to_find: path_to_remove = env_path break if path_to_remove: env_paths.remove(path_to_remove) value_modified = True new_value = os.pathsep.join(env_paths) return new_value if value_modified else None def _get_workspaces(environ, include_fuerte=False, include_non_existing=False): ''' Based on CMAKE_PREFIX_PATH return all catkin workspaces. :param include_fuerte: The flag if paths starting with '/opt/ros/fuerte' should be considered workspaces, ``bool`` ''' # get all cmake prefix paths env_name = 'CMAKE_PREFIX_PATH' value = environ[env_name] if env_name in environ else '' paths = [path for path in value.split(os.pathsep) if path] # remove non-workspace paths workspaces = [path for path in paths if os.path.isfile(os.path.join(path, CATKIN_MARKER_FILE)) or (include_fuerte and path.startswith('/opt/ros/fuerte')) or (include_non_existing and not os.path.exists(path))] return workspaces def prepend_env_variables(environ, env_var_subfolders, workspaces): ''' Generate shell code to prepend environment variables for the all workspaces. ''' lines = [] lines.append(comment('prepend folders of workspaces to environment variables')) paths = [path for path in workspaces.split(os.pathsep) if path] prefix = _prefix_env_variable(environ, 'CMAKE_PREFIX_PATH', paths, '') lines.append(prepend(environ, 'CMAKE_PREFIX_PATH', prefix)) for key in sorted([key for key in env_var_subfolders.keys() if key != 'CMAKE_PREFIX_PATH']): subfolder = env_var_subfolders[key] prefix = _prefix_env_variable(environ, key, paths, subfolder) lines.append(prepend(environ, key, prefix)) return lines def _prefix_env_variable(environ, name, paths, subfolders): ''' Return the prefix to prepend to the environment variable NAME, adding any path in NEW_PATHS_STR without creating duplicate or empty items. ''' value = environ[name] if name in environ else '' environ_paths = [path for path in value.split(os.pathsep) if path] checked_paths = [] for path in paths: if not isinstance(subfolders, list): subfolders = [subfolders] for subfolder in subfolders: path_tmp = path if subfolder: path_tmp = os.path.join(path_tmp, subfolder) # skip nonexistent paths if not os.path.exists(path_tmp): continue # exclude any path already in env and any path we already added if path_tmp not in environ_paths and path_tmp not in checked_paths: checked_paths.append(path_tmp) prefix_str = os.pathsep.join(checked_paths) if prefix_str != '' and environ_paths: prefix_str += os.pathsep return prefix_str def assignment(key, value): if not IS_WINDOWS: return 'export %s="%s"' % (key, value) else: return 'set %s=%s' % (key, value) def comment(msg): if not IS_WINDOWS: return '# %s' % msg else: return 'REM %s' % msg def prepend(environ, key, prefix): if key not in environ or not environ[key]: return assignment(key, prefix) if not IS_WINDOWS: return 'export %s="%s$%s"' % (key, prefix, key) else: return 'set %s=%s%%%s%%' % (key, prefix, key) def find_env_hooks(environ, cmake_prefix_path): ''' Generate shell code with found environment hooks for the all workspaces. ''' lines = [] lines.append(comment('found environment hooks in workspaces')) generic_env_hooks = [] generic_env_hooks_workspace = [] specific_env_hooks = [] specific_env_hooks_workspace = [] generic_env_hooks_by_filename = {} specific_env_hooks_by_filename = {} generic_env_hook_ext = 'bat' if IS_WINDOWS else 'sh' specific_env_hook_ext = environ['CATKIN_SHELL'] if not IS_WINDOWS and 'CATKIN_SHELL' in environ and environ['CATKIN_SHELL'] else None # remove non-workspace paths workspaces = [path for path in cmake_prefix_path.split(os.pathsep) if path and os.path.isfile(os.path.join(path, CATKIN_MARKER_FILE))] for workspace in reversed(workspaces): env_hook_dir = os.path.join(workspace, 'etc', 'catkin', 'profile.d') if os.path.isdir(env_hook_dir): for filename in sorted(os.listdir(env_hook_dir)): if filename.endswith('.%s' % generic_env_hook_ext): # remove previous env hook with same name if present if filename in generic_env_hooks_by_filename: i = generic_env_hooks.index(generic_env_hooks_by_filename[filename]) generic_env_hooks.pop(i) generic_env_hooks_workspace.pop(i) # append env hook generic_env_hooks.append(os.path.join(env_hook_dir, filename)) generic_env_hooks_workspace.append(workspace) generic_env_hooks_by_filename[filename] = generic_env_hooks[-1] elif specific_env_hook_ext is not None and filename.endswith('.%s' % specific_env_hook_ext): # remove previous env hook with same name if present if filename in specific_env_hooks_by_filename: i = specific_env_hooks.index(specific_env_hooks_by_filename[filename]) specific_env_hooks.pop(i) specific_env_hooks_workspace.pop(i) # append env hook specific_env_hooks.append(os.path.join(env_hook_dir, filename)) specific_env_hooks_workspace.append(workspace) specific_env_hooks_by_filename[filename] = specific_env_hooks[-1] env_hooks = generic_env_hooks + specific_env_hooks env_hooks_workspace = generic_env_hooks_workspace + specific_env_hooks_workspace count = len(env_hooks) lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_COUNT', count)) for i in range(count): lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_%d' % i, env_hooks[i])) lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_%d_WORKSPACE' % i, env_hooks_workspace[i])) return lines def _parse_arguments(args=None): parser = argparse.ArgumentParser(description='Generates code blocks for the setup.SHELL script.') parser.add_argument('--extend', action='store_true', help='Skip unsetting previous environment variables to extend context') return parser.parse_known_args(args=args)[0] if __name__ == '__main__': try: try: args = _parse_arguments() except Exception as e: print(e, file=sys.stderr) sys.exit(1) # environment at generation time CMAKE_PREFIX_PATH = '/home/anoop/mybot_ws/devel;/opt/ros/kinetic'.split(';') # prepend current workspace if not already part of CPP base_path = os.path.dirname(__file__) if base_path not in CMAKE_PREFIX_PATH: CMAKE_PREFIX_PATH.insert(0, base_path) CMAKE_PREFIX_PATH = os.pathsep.join(CMAKE_PREFIX_PATH) environ = dict(os.environ) lines = [] if not args.extend: lines += rollback_env_variables(environ, ENV_VAR_SUBFOLDERS) lines += prepend_env_variables(environ, ENV_VAR_SUBFOLDERS, CMAKE_PREFIX_PATH) lines += find_env_hooks(environ, CMAKE_PREFIX_PATH) print('\n'.join(lines)) # need to explicitly flush the output sys.stdout.flush() except IOError as e: # and catch potential "broken pipe" if stdout is not writable # which can happen when piping the output to a file but the disk is full if e.errno == errno.EPIPE: print(e, file=sys.stderr) sys.exit(2) raise sys.exit(0)
9d04c029711c160f3fc3d500e9135ec8d10faa34
9e5dc6943bd73ef19876eefe6b4ce39722fa1af9
/tests/test_pytorch2caffes.py
ba4d3a983ab0186822bcffc9855ff80fe08c6359
[]
no_license
UmboCV/onnx-caffe
a0649cfb1c7d35f7dd772f56baecbff427b98b3e
74ce1fbeb6a16e098650fe215d2083f01fe48ed2
refs/heads/dev
2021-07-06T10:24:38.218506
2018-10-23T00:15:00
2018-10-23T00:34:53
146,048,022
7
1
null
2019-03-26T07:30:00
2018-08-24T23:18:10
Python
UTF-8
Python
false
false
1,615
py
#!/usr/bin/env python from __future__ import absolute_import # pytorch -> onnx --> caffe --> (pb2, prototxt) file import numpy as np import onnx import os import pytest from common import testset, simple # ONNX generic @pytest.fixture(params=['caffe']) def backend(request): from onnx_caffe import backend as caffe_backend return caffe_backend def test_caffes_result(backend, testset): _model, _input, _output = testset prepared_backend = backend.prepare(_model) # Run the net: output = prepared_backend.run(_input)[0] np.testing.assert_almost_equal(_output, output, decimal=3) print(_output, output) print("Exported model has been executed on Caffe2 backend, and the result looks good!") def test_caffe_save_model(testset, request): model_dir = '.caffe_model/' + request.node.name + '/' if not os.path.exists(model_dir): os.makedirs(model_dir) # Apply the optimization on the original model onnx_model, _, _ = testset with open(model_dir + '/optimized_model.onnx', 'wb') as f: onnx.save(onnx_model, f) with open(model_dir + '/optimized_model.onnx.txt', 'w') as f: f.write(onnx.helper.printable_graph(onnx_model.graph)) for i, v in enumerate(onnx_model.graph.value_info): f.write("{}\n{}\n----".format(i, v)) from onnx_caffe import CaffeBackend caffemodel = CaffeBackend.onnx_graph_to_caffemodel(onnx_model.graph, prototxt_save_path=model_dir + '/optimized_model.prototxt') caffemodel.save(model_dir + '/optimized_model.caffemodel')
32443a280de93e0a4e418e0eb590554bbb3f99b0
84b70a03236590c962b9f29d639afc34ec31f0b7
/renduFinal/tests/exemple.py
636efa20692352c69a05c031df38aaeb527eef8a
[]
no_license
JulienAdrienCeline/tpCompil
04ded4ad0c7b60dcbf30cd6a08172392f399ad8c
e2eab5b4b43b9ba7ee83ffadc09e492924f8a180
refs/heads/master
2020-05-31T05:25:55.722745
2015-05-04T10:24:10
2015-05-04T10:24:10
33,997,722
0
0
null
null
null
null
UTF-8
Python
false
false
203
py
a = 3 b = 9 def fac(i,j): c = 5 d = 12 if(c < 10): c = 8 print d print c def triple(i): print 3*i fac(a,b) if(a < 10): print a if(b < 10): print b triple(b) if(a < 5): print a print a
e54991386218ddb04789aec57658012036dbfdf2
5c0493d7951e58758734c96a9f032d6c4bd81a88
/toh/hero/migrations/0001_initial.py
5591d157f6dc649b965305157665c53bdf899e3b
[]
no_license
ihatedebug/swpp2020-django-practice
0946fb995f3732483ce6ae70de8131692714191f
3c2a3bbd8aff7d1158e790591129f4547f1d9d74
refs/heads/main
2022-12-24T15:31:21.711764
2020-10-15T14:48:50
2020-10-15T14:48:50
304,278,015
0
0
null
2020-10-15T09:38:41
2020-10-15T09:38:40
null
UTF-8
Python
false
false
484
py
# Generated by Django 3.0.3 on 2020-10-15 10:41 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Hero', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=120)), ], ), ]
1ea382c2fc6c2ec0d464fd19f2ad02fc75054f27
755ae8334ec6df9d44e0f9bb263aa0227df3ca95
/algoxpert/validate_subsequence.py
f0e87021505c62cbfe35441ac0cd9e85090e7ac7
[]
no_license
adeoti-ade/coursera-algo-challenge
4a1b445c7dd5a47b61ca45bcbaa2c3aeedc3d042
2ae8490deb280f0a3298deb5e5de280b2f3cc062
refs/heads/main
2023-08-30T14:05:51.669681
2021-11-13T04:34:45
2021-11-13T04:34:45
409,127,768
0
0
null
null
null
null
UTF-8
Python
false
false
551
py
class ValidateSubsequence: def __init__(self, array, sequence): self.array = array self.sequence = sequence def first_method(self): seq_idx = 0 array_idx = 0 while array_idx < len(self.array) and seq_idx < len(self.sequence): if self.array[array_idx] == self.sequence[seq_idx]: seq_idx += 1 array_idx += 1 return seq_idx == len(self.sequence) validate = ValidateSubsequence([5, 1, 22, 25, 6, -1, 8, 10], [1, 6, -1, 10]) print(validate.first_method())
5bad366d4a602d27d7277289398a5575abb3d140
16b19ab9b1b3a957eb8b002d12415a88d20fb738
/delete_images.py
f6d48cff209b80e5a601c59a5f601f8598599462
[]
no_license
vvs14/python-utilities
6f41a23b638d6073edd28b9c4abd7fe8b8b9437d
56178f7306b542e4e2697c9b1b9754f05012dc5b
refs/heads/master
2021-01-21T13:03:08.899622
2017-09-25T15:37:33
2017-09-25T15:37:33
54,792,807
0
0
null
null
null
null
UTF-8
Python
false
false
869
py
''' @author Vivek Vikram Singh @date 26.03.2016 Program to Delete all image files in given Directory and all of its sub directories. To input correct directory path : go to that directory, right click on any file and see the path. Give that path in input. Can be used to remove images from a directory where images are not required among all other files. ''' import os from os.path import exists import time import imghdr root_dir = raw_input("Enter the directory path : ") for curr_dir, sub_dirs, files in os.walk(root_dir): print "Current Directory is : ", curr_dir time.sleep(1) for file_item in files: fname = os.path.join(curr_dir,file_item) img_type = imghdr.what(fname) if os.path.exists(fname): if img_type: print "Deleting : ",fname os.remove(fname) else: print fname ," is not Image file." else: print "File does not exist"
2e329c5f09c70f172be9bb6c6f526dac5da7c9ed
6b42891bfbd430638be7d800dd02d95c27183ad8
/adinv/migrations/0005_auto__add_advert__add_field_adslot_ad_chooser.py
552352ce78bb0733b1260396a65a3df162e6f33e
[]
no_license
carlio/django-adinv
bf6123d0ad8f0b2a42efa132f638e319d4f0c68f
e5356ccc4e8991166b5dcdd025da01e7263a3aeb
refs/heads/master
2020-05-17T20:27:47.029126
2012-12-01T13:48:43
2012-12-01T13:48:43
5,946,359
0
1
null
null
null
null
UTF-8
Python
false
false
2,812
py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Advert' db.create_table('adinv_advert', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=200)), ('dimensions', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['adinv.SlotDimensions'])), ('code', self.gf('django.db.models.fields.TextField')()), ('enabled', self.gf('django.db.models.fields.BooleanField')(default=True)), )) db.send_create_signal('adinv', ['Advert']) # Adding field 'AdSlot.ad_chooser' db.add_column('adinv_adslot', 'ad_chooser', self.gf('django.db.models.fields.CharField')(default='', max_length=100), keep_default=False) def backwards(self, orm): # Deleting model 'Advert' db.delete_table('adinv_advert') # Deleting field 'AdSlot.ad_chooser' db.delete_column('adinv_adslot', 'ad_chooser') models = { 'adinv.adslot': { 'Meta': {'object_name': 'AdSlot'}, 'ad_chooser': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'dimensions': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['adinv.SlotDimensions']", 'null': 'True'}), 'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slot_name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) }, 'adinv.advert': { 'Meta': {'object_name': 'Advert'}, 'code': ('django.db.models.fields.TextField', [], {}), 'dimensions': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['adinv.SlotDimensions']"}), 'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'adinv.slotdimensions': { 'Meta': {'object_name': 'SlotDimensions'}, 'height': ('django.db.models.fields.SmallIntegerField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'width': ('django.db.models.fields.SmallIntegerField', [], {}) } } complete_apps = ['adinv']
512cccdff042b753e66c88811c3fe1daaa5ce10b
d488f052805a87b5c4b124ca93494bc9b78620f7
/google-cloud-sdk/lib/googlecloudsdk/command_lib/accesscontextmanager/zones.py
7769f86c280257e290b19cd283c994d3d59183d5
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
PacktPublishing/DevOps-Fundamentals
5ce1fc938db66b420691aa8106ecfb3f9ceb1ace
60597e831e08325c7e51e8557591917f7c417275
refs/heads/master
2023-02-02T04:48:15.346907
2023-01-30T08:33:35
2023-01-30T08:33:35
131,293,311
13
19
null
null
null
null
UTF-8
Python
false
false
7,142
py
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Command line processing utilities for access zones.""" from googlecloudsdk.api_lib.accesscontextmanager import util from googlecloudsdk.calliope.concepts import concepts from googlecloudsdk.command_lib.accesscontextmanager import common from googlecloudsdk.command_lib.accesscontextmanager import levels from googlecloudsdk.command_lib.accesscontextmanager import policies from googlecloudsdk.command_lib.util.apis import arg_utils from googlecloudsdk.command_lib.util.args import repeated from googlecloudsdk.command_lib.util.concepts import concept_parsers from googlecloudsdk.core import resources REGISTRY = resources.REGISTRY def AddAccessLevels(ref, args, req): if args.IsSpecified('access_levels'): access_levels = [] for access_level in args.access_levels: level_ref = resources.REGISTRY.Create( 'accesscontextmanager.accessPolicies.accessLevels', accessLevelsId=access_level, **ref.Parent().AsDict()) access_levels.append(level_ref.RelativeName()) req.accessZone.accessLevels = access_levels return req def AddImplicitServiceWildcard(ref, args, req): """Add an implicit wildcard for services if they are modified. If either restricted services or unrestricted services is given, the other must also be provided as a wildcard (`*`). If neither is given, this is a no-op. Args: ref: resources.Resource, the (unused) resource args: argparse namespace, the parse arguments req: AccesscontextmanagerAccessPoliciesAccessZonesCreateRequest Returns: The modified request. """ del ref # Unused in AddImplicitServiceWildcard if args.IsSpecified('restricted_services'): req.accessZone.unrestrictedServices = ['*'] elif args.IsSpecified('unrestricted_services'): req.accessZone.restrictedServices = ['*'] return req def _GetAttributeConfig(): return concepts.ResourceParameterAttributeConfig( name='zone', help_text='The ID of the access zone.' ) def _GetResourceSpec(): return concepts.ResourceSpec( 'accesscontextmanager.accessPolicies.accessZones', resource_name='zone', accessPoliciesId=policies.GetAttributeConfig(), accessZonesId=_GetAttributeConfig()) def AddResourceArg(parser, verb): """Add a resource argument for an access zone. NOTE: Must be used only if it's the only resource arg in the command. Args: parser: the parser for the command. verb: str, the verb to describe the resource, such as 'to update'. """ concept_parsers.ConceptParser.ForResource( 'zone', _GetResourceSpec(), 'The access zone {}.'.format(verb), required=True).AddToParser(parser) def GetTypeEnumMapper(): return arg_utils.ChoiceEnumMapper( '--type', util.GetMessages().AccessZone.ZoneTypeValueValuesEnum, custom_mappings={ 'ZONE_TYPE_REGULAR': 'regular', 'ZONE_TYPE_BRIDGE': 'bridge' }, required=False, help_str="""\ Type of the zone. A *regular* zone allows resources within this access zone to import and export data amongst themselves. A project may belong to at most one regular access zone. A *bridge* access zone allows resources in different regular access zones to import and export data between each other. A project may belong to multiple bridge access zones (only if it also belongs to a regular access zone). Both restricted and unrestricted service lists, as well as access level lists, must be empty. """, ) def AddZoneUpdateArgs(parser): """Add args for zones update command.""" args = [ common.GetDescriptionArg('access zone'), common.GetTitleArg('access zone'), GetTypeEnumMapper().choice_arg ] for arg in args: arg.AddToParser(parser) _AddResources(parser) _AddUnrestrictedServices(parser) _AddRestrictedServices(parser) _AddLevelsUpdate(parser) def _AddResources(parser): repeated.AddPrimitiveArgs( parser, 'zone', 'resources', 'resources', additional_help=('Resources must be projects, in the form ' '`project/<projectnumber>`.')) def ParseResources(args, zone_result): return repeated.ParsePrimitiveArgs( args, 'resources', zone_result.GetAttrThunk('resources')) def _AddUnrestrictedServices(parser): repeated.AddPrimitiveArgs( parser, 'zone', 'unrestricted-services', 'unrestricted services', metavar='SERVICE', additional_help=( 'The zone boundary DOES NOT apply to these services (for example, ' '`storage.googleapis.com`). A wildcard (```*```) may be given to ' 'denote all services.\n\n' 'If restricted services are set, unrestricted services must be a ' 'wildcard.')) def ParseUnrestrictedServices(args, zone_result): return repeated.ParsePrimitiveArgs( args, 'unrestricted_services', zone_result.GetAttrThunk('unrestrictedServices')) def _AddRestrictedServices(parser): repeated.AddPrimitiveArgs( parser, 'zone', 'restricted-services', 'restricted services', metavar='SERVICE', additional_help=( 'The zone boundary DOES apply to these services (for example, ' '`storage.googleapis.com`). A wildcard (```*```) may be given to ' 'denote all services.\n\n' 'If unrestricted services are set, restricted services must be a ' 'wildcard.')) def ParseRestrictedServices(args, zone_result): return repeated.ParsePrimitiveArgs( args, 'restricted_services', zone_result.GetAttrThunk('restrictedServices')) def _AddLevelsUpdate(parser): repeated.AddPrimitiveArgs( parser, 'zone', 'access-levels', 'access levels', metavar='LEVEL', additional_help=( 'An intra-zone request must satisfy these access levels (for ' 'example, `MY_LEVEL`; must be in the same access policy as this ' 'zone) to be allowed.')) def _GetLevelIdFromLevelName(level_name): return REGISTRY.Parse(level_name, collection=levels.COLLECTION).accessLevelsId def ParseLevels(args, zone_result, policy_id): level_ids = repeated.ParsePrimitiveArgs( args, 'access_levels', zone_result.GetAttrThunk('accessLevels', transform=_GetLevelIdFromLevelName)) if level_ids is None: return None return [REGISTRY.Create(levels.COLLECTION, accessPoliciesId=policy_id, accessLevelsId=l) for l in level_ids]
7e29e532d2f1285cd50e39b2cb2212b658e5b9a8
149db911cd5b9f404e5d74fd6c8ed047482d2c22
/backend/menu/migrations/0001_initial.py
2c07fd16d8ed613c8286821c487d80336fef03b4
[]
no_license
crowdbotics-apps/bigbitesgrill-22907
45814458930ad7aed64a1f4941aabd930f1f2587
6cd1b7b663de21c7587cdbce1612c4807e2cc5f6
refs/heads/master
2023-01-14T05:10:18.129338
2020-11-23T03:27:17
2020-11-23T03:27:17
315,189,727
0
0
null
null
null
null
UTF-8
Python
false
false
3,144
py
# Generated by Django 2.2.17 on 2020-11-23 03:26 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('delivery_user_profile', '0001_initial'), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('description', models.TextField()), ('image', models.URLField()), ('icon', models.URLField()), ], ), migrations.CreateModel( name='Country', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('description', models.TextField()), ('prefix', models.CharField(max_length=8)), ('flag', models.URLField()), ], ), migrations.CreateModel( name='Item', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('description', models.TextField()), ('image', models.URLField()), ('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='item_category', to='menu.Category')), ], ), migrations.CreateModel( name='Review', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('rating', models.FloatField()), ('review_text', models.TextField()), ('timestamp_created', models.DateTimeField(auto_now_add=True)), ('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='review_item', to='menu.Item')), ('profile', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='review_profile', to='delivery_user_profile.Profile')), ], ), migrations.CreateModel( name='ItemVariant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('description', models.TextField()), ('price', models.FloatField()), ('image', models.URLField()), ('country', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='itemvariant_country', to='menu.Country')), ('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='itemvariant_item', to='menu.Item')), ], ), ]
bed06b0ef7c181eeae4f298e82e61e87e8d795b5
bb2507bb1757462e931b339bab6a59c877171a00
/src/models/archieved/efficientnetlite1.py
a263d3500cf905aff06805b92a440060dacd6bf1
[]
no_license
el16y2w/Mobile-Pose
ddc515ae2321ea2b7fbbb2b69e947ccedcd24cb6
14b0e27fe2631d4ad0f8cf7dfc2c3f06671c0670
refs/heads/master
2023-01-04T01:23:34.914151
2020-10-30T07:44:46
2020-10-30T07:44:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,026
py
import os import config import tensorflow as tf import tensorflow.contrib.slim as slim import models.efficientnet.lite.efficientnet_lite_builder as efficientnet_lite_builder from models.outputlayer import finallayerforoffsetoption class EfficientNetLite1: def __init__(self, shape,is4Train=True,model_name = "efficientnet-lite2", totalJoints=13): tf.reset_default_graph()# 利用这个可清空default graph以及nodes outputlayer = finallayerforoffsetoption() self.model_name = model_name self.inputImage = tf.placeholder(tf.float32, shape=shape, name='Image') output , endpoints = efficientnet_lite_builder.build_model(images=self.inputImage, model_name=self.model_name, training=is4Train, fine_tuning=False, features_only=True) self.output = outputlayer.fornetworks_DUC(output,totalJoints) def getInput(self): return self.inputImage def getOutput(self): return self.output
bd21f9f9fa89f4649931f3c82b4fec92d0236194
f085db42060d1616fcd4e1808cd1b8d6dc0fc913
/beluga/continuation/ContinuationSolution.py
32fe96a3d4e0a8b98ab3036cb4d04465fed94bec
[ "MIT" ]
permissive
thomasantony/beluga
415aabc955a3ff08639e275f70a3608d0371b6b8
070c39476e07a6d5e900a2f9b3cd21c0ae7f9fe7
refs/heads/master
2021-09-04T20:13:40.757066
2018-01-22T02:40:34
2018-01-22T02:40:34
118,074,853
3
1
null
2018-01-19T04:00:09
2018-01-19T04:00:09
null
UTF-8
Python
false
false
43
py
class ContinuationSolution(list): pass
adf6af0524df6ab886504be487d226bb8e2ea86d
eb9c3dac0dca0ecd184df14b1fda62e61cc8c7d7
/google/ads/googleads/v4/googleads-py/tests/unit/gapic/googleads.v4/services/test_ad_parameter_service.py
738eff76504f6163898c0336379da593536d1d5b
[ "Apache-2.0" ]
permissive
Tryweirder/googleapis-gen
2e5daf46574c3af3d448f1177eaebe809100c346
45d8e9377379f9d1d4e166e80415a8c1737f284d
refs/heads/master
2023-04-05T06:30:04.726589
2021-04-13T23:35:20
2021-04-13T23:35:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
34,565
py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os from unittest import mock import grpc import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from google import auth from google.ads.googleads.v4.resources.types import ad_parameter from google.ads.googleads.v4.services.services.ad_parameter_service import AdParameterServiceClient from google.ads.googleads.v4.services.services.ad_parameter_service import transports from google.ads.googleads.v4.services.types import ad_parameter_service from google.api_core import client_options from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.auth import credentials from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account from google.protobuf import field_mask_pb2 as field_mask # type: ignore from google.protobuf import wrappers_pb2 as wrappers # type: ignore from google.rpc import status_pb2 as status # type: ignore def client_cert_source_callback(): return b"cert bytes", b"key bytes" # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT def test__get_default_mtls_endpoint(): api_endpoint = "example.googleapis.com" api_mtls_endpoint = "example.mtls.googleapis.com" sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" assert AdParameterServiceClient._get_default_mtls_endpoint(None) is None assert AdParameterServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint assert AdParameterServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint assert AdParameterServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint assert AdParameterServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint assert AdParameterServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi def test_ad_parameter_service_client_from_service_account_info(): creds = credentials.AnonymousCredentials() with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: factory.return_value = creds info = {"valid": True} client = AdParameterServiceClient.from_service_account_info(info) assert client.transport._credentials == creds assert client.transport._host == 'googleads.googleapis.com:443' def test_ad_parameter_service_client_from_service_account_file(): creds = credentials.AnonymousCredentials() with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: factory.return_value = creds client = AdParameterServiceClient.from_service_account_file("dummy/file/path.json") assert client.transport._credentials == creds client = AdParameterServiceClient.from_service_account_json("dummy/file/path.json") assert client.transport._credentials == creds assert client.transport._host == 'googleads.googleapis.com:443' def test_ad_parameter_service_client_get_transport_class(): transport = AdParameterServiceClient.get_transport_class() assert transport == transports.AdParameterServiceGrpcTransport transport = AdParameterServiceClient.get_transport_class("grpc") assert transport == transports.AdParameterServiceGrpcTransport @mock.patch.object(AdParameterServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AdParameterServiceClient)) def test_ad_parameter_service_client_client_options(): # Check that if channel is provided we won't create a new one. with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.AdParameterServiceClient.get_transport_class') as gtc: transport = transports.AdParameterServiceGrpcTransport( credentials=credentials.AnonymousCredentials() ) client = AdParameterServiceClient(transport=transport) gtc.assert_not_called() # Check that if channel is provided via str we will create a new one. with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.AdParameterServiceClient.get_transport_class') as gtc: client = AdParameterServiceClient(transport="grpc") gtc.assert_called() # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceGrpcTransport.__init__') as grpc_transport: grpc_transport.return_value = None client = AdParameterServiceClient(client_options=options) grpc_transport.assert_called_once_with( ssl_channel_credentials=None, credentials=None, host="squid.clam.whelk", client_info=transports.base.DEFAULT_CLIENT_INFO, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT # is "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceGrpcTransport.__init__') as grpc_transport: grpc_transport.return_value = None client = AdParameterServiceClient() grpc_transport.assert_called_once_with( ssl_channel_credentials=None, credentials=None, host=client.DEFAULT_ENDPOINT, client_info=transports.base.DEFAULT_CLIENT_INFO, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceGrpcTransport.__init__') as grpc_transport: grpc_transport.return_value = None client = AdParameterServiceClient() grpc_transport.assert_called_once_with( ssl_channel_credentials=None, credentials=None, host=client.DEFAULT_MTLS_ENDPOINT, client_info=transports.base.DEFAULT_CLIENT_INFO, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has # unsupported value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError): client = AdParameterServiceClient() # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): with pytest.raises(ValueError): client = AdParameterServiceClient() @mock.patch.object(AdParameterServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AdParameterServiceClient)) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) @pytest.mark.parametrize("use_client_cert_env", ["true", "false"]) def test_ad_parameter_service_client_mtls_env_auto(use_client_cert_env): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceGrpcTransport.__init__') as grpc_transport: ssl_channel_creds = mock.Mock() with mock.patch('grpc.ssl_channel_credentials', return_value=ssl_channel_creds): grpc_transport.return_value = None client = AdParameterServiceClient(client_options=options) if use_client_cert_env == "false": expected_ssl_channel_creds = None expected_host = client.DEFAULT_ENDPOINT else: expected_ssl_channel_creds = ssl_channel_creds expected_host = client.DEFAULT_MTLS_ENDPOINT grpc_transport.assert_called_once_with( ssl_channel_credentials=expected_ssl_channel_creds, credentials=None, host=expected_host, client_info=transports.base.DEFAULT_CLIENT_INFO, ) # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceGrpcTransport.__init__') as grpc_transport: with mock.patch('google.auth.transport.grpc.SslCredentials.__init__', return_value=None): with mock.patch('google.auth.transport.grpc.SslCredentials.is_mtls', new_callable=mock.PropertyMock) as is_mtls_mock: with mock.patch('google.auth.transport.grpc.SslCredentials.ssl_credentials', new_callable=mock.PropertyMock) as ssl_credentials_mock: if use_client_cert_env == "false": is_mtls_mock.return_value = False ssl_credentials_mock.return_value = None expected_host = client.DEFAULT_ENDPOINT expected_ssl_channel_creds = None else: is_mtls_mock.return_value = True ssl_credentials_mock.return_value = mock.Mock() expected_host = client.DEFAULT_MTLS_ENDPOINT expected_ssl_channel_creds = ssl_credentials_mock.return_value grpc_transport.return_value = None client = AdParameterServiceClient() grpc_transport.assert_called_once_with( ssl_channel_credentials=expected_ssl_channel_creds, credentials=None, host=expected_host, client_info=transports.base.DEFAULT_CLIENT_INFO, ) # Check the case client_cert_source and ADC client cert are not provided. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceGrpcTransport.__init__') as grpc_transport: with mock.patch('google.auth.transport.grpc.SslCredentials.__init__', return_value=None): with mock.patch('google.auth.transport.grpc.SslCredentials.is_mtls', new_callable=mock.PropertyMock) as is_mtls_mock: is_mtls_mock.return_value = False grpc_transport.return_value = None client = AdParameterServiceClient() grpc_transport.assert_called_once_with( ssl_channel_credentials=None, credentials=None, host=client.DEFAULT_ENDPOINT, client_info=transports.base.DEFAULT_CLIENT_INFO, ) def test_ad_parameter_service_client_client_options_from_dict(): with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceGrpcTransport.__init__') as grpc_transport: grpc_transport.return_value = None client = AdParameterServiceClient( client_options={'api_endpoint': 'squid.clam.whelk'} ) grpc_transport.assert_called_once_with( ssl_channel_credentials=None, credentials=None, host="squid.clam.whelk", client_info=transports.base.DEFAULT_CLIENT_INFO, ) def test_get_ad_parameter(transport: str = 'grpc', request_type=ad_parameter_service.GetAdParameterRequest): client = AdParameterServiceClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.get_ad_parameter), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = ad_parameter.AdParameter( resource_name='resource_name_value', ) response = client.get_ad_parameter(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == ad_parameter_service.GetAdParameterRequest() # Establish that the response is the type that we expect. assert isinstance(response, ad_parameter.AdParameter) assert response.resource_name == 'resource_name_value' def test_get_ad_parameter_from_dict(): test_get_ad_parameter(request_type=dict) def test_get_ad_parameter_field_headers(): client = AdParameterServiceClient( credentials=credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = ad_parameter_service.GetAdParameterRequest() request.resource_name = 'resource_name/value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.get_ad_parameter), '__call__') as call: call.return_value = ad_parameter.AdParameter() client.get_ad_parameter(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( 'x-goog-request-params', 'resource_name=resource_name/value', ) in kw['metadata'] def test_get_ad_parameter_flattened(): client = AdParameterServiceClient( credentials=credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.get_ad_parameter), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = ad_parameter.AdParameter() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_ad_parameter( resource_name='resource_name_value', ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0].resource_name == 'resource_name_value' def test_get_ad_parameter_flattened_error(): client = AdParameterServiceClient( credentials=credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.get_ad_parameter( ad_parameter_service.GetAdParameterRequest(), resource_name='resource_name_value', ) def test_mutate_ad_parameters(transport: str = 'grpc', request_type=ad_parameter_service.MutateAdParametersRequest): client = AdParameterServiceClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.mutate_ad_parameters), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = ad_parameter_service.MutateAdParametersResponse( ) response = client.mutate_ad_parameters(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == ad_parameter_service.MutateAdParametersRequest() # Establish that the response is the type that we expect. assert isinstance(response, ad_parameter_service.MutateAdParametersResponse) def test_mutate_ad_parameters_from_dict(): test_mutate_ad_parameters(request_type=dict) def test_mutate_ad_parameters_field_headers(): client = AdParameterServiceClient( credentials=credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = ad_parameter_service.MutateAdParametersRequest() request.customer_id = 'customer_id/value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.mutate_ad_parameters), '__call__') as call: call.return_value = ad_parameter_service.MutateAdParametersResponse() client.mutate_ad_parameters(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( 'x-goog-request-params', 'customer_id=customer_id/value', ) in kw['metadata'] def test_mutate_ad_parameters_flattened(): client = AdParameterServiceClient( credentials=credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.mutate_ad_parameters), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = ad_parameter_service.MutateAdParametersResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.mutate_ad_parameters( customer_id='customer_id_value', operations=[ad_parameter_service.AdParameterOperation(update_mask=field_mask.FieldMask(paths=['paths_value']))], ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0].customer_id == 'customer_id_value' assert args[0].operations == [ad_parameter_service.AdParameterOperation(update_mask=field_mask.FieldMask(paths=['paths_value']))] def test_mutate_ad_parameters_flattened_error(): client = AdParameterServiceClient( credentials=credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.mutate_ad_parameters( ad_parameter_service.MutateAdParametersRequest(), customer_id='customer_id_value', operations=[ad_parameter_service.AdParameterOperation(update_mask=field_mask.FieldMask(paths=['paths_value']))], ) def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AdParameterServiceGrpcTransport( credentials=credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AdParameterServiceClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AdParameterServiceGrpcTransport( credentials=credentials.AnonymousCredentials(), ) client = AdParameterServiceClient(transport=transport) assert client.transport is transport def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AdParameterServiceGrpcTransport( credentials=credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = AdParameterServiceClient( credentials=credentials.AnonymousCredentials(), ) assert isinstance( client.transport, transports.AdParameterServiceGrpcTransport, ) @pytest.mark.parametrize("transport_class", [ transports.AdParameterServiceGrpcTransport, ]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. with mock.patch.object(auth, 'default') as adc: adc.return_value = (credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_ad_parameter_service_base_transport(): # Instantiate the base transport. with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceTransport.__init__') as Transport: Transport.return_value = None transport = transports.AdParameterServiceTransport( credentials=credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly # raise NotImplementedError. methods = ( 'get_ad_parameter', 'mutate_ad_parameters', ) for method in methods: with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) def test_ad_parameter_service_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. with mock.patch.object(auth, 'default') as adc, mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceTransport._prep_wrapped_messages') as Transport: Transport.return_value = None adc.return_value = (credentials.AnonymousCredentials(), None) transport = transports.AdParameterServiceTransport() adc.assert_called_once() def test_ad_parameter_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(auth, 'default') as adc: adc.return_value = (credentials.AnonymousCredentials(), None) AdParameterServiceClient() adc.assert_called_once_with(scopes=( 'https://www.googleapis.com/auth/adwords', )) def test_ad_parameter_service_transport_auth_adc(): # If credentials and host are not provided, the transport class should use # ADC credentials. with mock.patch.object(auth, 'default') as adc: adc.return_value = (credentials.AnonymousCredentials(), None) transports.AdParameterServiceGrpcTransport(host="squid.clam.whelk") adc.assert_called_once_with(scopes=( 'https://www.googleapis.com/auth/adwords', )) def test_ad_parameter_service_host_no_port(): client = AdParameterServiceClient( credentials=credentials.AnonymousCredentials(), client_options=client_options.ClientOptions(api_endpoint='googleads.googleapis.com'), ) assert client.transport._host == 'googleads.googleapis.com:443' def test_ad_parameter_service_host_with_port(): client = AdParameterServiceClient( credentials=credentials.AnonymousCredentials(), client_options=client_options.ClientOptions(api_endpoint='googleads.googleapis.com:8000'), ) assert client.transport._host == 'googleads.googleapis.com:8000' def test_ad_parameter_service_grpc_transport_channel(): channel = grpc.insecure_channel('http://localhost/') # Check that channel is used if provided. transport = transports.AdParameterServiceGrpcTransport( host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" assert transport._ssl_channel_credentials == None @pytest.mark.parametrize("transport_class", [transports.AdParameterServiceGrpcTransport]) def test_ad_parameter_service_transport_channel_mtls_with_client_cert_source( transport_class ): with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: with mock.patch.object(transport_class, "create_channel", autospec=True) as grpc_create_channel: mock_ssl_cred = mock.Mock() grpc_ssl_channel_cred.return_value = mock_ssl_cred mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel cred = credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): with mock.patch.object(auth, 'default') as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", api_mtls_endpoint="mtls.squid.clam.whelk", client_cert_source=client_cert_source_callback, ) adc.assert_called_once() grpc_ssl_channel_cred.assert_called_once_with( certificate_chain=b"cert bytes", private_key=b"key bytes" ) grpc_create_channel.assert_called_once_with( "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, scopes=( 'https://www.googleapis.com/auth/adwords', ), ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) assert transport.grpc_channel == mock_grpc_channel assert transport._ssl_channel_credentials == mock_ssl_cred @pytest.mark.parametrize("transport_class", [transports.AdParameterServiceGrpcTransport,]) def test_ad_parameter_service_transport_channel_mtls_with_adc( transport_class ): mock_ssl_cred = mock.Mock() with mock.patch.multiple( "google.auth.transport.grpc.SslCredentials", __init__=mock.Mock(return_value=None), ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): with mock.patch.object(transport_class, "create_channel", autospec=True) as grpc_create_channel: mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel mock_cred = mock.Mock() with pytest.warns(DeprecationWarning): transport = transport_class( host="squid.clam.whelk", credentials=mock_cred, api_mtls_endpoint="mtls.squid.clam.whelk", client_cert_source=None, ) grpc_create_channel.assert_called_once_with( "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, scopes=( 'https://www.googleapis.com/auth/adwords', ), ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) assert transport.grpc_channel == mock_grpc_channel def test_ad_group_criterion_path(): customer = "squid" ad_group_criterion = "clam" expected = "customers/{customer}/adGroupCriteria/{ad_group_criterion}".format(customer=customer, ad_group_criterion=ad_group_criterion, ) actual = AdParameterServiceClient.ad_group_criterion_path(customer, ad_group_criterion) assert expected == actual def test_parse_ad_group_criterion_path(): expected = { "customer": "whelk", "ad_group_criterion": "octopus", } path = AdParameterServiceClient.ad_group_criterion_path(**expected) # Check that the path construction is reversible. actual = AdParameterServiceClient.parse_ad_group_criterion_path(path) assert expected == actual def test_ad_parameter_path(): customer = "oyster" ad_parameter = "nudibranch" expected = "customers/{customer}/adParameters/{ad_parameter}".format(customer=customer, ad_parameter=ad_parameter, ) actual = AdParameterServiceClient.ad_parameter_path(customer, ad_parameter) assert expected == actual def test_parse_ad_parameter_path(): expected = { "customer": "cuttlefish", "ad_parameter": "mussel", } path = AdParameterServiceClient.ad_parameter_path(**expected) # Check that the path construction is reversible. actual = AdParameterServiceClient.parse_ad_parameter_path(path) assert expected == actual def test_common_billing_account_path(): billing_account = "winkle" expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) actual = AdParameterServiceClient.common_billing_account_path(billing_account) assert expected == actual def test_parse_common_billing_account_path(): expected = { "billing_account": "nautilus", } path = AdParameterServiceClient.common_billing_account_path(**expected) # Check that the path construction is reversible. actual = AdParameterServiceClient.parse_common_billing_account_path(path) assert expected == actual def test_common_folder_path(): folder = "scallop" expected = "folders/{folder}".format(folder=folder, ) actual = AdParameterServiceClient.common_folder_path(folder) assert expected == actual def test_parse_common_folder_path(): expected = { "folder": "abalone", } path = AdParameterServiceClient.common_folder_path(**expected) # Check that the path construction is reversible. actual = AdParameterServiceClient.parse_common_folder_path(path) assert expected == actual def test_common_organization_path(): organization = "squid" expected = "organizations/{organization}".format(organization=organization, ) actual = AdParameterServiceClient.common_organization_path(organization) assert expected == actual def test_parse_common_organization_path(): expected = { "organization": "clam", } path = AdParameterServiceClient.common_organization_path(**expected) # Check that the path construction is reversible. actual = AdParameterServiceClient.parse_common_organization_path(path) assert expected == actual def test_common_project_path(): project = "whelk" expected = "projects/{project}".format(project=project, ) actual = AdParameterServiceClient.common_project_path(project) assert expected == actual def test_parse_common_project_path(): expected = { "project": "octopus", } path = AdParameterServiceClient.common_project_path(**expected) # Check that the path construction is reversible. actual = AdParameterServiceClient.parse_common_project_path(path) assert expected == actual def test_common_location_path(): project = "oyster" location = "nudibranch" expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) actual = AdParameterServiceClient.common_location_path(project, location) assert expected == actual def test_parse_common_location_path(): expected = { "project": "cuttlefish", "location": "mussel", } path = AdParameterServiceClient.common_location_path(**expected) # Check that the path construction is reversible. actual = AdParameterServiceClient.parse_common_location_path(path) assert expected == actual def test_client_withDEFAULT_CLIENT_INFO(): client_info = gapic_v1.client_info.ClientInfo() with mock.patch.object(transports.AdParameterServiceTransport, '_prep_wrapped_messages') as prep: client = AdParameterServiceClient( credentials=credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) with mock.patch.object(transports.AdParameterServiceTransport, '_prep_wrapped_messages') as prep: transport_class = AdParameterServiceClient.get_transport_class() transport = transport_class( credentials=credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info)
[ "bazel-bot-development[bot]@users.noreply.github.com" ]
bazel-bot-development[bot]@users.noreply.github.com
2c69894e250cac1001e365aa618ab94646a07ca5
12e45ab1a4d996c121f7ebc6a5a60621aaba8354
/codingbat/String-1/make_tags.py
c159a0edd57c378691498f747d20cfadc4c0c00e
[]
no_license
dastan717/WedDEV
843983d27325df1684ffbdc53557942433828ae6
00406a43b28f8650bf3b5f5d61d2ab234662d09c
refs/heads/main
2023-03-13T12:37:48.636671
2021-04-02T20:31:50
2021-04-02T20:31:50
337,782,141
0
0
null
null
null
null
UTF-8
Python
false
false
67
py
def make_tags(tag, word): return "<"+tag+">"+word+"</"+tag+">"
d31eb44f23dbff95c71cf83b48b059a709466875
943f9856deb0777c49c22d0020948b4bfb4d218d
/musicConv/main/forms.py
61d79b293a7e5d19d516ad120d759dc5f5b021f9
[]
no_license
A-Aidyn/junctionX2020
c5569a437f0a56371da6e313e37ae06ce264888f
cb536451c16de50d66fc5a68cea5181581d41a10
refs/heads/main
2022-12-28T18:24:15.733643
2020-10-11T05:05:33
2020-10-11T05:05:33
302,698,477
0
1
null
2020-10-10T11:01:27
2020-10-09T16:38:02
Python
UTF-8
Python
false
false
328
py
from django import forms class DocumentForm(forms.Form): docfile = forms.FileField(widget=forms.FileInput(attrs={'class': 'upload-input', 'accept': '.mp3,audio/*', 'onchange':'selectedFileHandler()'}))
52c48698286b8482a49b52c1571e580e9aef70e3
4edde33f251e56c6433c07272375ae66f8025736
/learning_templates/basic_app/templatetags/my_extras.py
38f5e3569696c01d2462a015a693cfc5b9e13050
[]
no_license
tomthomask/django-deployment-example
a7dc460306604df24e3cc4bcecc280838500c2d7
57ececfcacb4213f3ac66c536becdaa2cdb1ece8
refs/heads/master
2022-11-30T03:35:28.768061
2020-07-28T19:26:25
2020-07-28T19:26:25
283,304,023
0
0
null
null
null
null
UTF-8
Python
false
false
244
py
from django import template register = template.Library() @register.filter(name='cut') def cut(value, arg): """ This cuts out all values of "arg" from the string! """ return value.replace(arg,'') # register.filter(cut,'cut')
78a6cf0cdb92b81e5e9348782f2384c58ed1d4ec
e76a97c024709ccca57a7ca127eb886c219563a0
/stack_180403.py
8fb01616bc960ebee4b802838f643c07d37fb2be
[ "Apache-2.0" ]
permissive
Jianyang-Hu/numpypractice
7731adc9252ac9804ecac484a491a240f4ff9567
f4d4a3e28f5dd10f9722f83b1ac66f0f2ccef8b9
refs/heads/master
2022-11-22T09:50:58.978715
2020-07-09T09:10:41
2020-07-23T14:32:51
281,971,693
0
0
null
null
null
null
UTF-8
Python
false
false
592
py
# -*- coding: utf-8 -*- # @version : Python3.6 # @Time : 2018/4/3 16:35 # @Author : Jianyang-Hu # @contact : [email protected] # @File : stack_180403.py # @Software: PyCharm import pandas as pd import numpy as np from pandas import Series,DataFrame data = DataFrame(np.arange(6).reshape(2,3), index=pd.Index(['Ohio','Coload'],name='State'), columns=pd.Index(['one','two','three'],name='number')) # print(data) print('................') #stack print(data.stack()) print('................') #unstack result = data.stack() print(result.unstack())
41ff1a640390f6409ed6908f2a856935291a5cd4
543cc60477cef7fc8cda349730f7296fdb7329d6
/genetic.py
4029c0d7d9622e4ac6faa0be6fda7157e1dd3a12
[]
no_license
cppower/abcde
f671f1ef770d8cc079238ae52d21ba3356610996
110dfa354aaf1164c365bd9eaf7e7642db5d3098
refs/heads/master
2021-01-11T04:56:10.498851
2017-02-18T20:16:42
2017-02-18T20:16:42
77,073,723
0
0
null
null
null
null
UTF-8
Python
false
false
10,276
py
from random import * from time import time from dames import testDFS NB_PARAMS = 1 TAILLE_CHROMO = 4 TAILLE_TOTALE = NB_PARAMS*TAILLE_CHROMO POPULATION = 100 MUTATION = 0.005 CROSSOVER = 0 NB_GENERATIONS = 1 resultats = [0 for i in range(0,POPULATION)] class Plateau: def __init__(self,pB= 1<<50|1<<49|1<<48|1<<47|1<<46|1<<45|1<<44|1<<43|1<<42|1<<41|1<<40|1<<39|1<<38|1<<37|1<<36|1<<35|1<<34|1<<33|1<<32|1<<31, pN=1<<20|1<<19|1<<18|1<<17|1<<16|1<<15|1<<14|1<<13|1<<12|1<<11|1<<10|1<<9|1<<8|1<<7|1<<6|1<<5|1<<4|1<<3|1<<2|1<<1, dB=0,dN=0): self.pionsBlancs=pB self.pionsNoirs=pN self.damesBlanches=dB self.damesNoires=dN INFINI=10**10 #Déplacements cat1 = [1,2,3,4,5,11,12,13,14,15,21,22,23,24,25,31,32,33,34,35,41,42,43,44,45] d1 = [-5,-4,5,6] d2 = [-6,-5,4,5] #Gestion des bords fZone = [1 ,2 , 3 ,4 ,5 ,46 , 47 ,48 ,49 ,50 ,6 ,16 ,26 ,36 ,15 ,25 ,35 ,45] vMove = [[5,6],[5,6],[5,6],[5,6],[5],[-5],[-5,-6],[-5,-6],[-5,-6],[-5,-6],[-5,5],[-5,5],[-5,5],[-5,5],[-5,5],[-5,5],[-5,5],[-5,5]] arbre = [] #© Victor Amblard history={} def minimaxAB(profondeur,nodeId, arbre,alpha,beta,color,noir): #Effectue l'algo minimax + elagage AB FONCTIONNE CORRECTEMENT global hashmap global valeurs global best_value,best_move if profondeur==4 and not noir: return arbre[nodeId][7][1]*color if profondeur==4 and noir: return arbre[nodeId][7][0]*color val=-INFINI for fils in ids: if fils%10==profondeur+1 and arbre[fils][0]==nodeId: v = -minimaxAB(profondeur+1,fils,arbre,-beta,-alpha, -color,noir) if v>val: val =v alpha = max(alpha, v) if alpha>=beta: break if profondeur==1: valeurs[nodeId]=val return val def compute_zobrist(plateau): #Fonction de hachage du damier O(n) return int(str(plateau.pionsBlancs)+str(plateau.pionsNoirs)+str(plateau.damesBlanches)+str(plateau.damesNoires)) def evalue(plateau, noir,b): #Function complete pB = plateau.pionsBlancs pN = plateau.pionsNoirs dB = plateau.damesBlanches dN = plateau.damesNoires totalB=0 totalN=0 totalB2 = 0 totalN2=0 for i in range(0, 51): if (pB>>i)%2==1: totalB+=1 totalB2+=1 elif (pN>>i)%2==1: totalN+=1 totalN2+=1 elif (dB>>i)%2==1: totalB+=b totalB2+=methode elif (dN>>i)%2==1: totalN+=b totalN2+=methode if noir: return (totalN-totalB, totalN2-totalB2) return (totalB-totalN,totalB2-totalN2) def explore(plateau,noir,b): #Function complete CAPTURE=False for i in range(1,51): if (noir and ((plateau.pionsNoirs|plateau.damesNoires)>>i)%2==1) or (not noir and ((plateau.pionsBlancs|plateau.damesBlanches)>>i)%2==1): CAPTURE = CAPTURE | prisesPossibles(i,plateau,noir,b) if not CAPTURE: for i in range(0,51): if (noir and ((plateau.pionsNoirs|plateau.damesNoires)>>i)%2==1) or (not noir and ((plateau.pionsBlancs|plateau.damesBlanches)>>i)%2==1): deplacementsPossibles(i,plateau, noir,b) def prisesPossibles(origine, plateau, noir,b): #Recherche de prise global arbre global priority dame = False if (not noir and (plateau.damesBlanches>>origine)%2==1) or (noir and (plateau.damesNoires>>origine)%2==1): dame = True if noir: chemins = testDFS.DFS(origine,plateau.pionsBlancs|plateau.damesBlanches,plateau.pionsBlancs,plateau.pionsNoirs,plateau.damesBlanches,plateau.damesNoires,dame) else: chemins = testDFS.DFS(origine,plateau.pionsNoirs|plateau.damesNoires,plateau.pionsBlancs,plateau.pionsNoirs,plateau.damesBlanches,plateau.damesNoires,dame) if chemins != []: cheminRetenu = [] maximum = 0 iMax = 0 for i in range(0,len(chemins)): if chemins[i][0]>maximum: maximum = chemins[i][0] arrivee = chemins[i][1] #puis choix des plus longs chemins iMax = i cheminRetenu = [chemins[iMax][2], chemins[iMax][3]] #print(chemins) #print(cheminRetenu) #param1: pions pris, param2 : dames prises priority = maximum nPlateau = modifieDamier(origine, "x", arrivee, plateau, noir, dame, cheminRetenu.copy()) arbre.append((origine, "x", arrivee, nPlateau, noir, priority, evalue(nPlateau,noir,b))) return True return False def deplacementsPossibles(origine, plateau, noir,b): #Function complete global arbre pB = plateau.pionsBlancs pN = plateau.pionsNoirs dB = plateau.damesBlanches dN = plateau.damesNoires dame = False if (not noir and (dB>>origine)%2==1) or (noir and (dN>>origine)%2==1): dame = True if not dame: if origine in cat1: for deplacement in d1: arrivee = origine+deplacement if ((origine not in fZone) or (origine in fZone and deplacement in vMove[fZone.index(origine)])) and arrivee>=0 and arrivee<=50: if ((pB|pN|dB|dN)>>arrivee)%2==0: if (noir and arrivee-origine>0) or (not noir and arrivee-origine<0): nplat = modifieDamier(origine, "-",arrivee, plateau, noir,False) arbre.append((origine, "-",arrivee, nplat,noir, 0, evalue(nplat, noir,b))) else: for deplacement in d2: arrivee=origine+deplacement if ((origine not in fZone) or (origine in fZone and deplacement in vMove[fZone.index(origine)])) and arrivee>=0 and arrivee<=50: if ((pB|pN|dB|dN)>>arrivee)%2==0: if (noir and arrivee-origine>0) or (not noir and arrivee-origine<0): nplat = modifieDamier(origine, "-",arrivee, plateau, noir,False) arbre.append((origine, "-", arrivee, nplat, noir, 0, evalue(nplat, noir,b))) else: for i in range(0,4): cur = origine if cur in cat1: deplacement = d1[i] else: deplacement = d2[i] while (cur not in fZone) or (cur in fZone and deplacement in vMove[fZone.index(cur)]) and cur+deplacement>=0 and cur+deplacement<=50: if ((pB|pN|dB|dN)>>(cur+deplacement))%2!=0: break #print(str(cur+deplacement)+" "+str(i)) nplat = modifieDamier (origine, "-",cur+deplacement,plateau, noir, True) arbre.append((origine, "-", cur+deplacement, nplat, noir, 0, evalue(nplat, noir,b))) if cur in cat1: deplacement = d2[i] cur += d1[i] else: deplacement = d1[i] cur+=d2[i] def modifieDamier(origine, coup, arrivee, plateau, noir, dame, chemin = None): #Function complete nPB=plateau.pionsBlancs nPN = plateau.pionsNoirs nDB = plateau.damesBlanches nDN = plateau.damesNoires if not dame: if noir: if arrivee not in [46,47,48,49,50]: #promotion blanc nPN ^= (1<<origine) nPN ^= (1<<arrivee) else: nPN ^= (1<<origine) nDN ^= (1<<arrivee) else: if arrivee not in [1,2,3,4,5]: #promotion noire nPB ^= (1<< origine) nPB ^= (1<<arrivee) else: nPB^= (1<<origine) nDB ^= (1<<arrivee) else: if noir: nDN ^= (1<<origine) nDN ^= (1<<arrivee) else: nDB ^= (1<<origine) nDB ^= (1<<arrivee) if coup == "x": for pion in chemin[0]: # Suppression des pions ennemis du plateau if noir: nPB ^= (1<<pion) else: nPN ^= (1<<pion) for dam in chemin[1]: #Suppression des dames ennemies du plateau if noir: nDB ^= (1<<dam) else: nDN ^= (1<<dam) npla = Plateau(nPB,nPN,nDB, nDN) return npla def highestPriority(plateau,noir): global arbreTotal iMax = 0 maxi = -INFINI for i in range(0,profondeurs[1]): element = arbreTotal[ids[i+1]] if element[2]=='x': if element[-2]>maxi: iMaxi=ids[i+1] maxi=element[-2] if maxi != -INFINI: return iMaxi else: a= minimaxAB(0,0,arbreTotal,-INFINI,INFINI,1,noir) maxi =-INFINI iMax = 0 for (key,val) in valeurs.items(): if val>maxi: maxi=val iMax=key return iMax def creeArbre(noir, plateau): global arbre global ids global arbreTotal global profondeurs global history profondeurs = [0 for i in range(0,10)] arbreTotal = {} arbreTotal[0]=(-INFINI,INFINI,"",-INFINI,plateau, not noir, -INFINI,-INFINI) ids = [0] deb = time() for profondeur in range(1,7): #print("------profondeur--------- "+str(profondeur)) for id in ids: if id%10 == profondeur - 1 : (dep, coup, arr,plateau, noir,evalu,priority) = (arbreTotal.get(id))[1:] noir = not noir if compute_zobrist(plateau) in history: break arbre= [] explore(plateau, noir) for elem in arbre: tmpId=randint(0,10**8) while tmpId in ids : tmpId=randint(0,10**8) newId=tmpId-(tmpId%10)+profondeur ids.append(newId) profondeurs[profondeur]+=1 arbreTotal[newId] = (id,)+elem en=time() delta=en-deb print(delta) #print(len(arbreTotal)) return arbre def play(a,b): pass def find(a): pass def initialise(): popu = [] for i in range(0,POPULATION): popu.append(randint(0,2**TAILLE_TOTALE)) return popu def fitness(i, chaine): curParams = [0 for i in range(0,NB_PARAMS)] curPl = Plateau() total=0 print(chaine) for i in range(0, NB_PARAMS): curParams[i]= (chaine>>TAILLE_CHROMO)<<TAILLE_CHROMO chaine=chaine>>TAILLE_CHROMO curParams.reverse() print(curParams) for i in range(0, 10): arbreTotal = {} priority = 0 valeurs = {} history={} priority = 0 creeArbre(True, curPl) bestMove = highestPriority(nPlateau,True) nPlateau = arbreTotal[bestMove][4] tPlateau = find(curPl) total+=(nPlateau==tPlateau) resultats[i]=total def selectionRoulette(curPop): nPop = [] somme = sum(resultats) for i in range(0,int((1-CROSSOVER)*POPULATION)): r = random() * somme s = somme c = False for i in range(0, POPULATION): s-=resultats[i] if s<=0: nPop.append(curPop[i]) c=True if not c: nPop.append(curPop[-1]) return nPop def mutation(): for i in range(0,POPULATION): for j in range(0,TAILLE_TOTALE): if random() > MUTATION: popu[i]^= (1<<j) return popu popu = initialise() for i in range(0,NB_GENERATIONS): print("Generation "+str(i)) for j in range(0, POPULATION): fitness(j, popu[j]) popu = selectionRoulette(popu) popu = mutation() #popu = crossover()
e5072b920c58d5c622ce4f52ceaa2a1322f10365
48cb0870c4c50dfc158f4be1506933540a7eb404
/interpreter/interpreter.py
624b73f6f666dd089ba9ee880fa4ec3d7c8b969b
[]
no_license
luap42/talos
79fc37ad3787501ab0e2260626b6476b943f502d
212940a9f99f160d671605c24be4c069dfc90d61
refs/heads/master
2021-06-23T03:07:23.177414
2017-09-01T14:55:41
2017-09-01T14:55:41
102,121,796
0
0
null
null
null
null
UTF-8
Python
false
false
35,624
py
import sys, copy, time from stdlib import * from lexer import * Symbols = SymbolTable() Procedures = SymbolTable() Structures = SymbolTable() Instances = SymbolTable() RANDOM_SEED = Random() OBJECT_COUNT = Random() def eval_term(term): term = [t if not t.type == "CONCRETE" else Token("EVALCONC", str(round(float(t.value), t.value.c))) for t in term] i = 0 while i < len(term): st = term[i] if st.type == "BRACK_START_SIGN": nt = [] n = 1 while n > 0: nt.append(st) del(term[i]) if i >= len(term): return Error("SyntaxError", "Unclosed bracket") st = term[i] if st.type == "BRACK_START_SIGN": n+=1 elif st.type == "BRACK_STOP_SIGN": n-=1 term[i] = eval_term(nt[1:]) if term[i].isError: return term[i] elif st.type == "BRACK_STOP_SIGN": return Error("SyntaxError", "Unopened bracket") i+=1 i = 0 while i < len(term): st = term[i] if st.type == "MINUS_SIGN" and ((term[i-1].type not in ["NUMBER", "EVALCONC", "CONCRETE"]) or i == 0): del term[i] if term[i].type == "NUMBER": term[i].value = str(-1*int(term[i].value)) elif term[i].type == "EVALCONC": term[i].value = str(-1*float(term[i].value)) elif term[i].type == "CONCRETE": term[i] = term[i].value.mod(ConcreteWrapper.froms("-1")) else: return Error("SyntaxError", "Only Numbers or Concretes may follow Negation sign") i+=1 # instance = instance_call("@init", (instance["@init"][1],args), instance, "&"+term[i].value[1:]) i = 0 while i < len(term): term[i] = solvevars(term[i]) if term[i].isError: return term[i] if term[i].type == "STRUCT_SUBITEM_SIGN": if term[i-1].type != "INSTANCE": return Error("SyntaxError", "Only objects may have subitems") if term[i+1].type not in ["FUNCTION_CALL", "VARIABLE"]: return Error("SyntaxError", "Only methods and properties are valid subitems") if term[i+1].type == "VARIABLE": tim1 = term[i-1] tip1 = term[i+1] del term[i+1] del term[i] if not Instances[tim1.value].__hasitem__(tip1.value): return Error("NotFoundError", "Property not found") term[i-1] = Instances[tim1.value][tip1.value] i-=1 else: tim1 = term[i-1] tip1 = term[i+1] if not Instances[tim1.value].__hasitem__(tip1.value): return Error("NotFoundError", "Method not found") argnum = len(Instances[tim1.value][tip1.value][1]) term_i = term[i+1] if i+argnum > len(term): return Error("ArgumentsError", "Not enough arguments for function " + term[i].value + ".") args = [] for _ in range(argnum): k+=1 args += [term[k]] ret = instance_call(tip1.value, (Instances[tim1.value][tip1.value][1],args), tim1, tim1.object) if ret[0].type=="ERROR_RETURN": return ret[0] return_ = ret[1] del term[i+1] del term[i] term[i-1] = return_ i -= 1 i += 1 if term == [None]: return Token("ARRAY", []) i = len(term) - 1 while i >= 0: if term[i].type == "FUNCTION_CALL": k = i if Structures.__hasitem__("&"+term[i].value[1:]): struct = Structures["&"+term[i].value[1:]] instance = create_instance(struct) OBJECT_COUNT.next() oc = OBJECT_COUNT.get() Instances[oc] = instance if instance.__hasitem__("@init"): argnum = len(instance["@init"][1]) term_i = term[i] if i+argnum > len(term): return Error("ArgumentsError", "Not enough arguments for function " + term[i].value + ".") args = [] for _ in range(argnum): k+=1 args += [term[k]] instance_call("@init", (instance["@init"][1],args), Token("INSTANCE", oc), "&"+term[i].value[1:]) term_i = Token("INSTANCE", oc) term_i.object = "&"+term[i].value[1:] elif term[i].value != "@random": argnum = function_parameter_number(term[i]) term_i = term[i] if i+argnum > len(term): return Error("ArgumentsError", "Not enough arguments for function " + term[i].value + ".") args = [] for _ in range(argnum): k+=1 args += [term[k]] term_i = solvefuncs(term_i, args) if term_i is not None and (term_i.type == "ERROR_RETURN" or term_i.isError): return term_i else: t = time.time() argnum = 2 if i+argnum > len(term): return Error("ArgumentsError", "Not enough arguments for function " + term[i].value + ".") args = [] for _ in range(argnum): k+=1 args += [term[k]] low, high = args term_i = Token("NUMBER", int(int(low.value)+(((t**3) / (t+(RANDOM_SEED.get()%(int(high.value)-int(low.value))))%(int(high.value)-int(low.value)))))) RANDOM_SEED.next() del term[i:k] if term_i != None and term_i.isError: return term[i] if term_i == None: del term[i] else: term[i] = term_i i-=1 if term == [None]: return Token("ARRAY", []) i = 0 while i < len(term): st = term[i] if st.type == "INDEX": if i == 0: return Error("SyntaxError", "Index cannot be first") t = term[i-1] if t.type != "ARRAY": print(term) return Error("SyntaxError", "Index must follow array") k = eval_term(lex(st.value)[0]) if k.isError: return k elif k.type != "NUMBER": return Error("SyntaxError", "Index must be number") if int(k.value) >= len(t.value): return Error("OverflowError", "Index out of range") del term[i] term[i-1] = t.value[int(k.value)] i-=1 i+=1 i = len(term) - 1 while i>=0: st = term[i] if st.type == "CAST": castto = st.value del term[i] st = term[i] if castto.endswith("[]"): if st.type != "ARRAY": return Error("UncastableError", "Cannot cast value from type `"+st.type+"` to typed array") else: if castto[:-2] == "string": st.value = [Token("STRING", str(s.value)) for s in st.value] elif castto[:-2] == "int": if None in [re.match("^[0-9]+(\.[0-9]+)?$", s.value) for s in st.value]: return Error("UncastableError", "Cannot cast to typed array when values don't match target type. Type: integer") st.value = [Token("NUMBER", int(float(s.value))) for s in st.value] elif castto[:-2] == "concrete": if None in [re.match("^[0-9]+(\.[0-9]+)?$", s.value) for s in st.value]: return Error("UncastableError", "Cannot cast to typed array when values don't match target type. Type: concrete") st.value = [ConcreteWrapper.froms(s.value) for s in st.value] st.value = [t if not t.type == "CONCRETE" else Token("EVALCONC", str(round(float(t.value), t.value.c))) for t in st.value] elif castto[:-2] == "boolean": if not False in [[s.type, s.value] in [["STRING","true"], ["STRING","false"], ["STRING","1"], ["STRING","0"], ["NUMBER","1"], ["NUMBER","0"]] for s in st.value]: st = [Token("BOOLEAN", "true") if s.value in ["true", "1"] else Token("BOOLEAN", "false") for s in st] else: return Error("UncastableError", "Cannot cast to typed array when values don't match target type. Type: boolean") else: return Error("CastTargetNotFoundError", "Cannot find cast type `"+castto[:-2]+"`") elif castto == "string": if st.type != "ARRAY": if st.type == "FILE_STREAM": st = solvefile(st) else: st.value = str(st.value) else: st.value = ", ".join([str(s.value) for s in st.value]) st.type = "STRING" elif castto == "int": if re.match("^[0-9]+(\.[0-9]+)?$", st.value): st.type = "NUMBER" st.value = str(int(float(st.value))) else: return Error("UncastableError", "Cannot cast `"+st.value+"` to integer") elif castto == "concrete": if re.match("^[0-9]+(\.[0-9]+)?$", st.value): st = ConcreteWrapper.froms(st.value) st = Token("EVALCONC", str(round(float(st.value), st.value.c))) else: return Error("UncastableError", "Cannot cast `"+st.value+"` to concrete") elif castto == "boolean": if [st.type, st.value] in [["STRING","true"], ["STRING","false"], ["STRING","1"], ["STRING","0"], ["NUMBER","1"], ["NUMBER","0"]]: if st.value in ["true", "1"]: st = Token("BOOLEAN", "true") else: st = Token("BOOLEAN", "false") else: return Error("UncastableError", "Cannot cast `"+st.type+":"+st.value+"` to boolean") elif castto == "file": if st.isError: return st if st.type == "STRING": st = Token("FILE_STREAM", st.value) else: return Error("UncastableError", "Cannot cast `"+st.type+"` to file") elif castto == "count": if st.isError: return st if st.type in ["ARRAY", "STRING"]: st = Token("NUMBER", len(st.value)) else: return Error("UncastableError", "Cannot cast `"+st.type+"` to count") else: return Error("CastTargetNotFoundError", "Cannot find cast type `"+castto+"`") term[i] = st i-=1 i = 0 while i < len(term): st = term[i] if st.type == "TIMES_SIGN": op1 = term[i-1] op2 = term[i+1] if (op1.type, op2.type) in [("NUMBER", "NUMBER"), ("STRING", "NUMBER"), ("NUMBER", "STRING"), ("NUMBER","EVALCONC"), ("EVALCONC", "EVALCONC"), ("EVALCONC", "NUMBER")]: if op1.type == op2.type == "NUMBER": res = Token("NUMBER", int(op1.value) * int(op2.value)) elif (op1.type, op2.type) == ("NUMBER", "EVALCONC") or (op1.type, op2.type) == ("EVALCONC", "EVALCONC") or (op1.type, op2.type) == ("EVALCONC", "NUMBER"): res = ConcreteWrapper.froms(str(op1.value)).value.mul(ConcreteWrapper.froms(str(op2.value)).value) elif op1.type == "STRING": if(int(op2.value)<=0): return Error("ValueError", "Cannot multiply string with negative integer or zero") res = Token("STRING", op1.value * int(op2.value)) else: if(int(op1.value)<=0): return Error("ValueError", "Cannot multiply string with negative integer or zero") res = Token("STRING", int(op1.value) * op2.value) del term[i] del term[i] term[i-1] = res i -= 1 else: return Error("TypeError", "Cannot multiply `"+op1.type+"` and `"+op2.type+"`") i += 1 i = 0 while i < len(term): st = term[i] if st.type == "BY_SIGN": op1 = term[i-1] op2 = term[i+1] if (op1.type, op2.type) in [("NUMBER", "NUMBER"), ("NUMBER","EVALCONC"), ("EVALCONC", "EVALCONC"), ("EVALCONC", "NUMBER")]: if(op1.type == op2.type == "NUMBER"): if(0 in [int(op1.value), int(op2.value)]): return Error("Div0Error", "Division by zero") res = Token("NUMBER", int(int(op1.value) / int(op2.value))) elif (op1.type, op2.type) == ("NUMBER", "EVALCONC") or (op1.type, op2.type) == ("EVALCONC", "EVALCONC") or (op1.type, op2.type) == ("EVALCONC", "NUMBER"): if 0.0 in [float(op1.value), float(op2.value)]: return Error("Div0Error", "Division by zero") res = ConcreteWrapper.froms(str(op1.value)).value.div(ConcreteWrapper.froms(str(op2.value)).value) del term[i] del term[i] term[i-1] = res i -= 1 else: return Error("TypeError", "Cannot divide `"+op1.type+"` and `"+op2.type+"`") i += 1 i = 0 while i < len(term): st = term[i] if st.type == "PLUS_SIGN": op1 = term[i-1] op2 = term[i+1] if (op1.type, op2.type) in [("NUMBER", "NUMBER"), ("NUMBER","EVALCONC"), ("EVALCONC", "EVALCONC"), ("EVALCONC", "NUMBER")] or "ARRAY" in (op1.type, op2.type) or "STRING" in (op1.type, op2.type): if (op1.type, op2.type) == ("NUMBER", "NUMBER"): res = Token("NUMBER", int(int(op1.value) + int(op2.value))) elif (op1.type, op2.type) == ("NUMBER", "EVALCONC") or (op1.type, op2.type) == ("EVALCONC", "EVALCONC") or (op1.type, op2.type) == ("EVALCONC", "NUMBER"): res = ConcreteWrapper.froms(str(op1.value)).value.add(ConcreteWrapper.froms(str(op2.value)).value) elif op1.type == "ARRAY": res = Token("ARRAY", op1.value+[op2]) elif op2.type == "ARRAY": res = Token("ARRAY", [op1]+op2.value) else: res = Token("STRING", str(op1.value) + str(op2.value)) del term[i] del term[i] term[i-1] = res i -= 1 else: return Error("TypeError", "Cannot add `"+op1.type+"` and `"+op2.type+"`") i += 1 i = 0 while i < len(term): st = term[i] if st.type == "MINUS_SIGN": op1 = term[i-1] op2 = term[i+1] if (op1.type, op2.type) in [("NUMBER", "NUMBER"), ("NUMBER","EVALCONC"), ("EVALCONC", "EVALCONC"), ("EVALCONC", "NUMBER")]: if(op1.type == op2.type == "NUMBER"): res = Token("NUMBER", int(int(op1.value) - int(op2.value))) elif (op1.type, op2.type) == ("NUMBER", "EVALCONC") or (op1.type, op2.type) == ("EVALCONC", "EVALCONC") or (op1.type, op2.type) == ("EVALCONC", "NUMBER"): res = ConcreteWrapper.froms(str(op1.value)).value.sub(ConcreteWrapper.froms(str(op2.value)).value) del term[i] del term[i] term[i-1] = res i -= 1 else: return Error("TypeError", "Cannot subtract `"+op1.type+"` and `"+op2.type+"`") i += 1 i = 0 while i < len(term): st = term[i] if st.type not in ["INSTANCE", "ARRAY"]: st = Token(st.type, str(st.value)) if not st.type == "CONCRETE" else Token("EVALCONC", str(round(float(st.value), st.value.c))) term[i] = st i+=1 if len(term) != 1: term = Token("ARRAY", term) else: term = term[0] return term def solvefile(expr): if expr.type == "FILE_STREAM": try: f = open(expr.value, "r") c = f.read() f.close() return Token("STRING", c) except: return Error("FileNotFoundError", "The file `"+expr.value+"` was not found.") return expr def solvevars(var): if var == None: return Token("NULL", None) if var.isError: return var while var.type == "VARIABLE": if Symbols.__hasitem__(var.value): var = Symbols[var.value] else: return Error("NotFoundError", "Variable not found") return var def function_parameter_number(func): if not Procedures.__hasitem__(func.value): return 0 return len(Procedures[func.value][1]) def solvefuncs(func, params=[]): if func.type != "FUNCTION_CALL": return func else: if not Procedures.__hasitem__(func.value): return Error("NotFoundError", "Function not found") return subparse(Procedures[func.value][0], "$"+func.value[1:], (Procedures[func.value][1],params)) def subparse(prod, lookforreturn, params=((),())): mProcedurestable = copy.deepcopy(Procedures.table) mSymbolstable = copy.deepcopy(Symbols.table) i = 0 for p in params[0]: Symbols[p.value] = params[1][i] i+=1 if parse(prod) == -1: return Token("ERROR_RETURN", "") return_ = None if Symbols.__hasitem__(lookforreturn): return_ = Symbols[lookforreturn] Procedures.table = copy.deepcopy(mProcedurestable) Symbols.table = copy.deepcopy(mSymbolstable) return return_ def create_instance(struct): mProcedurestable = copy.deepcopy(Procedures.table) mSymbolstable = copy.deepcopy(Symbols.table) OneStructure = SymbolTable() Procedures.table = OneStructure.table Symbols.table = OneStructure.table if parse(struct) == -1: return Token("ERROR_RETURN", "") Procedures.table = copy.deepcopy(mProcedurestable) Symbols.table = copy.deepcopy(mSymbolstable) return OneStructure def instance_call(func_name, args, obj, obj_name): func = Instances[obj.value][func_name][0] mProcedurestable = copy.deepcopy(Procedures.table) mSymbolstable = copy.deepcopy(Symbols.table) Symbols["$"+obj_name[1:]] = obj Symbols["$"+obj_name[1:]].object = obj_name i = 0 for p in args[0]: Symbols[p.value] = args[1][i] i+=1 if parse(func) == -1: return Token("ERROR_RETURN", ""), None return_ = None if Symbols.__hasitem__("$"+func_name[1:]): return_ = Symbols["$"+func_name[1:]] ret = obj Procedures.table = copy.deepcopy(mProcedurestable) Symbols.table = copy.deepcopy(mSymbolstable) return ret, return_ def parse(toks): if toks is None: return #print(toks) #return j = 0 while j < len(toks): i = 0 handled = False line = toks[j] while i < len(line): if line[i].type == "USE_STMT": handled = True if line[i+1].type != "STRING": Error("SyntaxError", "Only string may follow USE statement").printMessage() return -1 what = line[i+1].value if what.startswith("mod:"): what = what[4:] + ".talos" try: data = open_file(what) tokens = lex(data) parse(tokens) except: Error("ImportError", "Cannot load module `"+what+"`").printMessage() return -1 elif what.startswith("ext:"): Error("NotSupportedError", "TALOS-Extensions not supported yet").printMessage() return -1 else: Error("ImportTypeError", "Only mod: and ext: are valid import types").printMessage() return -1 elif line[i].type == "OUTPUT_STMT": handled = True i+=1 op = eval_term(line[i:]) if op.type == "ARRAY" and op.value == []: print() break if op.type == "ARRAY": op = Token("ARRAY", [solvefile(p) for p in op.value if p.value is not None]) else: op = (solvefile(op)) if op.isError or (op.type == "ARRAY" and True in [p.isError for p in op.value]): if op.type == "ARRAY": err = None for p in op.value: if p.isError: err = p else: err = op err.printMessage() return -1 if op.type == "ARRAY": print(", ".join([str(p.value) for p in op.value])) else: print(op.value) break elif line[i].type == "INPUT_STMT": handled = True output = line[i+2:] saveto_var = line[i+1] if saveto_var.type != "STREAM": output.insert(0, saveto_var) saveto_var = None op = eval_term(output) if op.type == "ARRAY": op = ([solvefile(p) for p in op.value if p.value is not None]) else: op = (solvefile(op)) if op.isError or (op.type == "ARRAY" and True in [p.isError for p in op.value]): if op.type == "ARRAY": err = None for p in op.value: if p.isError: err = p else: err = op err.printMessage() return -1 if op.type == "ARRAY": result = input(", ".list(join(str(op.value)))) else: result = input(op.value) if saveto_var: Symbols[saveto_var.value] = Token("STRING", result) break elif line[i].type == "FILE_WRITE_STMT": handled = True output = line[i+2:] saveto_file = line[i+1] if saveto_file.type != "STREAM": Error("SyntaxError", "fwrite needs to be followed by strean") return -1 saveto_file.type = "VARIABLE" op = eval_term(output) if op.type == "ARRAY": op = ([solvefile(p) for p in op.value if p.value is not None]) else: op = (solvefile(op)) if op.isError or (op.type == "ARRAY" and True in [p.isError for p in op.value]): if op.type == "ARRAY": err = None for p in op.value: if p.isError: err = p else: err = op err.printMessage() return -1 if op.type == "ARRAY": result = (", ".list(join(str(op.value)))) else: result = (op.value) f = open(solvevars(saveto_file).value, "w") f.write(result) f.close() saveto_file.type = "STREAM" break elif line[i].type == "EQUAL_SIGN": handled = True if line[0].type == "VARIABLE": output = line[i+1:] op = eval_term(output) if op.isError or (op.type == "ARRAY" and True in [p.isError for p in op.value]): if op.type == "ARRAY": err = None for p in op.value: if p.isError: err = p else: err = op err.printMessage() return -1 else: result = op varname = line[0] if i != 1: if Symbols.__hasitem__(varname.value): sv = solvevars(varname) k = 1 sub = None super_ = None while k < len(line[:i]): item = line[k] if item.type == "INDEX": if sv.type == "ARRAY": if int(eval_term(lex(item.value)[0]).value) > len(sv.value): Error("OverflowError", "Index out of range").printMessage() return -1 if k == len(line[:i]) - 1: super_ = sv.value sub = int(eval_term(lex(item.value)[0]).value) break else: sv = sv.value[int(eval_term(lex(item.value)[0]).value)] else: Error("SyntaxError", "Only arrays have index").printMessage() return -1 elif item.type == "STRUCT_SUBITEM_SIGN": if sv.type == "INSTANCE": if line[k+1].type == "VARIABLE": variable_name = line[k+1].value k += 1 if k == len(line[:i]) - 1: super_ = Instances[sv.value] sub = variable_name break else: sv = Instances[sv.value][variable_name] else: Error("SyntaxError", "Only properties can be changed").printMessage() return -1 else: Error("SyntaxError", "Only objects may have subitems").printMessage() return -1 elif k != len(line[:i]) - 1: Error("AssignmentError", "Cannot assign value-to-value").printMessage() return -1 k += 1 super_[sub] = result else: Error("AssignmentError", "Cannot assign value-to-value").printMessage() return -1 else: Symbols[varname.value] = result else: Error("AssignmentError", "Cannot assign value-to-value").printMessage() return -1 elif line[i].type == "SUB_START_STMT": handled = True name = line[i+1] if name.type != "FUNCTION_CALL": Error("SyntaxError", "Invalid function name").printMessage() return -1 name = name.value i+=2 arglist = [] while i < len(line): if line[i].type != "VARIABLE": Error("SyntaxError", "Only parameters might follow function definition").printMessage() return -1 arglist += [line[i]] i+=1 contentlist = [] broken = False while j < len(toks) and not broken: handled = True line = toks[j] cl = [] while i < len(line): if line[i].type == "SUB_STOP_STMT": broken = True break cl.append(line[i]) i += 1 contentlist.append(cl) if broken: break i = 0 j+=1 Procedures[name] = (contentlist[1:-1], arglist) elif line[i].type == "STRUCT_START_STMT": handled = True name = line[i+1] if name.type != "STRUCT": Error("SyntaxError", "Invalid struct name").printMessage() return -1 name = name.value i+=2 if line[i].type != "STRUCT_WITH_STMT": Error("SyntaxError", "Invalid struct statement: missing WITH").printMessage() return -1 i += 1 contentlist = [] broken = False while j < len(toks) and not broken: handled = True line = toks[j] cl = [] while i < len(line): if line[i].type == "STRUCT_STOP_STMT": broken = True break cl.append(line[i]) i += 1 contentlist.append(cl) if broken: break i = 0 j+=1 Structures[name] = (contentlist[1:-1]) elif line[i].type == "FOR_START_STMT": handled = True number = line[i+1] expr = [] while number.type != "FOR_TIMES_STMT": expr.append(number) i+=1 if i >= len(line): Error("SyntaxError", "FOR must be followed by TIMES").printMessage() return -1 number = line[i+1] number = eval_term(expr) if number.type != "NUMBER": Error("SyntaxError", "FOR must be followed by integer").printMessage() return -1 number = int(number.value) counter = None if len(line) > i+2 and line[i+2].type == "STREAM": counter = line[i+2].value i+=1 i+=3 ij = [i, j] contentlist = [] n = 1 while j < len(toks) and n > 0: line = toks[j] cl = [] while i < len(line) and n > 0: if line[i].type == "FOR_STOP_STMT": n -= 1 elif line[i].type == "FOR_START_STMT": n += 1 cl.append(line[i]) i += 1 contentlist.append(cl) i = 0 j+=1 forstmt = (contentlist[1:-1]) for k in range(number): if counter: Symbols[counter] = Token("NUMBER", k) parse(forstmt) if counter: del Symbols[counter] j-=1 i = 0 elif line[i].type == "IF_START_STMT": handled = True old_i = i while i < len(line): i+=1 if line[i].type in ["EQUALITY_CHECK_SIGN", "INEQUALITY_CHECK_SIGN", "GREATER_THAN_SIGN", "SMALLER_THAN_SIGN"]: break else: Error("SyntaxError", "If must be followed by either `==`, `>`, `<` or `!=`").showMessage() return -1 end_i = i while end_i < len(line): end_i += 1 if line[end_i].type == "THEN_STMT": break else: Error("SyntaxError", "If must be followed by `then`").showMessage() return -1 term1 = eval_term(line[old_i+1:i]) term2 = eval_term(line[i+1:end_i]) if (((line[i].type == "EQUALITY_CHECK_SIGN" and (term1.type, term1.value) != (term2.type, term2.value))) or ((line[i].type == "INEQUALITY_CHECK_SIGN" and (term1.type, term1.value) == (term2.type, term2.value))) or ((line[i].type == "SMALLER_THAN_SIGN" and term1.type != term2.type or term1.value >= term2.value)) or ((line[i].type == "GREATER_THAN_SIGN" and term1.type != term2.type or term1.value <= term2.value))): n = None i = old_i while n is None or (j < len(toks) and n > 0): line = toks[j] while i < len(line): if line[i].type == "IF_START_STMT": if n == None: n = 1 else: n += 1 elif line[i].type == "IF_STOP_STMT": n -= 1 i += 1 i = 0 j+=1 j -= 1 break else: i = end_i i+=1 if not handled: r = eval_term(line) if r.isError: r.printMessage() return -1 elif r.type == "ERROR_RETURN": return -1 j+=1 def run(): if len(sys.argv) != 2: print("Only one argument: filename") return data = open_file(sys.argv[1]) tokens = lex(data) parse(tokens) run() #print(Symbols) #a = ConcreteWrapper.froms("10").value #b = ConcreteWrapper.froms("1.5").value #c = a.div(b).value #print(float(c))
9eacf51b771582912383d366bc98f91903c6d7a8
b6097c94aed4137280b4bd03edf10d8c45b99970
/translator/urls.py
8c44f50e91734ad4d2073be26745b404d842cdcc
[]
no_license
letsgo247/breakorean
efd6399320470ac1014ae1bf064b623ec1e2cb2c
efa0745c25444c52097a54fbbf9ce898a4763aad
refs/heads/master
2020-07-24T13:41:59.520619
2019-10-20T15:45:37
2019-10-20T15:45:37
207,946,125
0
0
null
null
null
null
UTF-8
Python
false
false
588
py
from django.urls import path from . import views, andviews urlpatterns = [ path('', views.cover, name='cover'), path('select', views.select, name='select'), path('translator<int:alg_id>', views.translator, name='translator'), path('translated<int:alg_id>', views.translated, name='translated'), path('and', andviews.cover, name='andcover'), path('andselect', andviews.select, name='andselect'), path('andtranslator<int:alg_id>', andviews.translator, name='andtranslator'), path('andtranslated<int:alg_id>', andviews.translated, name='andtranslated'), ]
d2abdd3e0b8a17bc75a2300b1b927c931a86913f
f4092fbe29f80c4ae715730508477fefd9994837
/taskmate/todolist_app/admin.py
5e8f4133a5bdaab0d3798434a368f1167b8885b9
[]
no_license
naxus1/Django
320e255d11c3776f4d058b2d4e7da2f5a61c3e0b
c94d59798f2ebe5da229f0574c23fa773569d4cf
refs/heads/master
2022-12-02T14:14:59.951633
2021-01-15T02:59:59
2021-01-15T02:59:59
221,952,801
1
0
null
2022-11-22T06:43:55
2019-11-15T15:37:10
Python
UTF-8
Python
false
false
135
py
from django.contrib import admin from todolist_app.models import TaskList # Register your models here. admin.site.register(TaskList)
247be7466490103c5d82ac4620f83f5af32e4ea4
9c1966721f83c63e46788509951c273e2f8f9491
/data structures/bst_insert.py
ef4d5aecff4aec1836efbd7c0028a445da77166e
[]
no_license
maiman-1/hackerrank-dump
daba30e81e6fdb118ed9b77dcc9393846468a17c
e499c923a8768efafde18e65c055c2ec8b219014
refs/heads/main
2023-06-03T12:30:17.827010
2021-06-27T04:22:09
2021-06-27T04:22:09
375,561,273
0
0
null
null
null
null
UTF-8
Python
false
false
1,006
py
class Node: def __init__(self, info): self.info = info self.left = None self.right = None self.level = None def __str__(self): return str(self.info) def preOrder(root): if root == None: return print (root.info, end=" ") preOrder(root.left) preOrder(root.right) class BinarySearchTree: def __init__(self): self.root = None #Node is defined as #self.left (the left child of the node) #self.right (the right child of the node) #self.info (the value of the node) def insert(self, val): #Enter you code here. current = self.root self.insert_aux(current, val) def insert_aux(self, current, val): # Check left first if current.left is None and val <= current.info: current.left = Node(val) tree = BinarySearchTree() t = int(input()) arr = list(map(int, input().split())) for i in range(t): tree.insert(arr[i]) preOrder(tree.root)
46420d6d79533b4847126b91595955ff96211153
0a46b027e8e610b8784cb35dbad8dd07914573a8
/scripts/venv/lib/python2.7/site-packages/cogent/maths/stats/information_criteria.py
ead8f6417df1dd2fa2049a479c7f9aa4b4de1829
[ "MIT" ]
permissive
sauloal/cnidaria
bb492fb90a0948751789938d9ec64677052073c3
fe6f8c8dfed86d39c80f2804a753c05bb2e485b4
refs/heads/master
2021-01-17T13:43:17.307182
2016-10-05T14:14:46
2016-10-05T14:14:46
33,726,643
3
0
null
null
null
null
UTF-8
Python
false
false
1,145
py
from __future__ import division import numpy __author__ = "Gavin Huttley" __copyright__ = "Copyright 2007-2012, The Cogent Project" __credits__ = ["Gavin Huttley"] __license__ = "GPL" __version__ = "1.5.3" __maintainer__ = "Gavin Huttley" __email__ = "[email protected]" __status__ = "Production" def aic(lnL, nfp, sample_size=None): """returns Aikake Information Criterion Arguments: - lnL: the maximum log-likelihood of a model - nfp: the number of free parameters in the model - sample_size: if provided, the second order AIC is returned """ if sample_size is None: correction = 1 else: assert sample_size > 0, "Invalid sample_size %s" % sample_size correction = sample_size / (sample_size - nfp - 1) return -2* lnL + 2 * nfp * correction def bic(lnL, nfp, sample_size): """returns Bayesian Information Criterion Arguments: - lnL: the maximum log-likelihood of a model - nfp: the number of free parameters in the model - sample_size: size of the sample """ return -2* lnL + nfp * numpy.log(sample_size)
ce430d5d36bbec0fa9337f2273b604c280b16dbc
453a45dfab9fd06b0445f0e49a75bb52ee8b37dc
/scripts/cgminerstats.py
f978f6e818ca8f32f2170bca08b852cd90f383de
[ "WTFPL" ]
permissive
setkeh/cgminer-python
c18f3dfa88009ee5965e09d76f916f592826a6cc
b17ec3f8fe73bf736260413d84d723a3e0378ced
refs/heads/master
2021-01-21T23:14:25.419394
2015-02-26T23:55:32
2015-02-26T23:55:32
10,754,476
0
0
null
null
null
null
UTF-8
Python
false
false
997
py
#!/usr/bin/env python2.7 from pga0 import * from cgminerversion import * from cgminerconfig import * from coin import * from pga1 import * print "CGMiner:" print "Cgminer Version:", cg_version() print "Api Version:", api_version() print "PGA's Connected:", pga_count() print "ASIC's Connected:", asic_count() print "Pool Count:", pool_count() print "Pool Stratergy:", pool_stratergy() print "Miner OS:", miner_os() print "" print "Bitcoin Status:" print "Hash Method:", hash_method() print "Block Hash:", current_block_hash() print "Long Poll:", long_poll() print "Network Diff:", diff() print"" print "PGA 0:" print p0_mhs(), "MH/s" print "Accepted Shares:", p0_accepted() print "Rejected Shares:", p0_rejected() print "Hardware Errors:", p0_hwerrors() print "Utility:", p0_utility(),"/m" print "" print "PGA 1" print p1_mhs(), "MH/s" print "Accepted Shares:", p1_accepted() print "Rejected Shares:", p1_rejected() print "Hardware Errors:", p1_hwerrors() print "Utility:", p1_utility(),"/m"
f42b24eb133af9fb0d043daae02623831e534124
c17ca7a7824056f7ad58d0f71abc25670b20c1fc
/cenet/populations_xml.py
50514b7f8ab3d1c783e713a36c3b795c93d91dae
[ "Apache-2.0" ]
permissive
Si-elegans/Web-based_GUI_Tools
cd35b72e80aa400105593c5c819355437e204a81
58a9b7a76bc46467554192a38ff5329a94e2b627
refs/heads/master
2023-01-11T09:11:21.896172
2017-07-18T11:10:31
2017-07-18T11:10:31
97,445,306
3
1
Apache-2.0
2022-12-26T20:14:59
2017-07-17T07:03:13
JavaScript
UTF-8
Python
false
false
67,096
py
POPULATIONS_TEMPLATE =\ """ <population id="ADAL" component="" type="populationList"> <instance id="0"> <location y="8.65" x="-239.25" z="31.050000000000001"/> </instance> </population> <population id="ADAR" component="" type="populationList"> <instance id="0"> <location y="-12.9" x="-239.25" z="31.050000000000001"/> </instance> </population> <population id="ADEL" component="" type="populationList"> <instance id="0"> <location y="11." x="-242.375" z="32.450000000000003"/> </instance> </population> <population id="ADER" component="" type="populationList"> <instance id="0"> <location y="-15.299999" x="-242.375" z="32.450000000000003"/> </instance> </population> <population id="ADFL" component="" type="populationList"> <instance id="0"> <location y="3.7250001" x="-267.899999999999977" z="41.600002000000003"/> </instance> </population> <population id="ADFR" component="" type="populationList"> <instance id="0"> <location y="-8." x="-267.899999999999977" z="41.600002000000003"/> </instance> </population> <population id="ADLL" component="" type="populationList"> <instance id="0"> <location y="2.7" x="-265.75" z="47.549999999999997"/> </instance> </population> <population id="ADLR" component="" type="populationList"> <instance id="0"> <location y="-6.95" x="-265.75" z="47.549999999999997"/> </instance> </population> <population id="AFDL" component="" type="populationList"> <instance id="0"> <location y="4.5" x="-268.375" z="43.5"/> </instance> </population> <population id="AFDR" component="" type="populationList"> <instance id="0"> <location y="-8.75" x="-268.375" z="43.5"/> </instance> </population> <population id="AIAL" component="" type="populationList"> <instance id="0"> <location y="0.8" x="-264.149999999999977" z="35.550002999999997"/> </instance> </population> <population id="AIAR" component="" type="populationList"> <instance id="0"> <location y="-5.1" x="-264.149999999999977" z="35.550002999999997"/> </instance> </population> <population id="AIBL" component="" type="populationList"> <instance id="0"> <location y="2.7" x="-266.199979999999982" z="37."/> </instance> </population> <population id="AIBR" component="" type="populationList"> <instance id="0"> <location y="-6.8999996" x="-266.199979999999982" z="37."/> </instance> </population> <population id="AIML" component="" type="populationList"> <instance id="0"> <location y="9.25" x="-253.449980000000011" z="28.400002000000001"/> </instance> </population> <population id="AIMR" component="" type="populationList"> <instance id="0"> <location y="-13.500000999999999" x="-253.449980000000011" z="28.400002000000001"/> </instance> </population> <population id="AINL" component="" type="populationList"> <instance id="0"> <location y="-1.4499999" x="-269.541999999999973" z="39.357998000000002"/> </instance> </population> <population id="AINR" component="" type="populationList"> <instance id="0"> <location y="-3.067" x="-269.541999999999973" z="39.357998000000002"/> </instance> </population> <population id="AIYL" component="" type="populationList"> <instance id="0"> <location y="7.4500003" x="-252.500020000000006" z="28.949999999999999"/> </instance> </population> <population id="AIYR" component="" type="populationList"> <instance id="0"> <location y="-11.699999999999999" x="-252.500020000000006" z="28.949999999999999"/> </instance> </population> <population id="AIZL" component="" type="populationList"> <instance id="0"> <location y="5.6000004" x="-258.75" z="37.450000000000003"/> </instance> </population> <population id="AIZR" component="" type="populationList"> <instance id="0"> <location y="-9.949999999999999" x="-258.75" z="37.450000000000003"/> </instance> </population> <population id="ALA" component="" type="populationList"> <instance id="0"> <location y="-1.35" x="-271." z="50.850000000000001"/> </instance> </population> <population id="ALML" component="" type="populationList"> <instance id="0"> <location y="22.675000000000001" x="-60.75" z="-37.149997999999997"/> </instance> </population> <population id="ALMR" component="" type="populationList"> <instance id="0"> <location y="-24.149999999999999" x="-60.75" z="-37.149997999999997"/> </instance> </population> <population id="ALNL" component="" type="populationList"> <instance id="0"> <location y="0.32500002" x="406.699979999999982" z="12.375"/> </instance> </population> <population id="ALNR" component="" type="populationList"> <instance id="0"> <location y="-2.925" x="406.699979999999982" z="12.375"/> </instance> </population> <population id="AQR" component="" type="populationList"> <instance id="0"> <location y="-14.800000000000001" x="-243.050000000000011" z="33.950000000000003"/> </instance> </population> <population id="AS1" component="" type="populationList"> <instance id="0"> <location y="-0.275" x="-229.038000000000011" z="4.738"/> </instance> </population> <population id="AS10" component="" type="populationList"> <instance id="0"> <location y="-1.9" x="278.25" z="-24."/> </instance> </population> <population id="AS11" component="" type="populationList"> <instance id="0"> <location y="-1.8750001" x="315.699999999999989" z="-26.124998000000001"/> </instance> </population> <population id="AS2" component="" type="populationList"> <instance id="0"> <location y="-1.8750001" x="-203.875" z="-12.725"/> </instance> </population> <population id="AS3" component="" type="populationList"> <instance id="0"> <location y="-1.9" x="-151.400010000000009" z="-45.649997999999997"/> </instance> </population> <population id="AS4" component="" type="populationList"> <instance id="0"> <location y="-1.8750001" x="-90.200005000000004" z="-65.375"/> </instance> </population> <population id="AS5" component="" type="populationList"> <instance id="0"> <location y="-1.8750001" x="-3.7500002" z="-52.524999999999999"/> </instance> </population> <population id="AS6" component="" type="populationList"> <instance id="0"> <location y="-1.9" x="28.25" z="-34.25"/> </instance> </population> <population id="AS7" component="" type="populationList"> <instance id="0"> <location y="-1.9" x="119.900000000000006" z="3.9500003"/> </instance> </population> <population id="AS8" component="" type="populationList"> <instance id="0"> <location y="-1.9" x="181.849999999999994" z="-1.7750001"/> </instance> </population> <population id="AS9" component="" type="populationList"> <instance id="0"> <location y="-1.8750001" x="228.924990000000008" z="-14.5"/> </instance> </population> <population id="ASEL" component="" type="populationList"> <instance id="0"> <location y="4.125" x="-263.675000000000011" z="40.049999999999997"/> </instance> </population> <population id="ASER" component="" type="populationList"> <instance id="0"> <location y="-8.375" x="-263.675000000000011" z="40.049999999999997"/> </instance> </population> <population id="ASGL" component="" type="populationList"> <instance id="0"> <location y="3.7" x="-265.350000000000023" z="45.424999999999997"/> </instance> </population> <population id="ASGR" component="" type="populationList"> <instance id="0"> <location y="-8." x="-265.350000000000023" z="45.424999999999997"/> </instance> </population> <population id="ASHL" component="" type="populationList"> <instance id="0"> <location y="5.55" x="-265.625" z="41."/> </instance> </population> <population id="ASHR" component="" type="populationList"> <instance id="0"> <location y="-9.800000000000001" x="-265.625" z="41."/> </instance> </population> <population id="ASIL" component="" type="populationList"> <instance id="0"> <location y="2.6499999" x="-263.699999999999989" z="46.875"/> </instance> </population> <population id="ASIR" component="" type="populationList"> <instance id="0"> <location y="-6.8999996" x="-263.699999999999989" z="46.875"/> </instance> </population> <population id="ASJL" component="" type="populationList"> <instance id="0"> <location y="2.9750001" x="-263." z="37.475000000000001"/> </instance> </population> <population id="ASJR" component="" type="populationList"> <instance id="0"> <location y="-7.25" x="-263." z="37.475000000000001"/> </instance> </population> <population id="ASKL" component="" type="populationList"> <instance id="0"> <location y="3.7" x="-268.024999999999977" z="46.399997999999997"/> </instance> </population> <population id="ASKR" component="" type="populationList"> <instance id="0"> <location y="-8." x="-268.024999999999977" z="46.399997999999997"/> </instance> </population> <population id="AUAL" component="" type="populationList"> <instance id="0"> <location y="4.5" x="-263.975000000000023" z="37.475000000000001"/> </instance> </population> <population id="AUAR" component="" type="populationList"> <instance id="0"> <location y="-8.800000000000001" x="-263.975000000000023" z="37.475000000000001"/> </instance> </population> <population id="AVAL" component="" type="populationList"> <instance id="0"> <location y="-0.55" x="-271.5" z="37.982999999999997"/> </instance> </population> <population id="AVAR" component="" type="populationList"> <instance id="0"> <location y="-3.5" x="-271.5" z="37.982999999999997"/> </instance> </population> <population id="AVBL" component="" type="populationList"> <instance id="0"> <location y="0.225" x="-269.793999999999983" z="37.863002999999999"/> </instance> </population> <population id="AVBR" component="" type="populationList"> <instance id="0"> <location y="-4.581" x="-269.793999999999983" z="37.863002999999999"/> </instance> </population> <population id="AVDL" component="" type="populationList"> <instance id="0"> <location y="-0.167" x="-268.699999999999989" z="37.299999999999997"/> </instance> </population> <population id="AVDR" component="" type="populationList"> <instance id="0"> <location y="-4.033" x="-268.682999999999993" z="37.283000000000001"/> </instance> </population> <population id="AVEL" component="" type="populationList"> <instance id="0"> <location y="2.75" x="-269.350000000000023" z="40.649999999999999"/> </instance> </population> <population id="AVER" component="" type="populationList"> <instance id="0"> <location y="-8.4" x="-269.350000000000023" z="40.649999999999999"/> </instance> </population> <population id="AVFL" component="" type="populationList"> <instance id="0"> <location y="2.1" x="-246.400000000000006" z="18.600000000000001"/> </instance> </population> <population id="AVFR" component="" type="populationList"> <instance id="0"> <location y="-6.5" x="-246.400000000000006" z="18.600000000000001"/> </instance> </population> <population id="AVG" component="" type="populationList"> <instance id="0"> <location y="-2." x="-237.099999999999994" z="12.85"/> </instance> </population> <population id="AVHL" component="" type="populationList"> <instance id="0"> <location y="4.1499996" x="-264.399999999999977" z="45."/> </instance> </population> <population id="AVHR" component="" type="populationList"> <instance id="0"> <location y="-8.900001" x="-264.399999999999977" z="45."/> </instance> </population> <population id="AVJL" component="" type="populationList"> <instance id="0"> <location y="0.2" x="-264.899999999999977" z="47.549999999999997"/> </instance> </population> <population id="AVJR" component="" type="populationList"> <instance id="0"> <location y="-4.75" x="-264.899999999999977" z="47.549999999999997"/> </instance> </population> <population id="AVKL" component="" type="populationList"> <instance id="0"> <location y="1.65" x="-255." z="22.574999999999999"/> </instance> </population> <population id="AVKR" component="" type="populationList"> <instance id="0"> <location y="-4.583" x="-246.950009999999992" z="19."/> </instance> </population> <population id="AVL" component="" type="populationList"> <instance id="0"> <location y="-7.5000005" x="-263.449999999999989" z="36.350000000000001"/> </instance> </population> <population id="AVM" component="" type="populationList"> <instance id="0"> <location y="-20.5" x="-55.649999999999999" z="-44.600002000000003"/> </instance> </population> <population id="AWAL" component="" type="populationList"> <instance id="0"> <location y="3.9" x="-265.875" z="42.75"/> </instance> </population> <population id="AWAR" component="" type="populationList"> <instance id="0"> <location y="-8.199999999999999" x="-265.875" z="42.75"/> </instance> </population> <population id="AWBL" component="" type="populationList"> <instance id="0"> <location y="5.5" x="-266.225000000000023" z="43.100000000000001"/> </instance> </population> <population id="AWBR" component="" type="populationList"> <instance id="0"> <location y="-9.75" x="-266.225000000000023" z="43.100000000000001"/> </instance> </population> <population id="AWCL" component="" type="populationList"> <instance id="0"> <location y="3.8" x="-267.949999999999989" z="38.950000000000003"/> </instance> </population> <population id="AWCR" component="" type="populationList"> <instance id="0"> <location y="-8.1" x="-267.949999999999989" z="38.950000000000003"/> </instance> </population> <population id="BAGL" component="" type="populationList"> <instance id="0"> <location y="4.675" x="-277.099980000000016" z="44.975002000000003"/> </instance> </population> <population id="BAGR" component="" type="populationList"> <instance id="0"> <location y="-9." x="-277.099980000000016" z="44.975002000000003"/> </instance> </population> <population id="BDUL" component="" type="populationList"> <instance id="0"> <location y="15.35" x="-187.150000000000006" z="-0.2"/> </instance> </population> <population id="BDUR" component="" type="populationList"> <instance id="0"> <location y="-19.649999999999999" x="-187.150000000000006" z="-0.2"/> </instance> </population> <population id="CANL" component="" type="populationList"> <instance id="0"> <location y="25.350002" x="47.950000000000003" z="1.65"/> </instance> </population> <population id="CANR" component="" type="populationList"> <instance id="0"> <location y="-27.25" x="47.950000000000003" z="1.65"/> </instance> </population> <population id="CEPDL" component="" type="populationList"> <instance id="0"> <location y="1.35" x="-275.025019999999984" z="54.075004999999997"/> </instance> </population> <population id="CEPDR" component="" type="populationList"> <instance id="0"> <location y="-5.625" x="-275.025019999999984" z="54.075004999999997"/> </instance> </population> <population id="CEPVL" component="" type="populationList"> <instance id="0"> <location y="0.70000005" x="-277.125" z="39.924999999999997"/> </instance> </population> <population id="CEPVR" component="" type="populationList"> <instance id="0"> <location y="-4.95" x="-277.125" z="39.924999999999997"/> </instance> </population> <population id="DA1" component="" type="populationList"> <instance id="0"> <location y="-0.75" x="-227.075009999999992" z="3.425"/> </instance> </population> <population id="DA2" component="" type="populationList"> <instance id="0"> <location y="-1.9" x="-190.75" z="-21.675000000000001"/> </instance> </population> <population id="DA3" component="" type="populationList"> <instance id="0"> <location y="-1.65" x="-123.650000000000006" z="-58.350002000000003"/> </instance> </population> <population id="DA4" component="" type="populationList"> <instance id="0"> <location y="-1.7" x="-32.399999999999999" z="-61.75"/> </instance> </population> <population id="DA5" component="" type="populationList"> <instance id="0"> <location y="-1.65" x="84.200000000000003" z="-3.15"/> </instance> </population> <population id="DA6" component="" type="populationList"> <instance id="0"> <location y="-1.65" x="198.675000000000011" z="-6.3500004"/> </instance> </population> <population id="DA7" component="" type="populationList"> <instance id="0"> <location y="-1.65" x="281.600000000000023" z="-24.949999999999999"/> </instance> </population> <population id="DA8" component="" type="populationList"> <instance id="0"> <location y="1.275" x="376.800000000000011" z="-10.925000000000001"/> </instance> </population> <population id="DA9" component="" type="populationList"> <instance id="0"> <location y="-4.6" x="376.800000000000011" z="-10.925000000000001"/> </instance> </population> <population id="DB1" component="" type="populationList"> <instance id="0"> <location y="-1.9" x="-230.349989999999991" z="6.85"/> </instance> </population> <population id="DB2" component="" type="populationList"> <instance id="0"> <location y="-0.2" x="-244.5" z="15.787000000000001"/> </instance> </population> <population id="DB3" component="" type="populationList"> <instance id="0"> <location y="-1.85" x="-195.275000000000006" z="-18.524999999999999"/> </instance> </population> <population id="DB4" component="" type="populationList"> <instance id="0"> <location y="-1.8750001" x="-96.275000000000006" z="-64.650000000000006"/> </instance> </population> <population id="DB5" component="" type="populationList"> <instance id="0"> <location y="-4.05" x="35.25" z="-30.449999999999999"/> </instance> </population> <population id="DB6" component="" type="populationList"> <instance id="0"> <location y="-1.8249999" x="178.099999999999994" z="-0.2"/> </instance> </population> <population id="DB7" component="" type="populationList"> <instance id="0"> <location y="-1.85" x="267.75" z="-22.625"/> </instance> </population> <population id="DD1" component="" type="populationList"> <instance id="0"> <location y="-0.9" x="-231.949999999999989" z="6.85"/> </instance> </population> <population id="DD2" component="" type="populationList"> <instance id="0"> <location y="-1.85" x="-156.474989999999991" z="-42.850000000000001"/> </instance> </population> <population id="DD3" component="" type="populationList"> <instance id="0"> <location y="-1.9" x="-28.600002" z="-60.524999999999999"/> </instance> </population> <population id="DD4" component="" type="populationList"> <instance id="0"> <location y="-1.8750001" x="122.899994000000007" z="4.5499997"/> </instance> </population> <population id="DD5" component="" type="populationList"> <instance id="0"> <location y="-1.8750001" x="234.050019999999989" z="-15.775"/> </instance> </population> <population id="DD6" component="" type="populationList"> <instance id="0"> <location y="-1.9" x="365.774999999999977" z="-16.475000000000001"/> </instance> </population> <population id="DVA" component="" type="populationList"> <instance id="0"> <location y="-2.345" x="394.600000000000023" z="3.678"/> </instance> </population> <population id="DVB" component="" type="populationList"> <instance id="0"> <location y="-0.75" x="394.5" z="4."/> </instance> </population> <population id="DVC" component="" type="populationList"> <instance id="0"> <location y="-0.116" x="395.432979999999986" z="5.992"/> </instance> </population> <population id="FLPL" component="" type="populationList"> <instance id="0"> <location y="10.875" x="-246.300000000000011" z="31.050000000000001"/> </instance> </population> <population id="FLPR" component="" type="populationList"> <instance id="0"> <location y="-15.050000000000001" x="-246.300000000000011" z="31.050000000000001"/> </instance> </population> <population id="HSNL" component="" type="populationList"> <instance id="0"> <location y="17.449999999999999" x="61.049999999999997" z="6.95"/> </instance> </population> <population id="HSNR" component="" type="populationList"> <instance id="0"> <location y="-21.649999999999999" x="61.049999999999997" z="6.95"/> </instance> </population> <population id="I1L" component="" type="populationList"> <instance id="0"> <location y="2.8999999" x="-300.350000000000023" z="53.149997999999997"/> </instance> </population> <population id="I1R" component="" type="populationList"> <instance id="0"> <location y="-7.1500006" x="-300.350000000000023" z="53.149997999999997"/> </instance> </population> <population id="I2L" component="" type="populationList"> <instance id="0"> <location y="1.55" x="-311.649999999999977" z="54.450000000000003"/> </instance> </population> <population id="I2R" component="" type="populationList"> <instance id="0"> <location y="-5.7999997" x="-311.649999999999977" z="54.450000000000003"/> </instance> </population> <population id="I3" component="" type="populationList"> <instance id="0"> <location y="-2.05" x="-296.550020000000018" z="58.25"/> </instance> </population> <population id="I4" component="" type="populationList"> <instance id="0"> <location y="-2.05" x="-253.900010000000009" z="43.100000000000001"/> </instance> </population> <population id="I5" component="" type="populationList"> <instance id="0"> <location y="-2.1" x="-247.849989999999991" z="30.675000000000001"/> </instance> </population> <population id="I6" component="" type="populationList"> <instance id="0"> <location y="1.7" x="-251.650000000000006" z="43.049999999999997"/> </instance> </population> <population id="IL1DL" component="" type="populationList"> <instance id="0"> <location y="2.825" x="-282.762999999999977" z="52.762996999999999"/> </instance> </population> <population id="IL1DR" component="" type="populationList"> <instance id="0"> <location y="-7.0620003" x="-282.762999999999977" z="52.762996999999999"/> </instance> </population> <population id="IL1L" component="" type="populationList"> <instance id="0"> <location y="3.8" x="-282.675020000000018" z="47.850002000000003"/> </instance> </population> <population id="IL1R" component="" type="populationList"> <instance id="0"> <location y="-8.075001" x="-282.675020000000018" z="47.850002000000003"/> </instance> </population> <population id="IL1VL" component="" type="populationList"> <instance id="0"> <location y="2.25" x="-279.5" z="41."/> </instance> </population> <population id="IL1VR" component="" type="populationList"> <instance id="0"> <location y="-6.5499997" x="-279.5" z="41."/> </instance> </population> <population id="IL2DL" component="" type="populationList"> <instance id="0"> <location y="7.1000004" x="-287.474980000000016" z="57.125003999999997"/> </instance> </population> <population id="IL2DR" component="" type="populationList"> <instance id="0"> <location y="-11.35" x="-287.474980000000016" z="57.125003999999997"/> </instance> </population> <population id="IL2L" component="" type="populationList"> <instance id="0"> <location y="6.7500005" x="-285." z="49.350000000000001"/> </instance> </population> <population id="IL2R" component="" type="populationList"> <instance id="0"> <location y="-11." x="-285." z="49.350000000000001"/> </instance> </population> <population id="IL2VL" component="" type="populationList"> <instance id="0"> <location y="3.3" x="-288.875" z="42.950000000000003"/> </instance> </population> <population id="IL2VR" component="" type="populationList"> <instance id="0"> <location y="-7.6" x="-288.875" z="42.950000000000003"/> </instance> </population> <population id="LUAL" component="" type="populationList"> <instance id="0"> <location y="1.35" x="403.800020000000018" z="4.1"/> </instance> </population> <population id="LUAR" component="" type="populationList"> <instance id="0"> <location y="-3.85" x="403.800020000000018" z="4.1"/> </instance> </population> <population id="M1" component="" type="populationList"> <instance id="0"> <location y="-0.86700004" x="-252.134999999999991" z="44.420001999999997"/> </instance> </population> <population id="M2L" component="" type="populationList"> <instance id="0"> <location y="3.7" x="-254.349989999999991" z="38.649999999999999"/> </instance> </population> <population id="M2R" component="" type="populationList"> <instance id="0"> <location y="-8." x="-254.349989999999991" z="38.649999999999999"/> </instance> </population> <population id="M3L" component="" type="populationList"> <instance id="0"> <location y="3.7500002" x="-295.399999999999977" z="48.149999999999999"/> </instance> </population> <population id="M3R" component="" type="populationList"> <instance id="0"> <location y="-8.050000000000001" x="-295.399999999999977" z="48.149999999999999"/> </instance> </population> <population id="M4" component="" type="populationList"> <instance id="0"> <location y="-2.033" x="-288.932979999999986" z="57.582999999999998"/> </instance> </population> <population id="M5" component="" type="populationList"> <instance id="0"> <location y="-2.2" x="-241.449999999999989" z="41.800002999999997"/> </instance> </population> <population id="MCL" component="" type="populationList"> <instance id="0"> <location y="3.2" x="-296.149999999999977" z="52.299999999999997"/> </instance> </population> <population id="MCR" component="" type="populationList"> <instance id="0"> <location y="-7.25" x="-296.149999999999977" z="52.299999999999997"/> </instance> </population> <population id="MI" component="" type="populationList"> <instance id="0"> <location y="-2.1539998" x="-293.512020000000007" z="56.707000000000001"/> </instance> </population> <population id="NSML" component="" type="populationList"> <instance id="0"> <location y="2.6000001" x="-292.25" z="51.799999999999997"/> </instance> </population> <population id="NSMR" component="" type="populationList"> <instance id="0"> <location y="-6.3500004" x="-292.25" z="51.799999999999997"/> </instance> </population> <population id="OLLL" component="" type="populationList"> <instance id="0"> <location y="4.4" x="-283.899999999999977" z="50.024997999999997"/> </instance> </population> <population id="OLLR" component="" type="populationList"> <instance id="0"> <location y="-8.65" x="-283.899999999999977" z="50.024997999999997"/> </instance> </population> <population id="OLQDL" component="" type="populationList"> <instance id="0"> <location y="2.775" x="-280." z="53.425002999999997"/> </instance> </population> <population id="OLQDR" component="" type="populationList"> <instance id="0"> <location y="-7.0249996" x="-280." z="53.425002999999997"/> </instance> </population> <population id="OLQVL" component="" type="populationList"> <instance id="0"> <location y="4.2" x="-279.25" z="43.924999999999997"/> </instance> </population> <population id="OLQVR" component="" type="populationList"> <instance id="0"> <location y="-8.474999" x="-279.25" z="43.924999999999997"/> </instance> </population> <population id="PDA" component="" type="populationList"> <instance id="0"> <location y="-2.95" x="387.25" z="-5.5"/> </instance> </population> <population id="PDB" component="" type="populationList"> <instance id="0"> <location y="-3.3" x="384.649999999999977" z="-7.75"/> </instance> </population> <population id="PDEL" component="" type="populationList"> <instance id="0"> <location y="25.75" x="143.800000000000011" z="25.600000000000001"/> </instance> </population> <population id="PDER" component="" type="populationList"> <instance id="0"> <location y="-27.350000000000001" x="143.800000000000011" z="25.600000000000001"/> </instance> </population> <population id="PHAL" component="" type="populationList"> <instance id="0"> <location y="1.2" x="402.899999999999977" z="4.1"/> </instance> </population> <population id="PHAR" component="" type="populationList"> <instance id="0"> <location y="-3.8" x="402.899999999999977" z="4.1"/> </instance> </population> <population id="PHBL" component="" type="populationList"> <instance id="0"> <location y="1.2" x="405.600039999999979" z="5.475"/> </instance> </population> <population id="PHBR" component="" type="populationList"> <instance id="0"> <location y="-3.7250001" x="405.600039999999979" z="5.475"/> </instance> </population> <population id="PHCL" component="" type="populationList"> <instance id="0"> <location y="0.75" x="408.774999999999977" z="7.275"/> </instance> </population> <population id="PHCR" component="" type="populationList"> <instance id="0"> <location y="-3.425" x="408.774999999999977" z="7.275"/> </instance> </population> <population id="PLML" component="" type="populationList"> <instance id="0"> <location y="2.5" x="410.149999999999977" z="8.175000000000001"/> </instance> </population> <population id="PLMR" component="" type="populationList"> <instance id="0"> <location y="-3.675" x="410.149999999999977" z="8.175000000000001"/> </instance> </population> <population id="PLNL" component="" type="populationList"> <instance id="0"> <location y="4.225" x="402.300000000000011" z="6.8999996"/> </instance> </population> <population id="PLNR" component="" type="populationList"> <instance id="0"> <location y="-6.225" x="402.300000000000011" z="6.8999996"/> </instance> </population> <population id="PQR" component="" type="populationList"> <instance id="0"> <location y="-0.32500002" x="407.300000000000011" z="7.6499996"/> </instance> </population> <population id="PVCL" component="" type="populationList"> <instance id="0"> <location y="0.85" x="404.150019999999984" z="5.5"/> </instance> </population> <population id="PVCR" component="" type="populationList"> <instance id="0"> <location y="-3.4499998" x="404.150019999999984" z="5.5"/> </instance> </population> <population id="PVDL" component="" type="populationList"> <instance id="0"> <location y="24.748999999999999" x="175.15100000000001" z="24.952000000000002"/> </instance> </population> <population id="PVDR" component="" type="populationList"> <instance id="0"> <location y="-26.113997999999999" x="175.15100000000001" z="24.952000000000002"/> </instance> </population> <population id="PVM" component="" type="populationList"> <instance id="0"> <location y="24.850000000000001" x="188.800000000000011" z="20.550001000000002"/> </instance> </population> <population id="PVNL" component="" type="populationList"> <instance id="0"> <location y="0.55" x="410." z="8.900001"/> </instance> </population> <population id="PVNR" component="" type="populationList"> <instance id="0"> <location y="-3.25" x="409.949999999999989" z="8.900001"/> </instance> </population> <population id="PVPL" component="" type="populationList"> <instance id="0"> <location y="-0.1" x="366.650019999999984" z="-14.699999999999999"/> </instance> </population> <population id="PVPR" component="" type="populationList"> <instance id="0"> <location y="-0.15" x="356.550000000000011" z="-16.649999999999999"/> </instance> </population> <population id="PVQL" component="" type="populationList"> <instance id="0"> <location y="0.85" x="402.400019999999984" z="5.15"/> </instance> </population> <population id="PVQR" component="" type="populationList"> <instance id="0"> <location y="-3.3" x="402.400019999999984" z="5.15"/> </instance> </population> <population id="PVR" component="" type="populationList"> <instance id="0"> <location y="-1.85" x="407.350000000000023" z="7.7"/> </instance> </population> <population id="PVT" component="" type="populationList"> <instance id="0"> <location y="-0.1" x="358.75" z="-17.5"/> </instance> </population> <population id="PVWL" component="" type="populationList"> <instance id="0"> <location y="0.8" x="405.399999999999977" z="6.8"/> </instance> </population> <population id="PVWR" component="" type="populationList"> <instance id="0"> <location y="-3.4" x="405.399999999999977" z="6.8"/> </instance> </population> <population id="RIAL" component="" type="populationList"> <instance id="0"> <location y="4." x="-270.25" z="45."/> </instance> </population> <population id="RIAR" component="" type="populationList"> <instance id="0"> <location y="-8.199999999999999" x="-270.25" z="45."/> </instance> </population> <population id="RIBL" component="" type="populationList"> <instance id="0"> <location y="5.5" x="-264.350000000000023" z="38."/> </instance> </population> <population id="RIBR" component="" type="populationList"> <instance id="0"> <location y="-9.800000000000001" x="-264.350000000000023" z="38."/> </instance> </population> <population id="RICL" component="" type="populationList"> <instance id="0"> <location y="-0.737" x="-267.062999999999988" z="38.087000000000003"/> </instance> </population> <population id="RICR" component="" type="populationList"> <instance id="0"> <location y="-3.563" x="-267.062999999999988" z="38.087000000000003"/> </instance> </population> <population id="RID" component="" type="populationList"> <instance id="0"> <location y="-1.225" x="-272.350000000000023" z="54.938000000000002"/> </instance> </population> <population id="RIFL" component="" type="populationList"> <instance id="0"> <location y="0." x="-239.849989999999991" z="18.350000000000001"/> </instance> </population> <population id="RIFR" component="" type="populationList"> <instance id="0"> <location y="-5.15" x="-245.5" z="23.899999999999999"/> </instance> </population> <population id="RIGL" component="" type="populationList"> <instance id="0"> <location y="0." x="-233.25" z="16.350000000000001"/> </instance> </population> <population id="RIGR" component="" type="populationList"> <instance id="0"> <location y="-4.7" x="-241.950009999999992" z="20.649999999999999"/> </instance> </population> <population id="RIH" component="" type="populationList"> <instance id="0"> <location y="-2." x="-267.350000000000023" z="35.950000000000003"/> </instance> </population> <population id="RIML" component="" type="populationList"> <instance id="0"> <location y="3.5" x="-260.899999999999977" z="39."/> </instance> </population> <population id="RIMR" component="" type="populationList"> <instance id="0"> <location y="-7.75" x="-260.899999999999977" z="39."/> </instance> </population> <population id="RIPL" component="" type="populationList"> <instance id="0"> <location y="3.3750002" x="-278.574979999999982" z="48.824997000000003"/> </instance> </population> <population id="RIPR" component="" type="populationList"> <instance id="0"> <location y="-7.625" x="-278.574979999999982" z="48.824997000000003"/> </instance> </population> <population id="RIR" component="" type="populationList"> <instance id="0"> <location y="-11.599999" x="-265.899999999999977" z="36.649997999999997"/> </instance> </population> <population id="RIS" component="" type="populationList"> <instance id="0"> <location y="-4.8250003" x="-262.163000000000011" z="33.637999999999998"/> </instance> </population> <population id="RIVL" component="" type="populationList"> <instance id="0"> <location y="4.5" x="-265.300020000000018" z="50.350000000000001"/> </instance> </population> <population id="RIVR" component="" type="populationList"> <instance id="0"> <location y="-8.75" x="-265.300020000000018" z="50.350000000000001"/> </instance> </population> <population id="RMDDL" component="" type="populationList"> <instance id="0"> <location y="3.6" x="-269.074979999999982" z="37.649999999999999"/> </instance> </population> <population id="RMDDR" component="" type="populationList"> <instance id="0"> <location y="-7.75" x="-269.074979999999982" z="37.649999999999999"/> </instance> </population> <population id="RMDL" component="" type="populationList"> <instance id="0"> <location y="3.1" x="-271." z="41.200000000000003"/> </instance> </population> <population id="RMDR" component="" type="populationList"> <instance id="0"> <location y="-7.4" x="-271." z="41.200000000000003"/> </instance> </population> <population id="RMDVL" component="" type="populationList"> <instance id="0"> <location y="4.8500004" x="-271.199979999999982" z="44.399999999999999"/> </instance> </population> <population id="RMDVR" component="" type="populationList"> <instance id="0"> <location y="-9.049999" x="-271.199979999999982" z="44.399999999999999"/> </instance> </population> <population id="RMED" component="" type="populationList"> <instance id="0"> <location y="-1.5" x="-275.75" z="58.499996000000003"/> </instance> </population> <population id="RMEL" component="" type="populationList"> <instance id="0"> <location y="4.65" x="-274.399999999999977" z="46.987000000000002"/> </instance> </population> <population id="RMER" component="" type="populationList"> <instance id="0"> <location y="-8.900001" x="-274.399999999999977" z="46.987000000000002"/> </instance> </population> <population id="RMEV" component="" type="populationList"> <instance id="0"> <location y="-2.033" x="-272.966999999999985" z="35.667000000000002"/> </instance> </population> <population id="RMFL" component="" type="populationList"> <instance id="0"> <location y="1.1" x="-265.050020000000018" z="34.100000000000001"/> </instance> </population> <population id="RMFR" component="" type="populationList"> <instance id="0"> <location y="-5.4" x="-265.050020000000018" z="34.100000000000001"/> </instance> </population> <population id="RMGL" component="" type="populationList"> <instance id="0"> <location y="8.25" x="-238.299990000000008" z="32.700000000000003"/> </instance> </population> <population id="RMGR" component="" type="populationList"> <instance id="0"> <location y="-12.5" x="-238.299990000000008" z="32.700000000000003"/> </instance> </population> <population id="RMHL" component="" type="populationList"> <instance id="0"> <location y="1.1" x="-265.899999999999977" z="35.700000000000003"/> </instance> </population> <population id="RMHR" component="" type="populationList"> <instance id="0"> <location y="-5.2999997" x="-265.899999999999977" z="35.700000000000003"/> </instance> </population> <population id="SAADL" component="" type="populationList"> <instance id="0"> <location y="-4.6879997" x="-270.168999999999983" z="42.131"/> </instance> </population> <population id="SAADR" component="" type="populationList"> <instance id="0"> <location y="0.531" x="-270.168999999999983" z="42.131"/> </instance> </population> <population id="SAAVL" component="" type="populationList"> <instance id="0"> <location y="3.9" x="-270.900019999999984" z="45.424999999999997"/> </instance> </population> <population id="SAAVR" component="" type="populationList"> <instance id="0"> <location y="-8.175000000000001" x="-270.900019999999984" z="45.424999999999997"/> </instance> </population> <population id="SABD" component="" type="populationList"> <instance id="0"> <location y="-3.2" x="-234.800000000000011" z="14.925000000000001"/> </instance> </population> <population id="SABVL" component="" type="populationList"> <instance id="0"> <location y="3.325" x="-249.25" z="24.349997999999999"/> </instance> </population> <population id="SABVR" component="" type="populationList"> <instance id="0"> <location y="-8.1" x="-249.25" z="24.349997999999999"/> </instance> </population> <population id="SDQL" component="" type="populationList"> <instance id="0"> <location y="21.399999999999999" x="222.799990000000008" z="19.199999999999999"/> </instance> </population> <population id="SDQR" component="" type="populationList"> <instance id="0"> <location y="-14.200001" x="-131.75" z="-10.550000000000001"/> </instance> </population> <population id="SIADL" component="" type="populationList"> <instance id="0"> <location y="-3.958" x="-267.658000000000015" z="43.966999999999999"/> </instance> </population> <population id="SIADR" component="" type="populationList"> <instance id="0"> <location y="-0.38300002" x="-269.199979999999982" z="43.649999999999999"/> </instance> </population> <population id="SIAVL" component="" type="populationList"> <instance id="0"> <location y="5.9500003" x="-259.800020000000018" z="32.25"/> </instance> </population> <population id="SIAVR" component="" type="populationList"> <instance id="0"> <location y="-10.199999999999999" x="-259.800020000000018" z="32.25"/> </instance> </population> <population id="SIBDL" component="" type="populationList"> <instance id="0"> <location y="-5.2669997" x="-269.132999999999981" z="45.799999999999997"/> </instance> </population> <population id="SIBDR" component="" type="populationList"> <instance id="0"> <location y="0.96699995" x="-269.132999999999981" z="45.799999999999997"/> </instance> </population> <population id="SIBVL" component="" type="populationList"> <instance id="0"> <location y="-2.667" x="-269.867000000000019" z="35.408000000000001"/> </instance> </population> <population id="SIBVR" component="" type="populationList"> <instance id="0"> <location y="-2.767" x="-269.867000000000019" z="35.408000000000001"/> </instance> </population> <population id="SMBDL" component="" type="populationList"> <instance id="0"> <location y="3.1" x="-264.300000000000011" z="33.100000000000001"/> </instance> </population> <population id="SMBDR" component="" type="populationList"> <instance id="0"> <location y="-7." x="-264.300000000000011" z="33.100000000000001"/> </instance> </population> <population id="SMBVL" component="" type="populationList"> <instance id="0"> <location y="0.425" x="-263.449999999999989" z="33.049999999999997"/> </instance> </population> <population id="SMBVR" component="" type="populationList"> <instance id="0"> <location y="-4.6" x="-263.449999999999989" z="33.049999999999997"/> </instance> </population> <population id="SMDDL" component="" type="populationList"> <instance id="0"> <location y="3.25" x="-266.25" z="34.100000000000001"/> </instance> </population> <population id="SMDDR" component="" type="populationList"> <instance id="0"> <location y="-7.4500003" x="-266.25" z="34.100000000000001"/> </instance> </population> <population id="SMDVL" component="" type="populationList"> <instance id="0"> <location y="4.7" x="-270.949999999999989" z="46.649999999999999"/> </instance> </population> <population id="SMDVR" component="" type="populationList"> <instance id="0"> <location y="-8.900001" x="-270.949999999999989" z="46.649999999999999"/> </instance> </population> <population id="URADL" component="" type="populationList"> <instance id="0"> <location y="5." x="-284.649999999999977" z="52.200000000000003"/> </instance> </population> <population id="URADR" component="" type="populationList"> <instance id="0"> <location y="-9.300000000000001" x="-284.649999999999977" z="52.200000000000003"/> </instance> </population> <population id="URAVL" component="" type="populationList"> <instance id="0"> <location y="0.32500002" x="-279.600000000000023" z="41.399999999999999"/> </instance> </population> <population id="URAVR" component="" type="populationList"> <instance id="0"> <location y="-4.575" x="-279.600000000000023" z="41.399999999999999"/> </instance> </population> <population id="URBL" component="" type="populationList"> <instance id="0"> <location y="5.05" x="-279.949999999999989" z="47.549999999999997"/> </instance> </population> <population id="URBR" component="" type="populationList"> <instance id="0"> <location y="-9.324999999999999" x="-279.949999999999989" z="47.549999999999997"/> </instance> </population> <population id="URXL" component="" type="populationList"> <instance id="0"> <location y="3.05" x="-269.875" z="48.274999999999999"/> </instance> </population> <population id="URXR" component="" type="populationList"> <instance id="0"> <location y="-7.35" x="-269.875" z="48.274999999999999"/> </instance> </population> <population id="URYDL" component="" type="populationList"> <instance id="0"> <location y="4.125" x="-281.425000000000011" z="51.899997999999997"/> </instance> </population> <population id="URYDR" component="" type="populationList"> <instance id="0"> <location y="-8.4" x="-281.425000000000011" z="51.899997999999997"/> </instance> </population> <population id="URYVL" component="" type="populationList"> <instance id="0"> <location y="3.4" x="-280.925020000000018" z="45.350000000000001"/> </instance> </population> <population id="URYVR" component="" type="populationList"> <instance id="0"> <location y="-7.7" x="-280.925020000000018" z="45.350000000000001"/> </instance> </population> <population id="VA1" component="" type="populationList"> <instance id="0"> <location y="-1.35" x="-235.550000000000011" z="11.75"/> </instance> </population> <population id="VA10" component="" type="populationList"> <instance id="0"> <location y="-1.85" x="254.625020000000006" z="-21.25"/> </instance> </population> <population id="VA11" component="" type="populationList"> <instance id="0"> <location y="-1.55" x="312.350000000000023" z="-26.249998000000001"/> </instance> </population> <population id="VA12" component="" type="populationList"> <instance id="0"> <location y="-0.1" x="362.449999999999989" z="-18.149999999999999"/> </instance> </population> <population id="VA2" component="" type="populationList"> <instance id="0"> <location y="-1.85" x="-217.099999999999994" z="-3.9500003"/> </instance> </population> <population id="VA3" component="" type="populationList"> <instance id="0"> <location y="-1.475" x="-184.099989999999991" z="-26.374998000000001"/> </instance> </population> <population id="VA4" component="" type="populationList"> <instance id="0"> <location y="-1.85" x="-119.500010000000003" z="-58.700000000000003"/> </instance> </population> <population id="VA5" component="" type="populationList"> <instance id="0"> <location y="-1.85" x="-54.299999999999997" z="-66.049994999999996"/> </instance> </population> <population id="VA6" component="" type="populationList"> <instance id="0"> <location y="-1.85" x="21.550000000000001" z="-41.149999999999999"/> </instance> </population> <population id="VA7" component="" type="populationList"> <instance id="0"> <location y="-1.85" x="98.049994999999996" z="1.175"/> </instance> </population> <population id="VA8" component="" type="populationList"> <instance id="0"> <location y="-1.8" x="150.300000000000011" z="3.4"/> </instance> </population> <population id="VA9" component="" type="populationList"> <instance id="0"> <location y="-1.8" x="208.824999999999989" z="-9.049999"/> </instance> </population> <population id="VB1" component="" type="populationList"> <instance id="0"> <location y="-1.55" x="-246.449999999999989" z="16.399999999999999"/> </instance> </population> <population id="VB10" component="" type="populationList"> <instance id="0"> <location y="-1.85" x="218.074980000000011" z="-11.4"/> </instance> </population> <population id="VB11" component="" type="populationList"> <instance id="0"> <location y="-1.8249999" x="262.324999999999989" z="-21.949999999999999"/> </instance> </population> <population id="VB2" component="" type="populationList"> <instance id="0"> <location y="-2." x="-253.300000000000011" z="19.850000000000001"/> </instance> </population> <population id="VB3" component="" type="populationList"> <instance id="0"> <location y="-1.85" x="-210.224999999999994" z="-8.725"/> </instance> </population> <population id="VB4" component="" type="populationList"> <instance id="0"> <location y="-2." x="-173.25" z="-33.5"/> </instance> </population> <population id="VB5" component="" type="populationList"> <instance id="0"> <location y="-1.85" x="-109.549999999999997" z="-62.149999999999999"/> </instance> </population> <population id="VB6" component="" type="populationList"> <instance id="0"> <location y="-1.85" x="-36.575000000000003" z="-62.699997000000003"/> </instance> </population> <population id="VB7" component="" type="populationList"> <instance id="0"> <location y="-9.675000000000001" x="41.450000000000003" z="-24.361999999999998"/> </instance> </population> <population id="VB8" component="" type="populationList"> <instance id="0"> <location y="-1.8249999" x="108.799999999999997" z="2.875"/> </instance> </population> <population id="VB9" component="" type="populationList"> <instance id="0"> <location y="-1.85" x="159.550000000000011" z="3.2"/> </instance> </population> <population id="VC1" component="" type="populationList"> <instance id="0"> <location y="-0.72499996" x="-170.025010000000009" z="-35.75"/> </instance> </population> <population id="VC2" component="" type="populationList"> <instance id="0"> <location y="-0.625" x="-105.325000000000003" z="-63.399999999999999"/> </instance> </population> <population id="VC3" component="" type="populationList"> <instance id="0"> <location y="-1.4499999" x="-6.45" z="-54.000003999999997"/> </instance> </population> <population id="VC4" component="" type="populationList"> <instance id="0"> <location y="-1.15" x="43.850000000000001" z="-24.199999999999999"/> </instance> </population> <population id="VC5" component="" type="populationList"> <instance id="0"> <location y="-1.15" x="66.549994999999996" z="-12.5"/> </instance> </population> <population id="VC6" component="" type="populationList"> <instance id="0"> <location y="-1.8249999" x="174.175000000000011" z="1."/> </instance> </population> <population id="VD1" component="" type="populationList"> <instance id="0"> <location y="-0.70000005" x="-228.599999999999994" z="4.05"/> </instance> </population> <population id="VD10" component="" type="populationList"> <instance id="0"> <location y="-0.75" x="236.099999999999994" z="-16.5"/> </instance> </population> <population id="VD11" component="" type="populationList"> <instance id="0"> <location y="-0.8" x="283.800020000000018" z="-24.800000000000001"/> </instance> </population> <population id="VD12" component="" type="populationList"> <instance id="0"> <location y="-0.75" x="345.5" z="-23.149999999999999"/> </instance> </population> <population id="VD13" component="" type="populationList"> <instance id="0"> <location y="-0.75" x="379.850000000000023" z="-10.75"/> </instance> </population> <population id="VD2" component="" type="populationList"> <instance id="0"> <location y="-0.65000004" x="-226.049990000000008" z="2.35"/> </instance> </population> <population id="VD3" component="" type="populationList"> <instance id="0"> <location y="-0.8" x="-188.099999999999994" z="-23.449999999999999"/> </instance> </population> <population id="VD4" component="" type="populationList"> <instance id="0"> <location y="-0.8" x="-137.199999999999989" z="-52.700000000000003"/> </instance> </population> <population id="VD5" component="" type="populationList"> <instance id="0"> <location y="-0.75" x="-68.299999999999997" z="-66.75"/> </instance> </population> <population id="VD6" component="" type="populationList"> <instance id="0"> <location y="-0.70000005" x="-1.4000001" z="-52.149997999999997"/> </instance> </population> <population id="VD7" component="" type="populationList"> <instance id="0"> <location y="-12.349999" x="57.950000000000003" z="-14.200001"/> </instance> </population> <population id="VD8" component="" type="populationList"> <instance id="0"> <location y="-0.75" x="135.099989999999991" z="3.9500003"/> </instance> </population> <population id="VD9" component="" type="populationList"> <instance id="0"> <location y="-0.8" x="191.5" z="-3.8"/> </instance> </population> """
6414139850343e0efe620371e16f2883d3045f33
74bdcebcc6fdf66c69c04d4d2ea2c4ac0592dd99
/layers/vsgc_layer_pre.py
28e5f33e2166d77c4e0cf28132998f71d0a6a6f5
[]
no_license
lt610/DeeperGNNS
470bfd8a2db6860db79cb9578e747863a9f26554
1e5c36b49342908c38aefc3541d7f70059565d33
refs/heads/master
2023-01-27T12:09:03.993995
2020-12-06T12:21:51
2020-12-06T12:21:51
282,876,382
10
0
null
null
null
null
UTF-8
Python
false
false
5,655
py
import torch as th from torch import nn import dgl.function as fn from layers.pair_norm import PairNorm import dgl class VSGCLayerPre(nn.Module): def __init__(self, in_dim, out_dim, bias=True, k=1, alpha=1, lambd=1, dropout=0): super(VSGCLayerPre, self).__init__() self.linear = nn.Linear(in_dim, out_dim, bias=bias) self.k = k self.alpha = alpha self.lambd = lambd self.dropout = nn.Dropout(dropout) # self.exact_solution = False # self.cache_es = None self.reset_parameters() def reset_parameters(self): nn.init.xavier_uniform_(self.linear.weight) if self.linear.bias is not None: nn.init.zeros_(self.linear.bias) # alpha and lambda def forward(self, graph, features): g = graph.local_var() degs = g.in_degrees().float() - 1.0 norm_lambd_1 = th.pow(self.lambd * degs + 1.0, -1) norm_lambd_1 = norm_lambd_1.to(features.device).unsqueeze(1) norm05 = th.pow(degs + 1.0, 0.5) norm05 = norm05.to(features.device).unsqueeze(1) norm_05 = th.pow(degs + 1.0, -0.5) norm_05 = norm_05.to(features.device).unsqueeze(1) # g = g.remove_self_loop() h = self.dropout(features) h = self.linear(h) h_pre = h h_initial = h * norm_lambd_1 for _ in range(self.k): h = h * norm_05 g.ndata['h'] = h g.update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h')) h = g.ndata.pop('h') h = h * norm_lambd_1 * norm05 # h = self.alpha * h + self.alpha * ri + (1 - self.alpha) * h_pre h = self.alpha * self.lambd * h + (1 - self.alpha) * h_pre + self.alpha * h_initial h_pre = h return h # exact solution # def forward(self, graph, features): # g = graph.local_var() # device =features # # g = g.remove_self_loop() # h = self.dropout(features) # h = self.linear(h) # # if self.exact_solution: # if self.cache_es is None: # g = g.remove_self_loop() # adj = g.adjacency_matrix().to(device) # degs = g.in_degrees().float().clamp(min=1) # norm = th.diag(degs) # norm05 = th.diag(th.pow(degs+1, 0.5)) # norm05 = norm05.to(features.device) # norm_05 = th.diag(th.pow(degs+1, -0.5)) # norm_05 = norm_05.to(features.device) # es = th.mm(adj, norm_05) # es = self.lambd * th.mm(norm05, es) # es = self.lambd * norm + th.eye(adj.shape[0]).to(device) - es # es = th.inverse(es) # self.cache_es = es # h = th.mm(self.cache_es, h) # else: # degs = g.in_degrees().float().clamp(min=1) - 1.0 # norm_lambd_1 = th.pow(self.lambd * degs + 1.0, -1) # norm_lambd_1 = norm_lambd_1.to(features.device).unsqueeze(1) # # norm05 = th.pow(degs + 1.0, 0.5) # norm05 = norm05.to(features.device).unsqueeze(1) # norm_05 = th.pow(degs + 1.0, -0.5) # norm_05 = norm_05.to(features.device).unsqueeze(1) # # h_pre = h # h_initial = h * norm_lambd_1 # for _ in range(self.k): # h = h * norm_05 # # g.ndata['h'] = h # g.update_all(fn.copy_u('h', 'm'), # fn.sum('m', 'h')) # h = g.ndata.pop('h') # # h = h * norm_lambd_1 * norm05 # # # h = self.alpha * h + self.alpha * ri + (1 - self.alpha) * h_pre # h = self.alpha * self.lambd * h + (1 - self.alpha) * h_pre + self.alpha * h_initial # # h_pre = h # # return h # # only alpha # def forward(self, graph, features): # g = graph.local_var() # # # g = g.remove_self_loop() # degs = g.in_degrees().float().clamp(min=1) # norm = th.pow(degs, -0.5) # norm = norm.to(features.device).unsqueeze(1) # # norm_1 = th.pow(degs, -1) # norm_1 = norm_1.to(features.device).unsqueeze(1) # # # g = g.remove_self_loop() # h = self.dropout(features) # h = self.linear(h) # # h_pre = h # ri = h * norm_1 # for _ in range(self.k): # # h = h * norm # g.ndata['h'] = h # g.update_all(fn.copy_u('h', 'm'), # fn.sum('m', 'h')) # h = g.ndata.pop('h') # # h = h * norm # h = self.alpha * h + self.alpha * ri + (1 - self.alpha) * h_pre # h_pre = h # return h # #非对称D # def forward(self, graph, features): # g = graph.local_var() # # # g = g.remove_self_loop() # degs = g.in_degrees().float().clamp(min=1) # # norm_1 = th.pow(degs, -1) # norm_1 = norm_1.to(features.device).unsqueeze(1) # # # g = g.remove_self_loop() # h = self.dropout(features) # h = self.linear(h) # # h_pre = h # ri = h * norm_1 # for _ in range(self.k): # # g.ndata['h'] = h # g.update_all(fn.copy_u('h', 'm'), # fn.sum('m', 'h')) # h = g.ndata.pop('h') # # h = h * norm_1 # h = self.alpha * h + self.alpha * ri + (1 - self.alpha) * h_pre # h_pre = h # return h
5c713e71b6d36c733a3c7071ffaec82c80094caa
f8826a479f2b9d2f28993ceea7a7d0e3847aaf3d
/apps/requestlogger/models.py
9fa6f370798fdbd62b4484b8acf1d332f55c10a0
[]
no_license
icomms/wqmanager
bec6792ada11af0ff55dc54fd9b9ba49242313b7
f683b363443e1c0be150656fd165e07a75693f55
refs/heads/master
2021-01-20T11:59:42.299351
2012-02-20T15:28:40
2012-02-20T15:28:40
2,154,449
1
1
null
null
null
null
UTF-8
Python
false
false
2,869
py
from django.db import models from django.contrib.auth.models import User from domain.models import Domain import os import logging import settings # this is a really bad place for this class to live, but reference it here for now from scheduler.fields import PickledObjectField from datetime import datetime from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse REQUEST_TYPES = ( ('GET', 'Get'), ('POST', 'Post'), ('PUT', 'Put'), ) class RequestLog(models.Model): '''Keeps track of incoming requests''' # Lots of stuff here is replicated in Submission. # They should ultimately point here, but that's a data migration # problem. method = models.CharField(max_length=4, choices=REQUEST_TYPES) url = models.CharField(max_length=200) time = models.DateTimeField(_('Request Time'), default = datetime.now) ip = models.IPAddressField(_('Submitting IP Address'), null=True, blank=True) is_secure = models.BooleanField(default=False) # The logged in user user = models.ForeignKey(User, null=True, blank=True) # Some pickled fields for having access to the raw info headers = PickledObjectField(_('Request Headers')) parameters = PickledObjectField(_('Request Parameters')) def __unicode__(self): return "%s to %s at %s from %s" % (self.method, self.url, self.time, self.ip) @classmethod def from_request(cls, request): '''Creates an instance of a RequestLog from a standard django HttpRequest object. ''' log = RequestLog() log.method = request.method log.url = request.build_absolute_uri(request.path) log.time = datetime.now() log.is_secure = request.is_secure() if request.META.has_key('REMOTE_ADDR') and request.META['REMOTE_ADDR']: log.ip = request.META['REMOTE_ADDR'] elif request.META.has_key('REMOTE_HOST') and request.META['REMOTE_HOST']: log.ip = request.META['REMOTE_HOST'] # if request.user != User, then user is anonymous if isinstance(request.user, User): log.user = request.user def _convert_to_dict(obj): # converts a django-querydict to a true python dict # and converts any values to strings. This could result # in a loss of information to_return = {} for key, value in obj.items(): to_return[key] = str(value) return to_return log.headers = _convert_to_dict(request.META) if request.method == "GET": log.parameters = _convert_to_dict(request.GET) else: log.parameters = _convert_to_dict(request.POST) return log
ae180e8cf37b46499f5232dd71f2789e8e56b342
a16691abb472e2d57cf417cc671e7574f97aaf23
/src/13_millas.py
785d28eea60a685a38043e0f43f552b1e14265d4
[ "MIT" ]
permissive
agomusa/oop-algorithms-python-platzi
fbb16208b68e822c6232ffb944c414c176004ac1
56e5f636c9243fbd81148a6e6e8405034f362c70
refs/heads/main
2023-06-19T21:38:19.925134
2021-07-07T20:49:09
2021-07-07T20:49:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
733
py
class Millas: def __init__(self): self._distancia = 0 # Función para obtener el valor de _distancia def obtener_distancia(self): print("Llamada al método getter...") return self._distancia # Función para definir el valor de _distancia def definir_distancia(self, recorrido): print("Llamada al método setter...") self._distancia = recorrido # Función para eliminar el atributo _distancia def eliminar_distancia(self): del self._distancia distancia = property(obtener_distancia, definir_distancia, eliminar_distancia) if __name__ == '__main__': avion = Millas() avion.distancia = int(input('¿Cuantas millas vas a viajar? ')) print('Vas a viajar '+str(avion.distancia*1.609344)+' Kilometros')
017d1388db426775c4c7bd1d1c8f5b3ddf57f674
1fdc21ac035f53c1d51d02ef4c0cd0b9333ff0ca
/00_stats_backend/stats_backend/serie/serializers.py
c1712a8b5a8b2a31c994dbb7c179bceb415f4e2c
[]
no_license
RoscaS/stats_stats-dashboard
42a3d22160e27c4ebb060640e7f5ca263fc004c4
359506ac071189dbde64c0756ed772ec7991987f
refs/heads/master
2023-01-12T11:06:23.316993
2019-06-23T01:58:06
2019-06-23T01:58:06
177,424,980
0
0
null
2023-01-03T18:27:01
2019-03-24T14:21:51
Python
UTF-8
Python
false
false
239
py
from rest_framework import serializers from serie.models import Serie class SerieSerializer(serializers.ModelSerializer): class Meta: model = Serie # fields = '__all__' fields = ( 'data', )
b254df743e617dfd1390743f0e04bbe4d12cb542
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03227/s922156594.py
3367f99a10180d83d75fbea989fb7e0b5a810cdd
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
173
py
import sys def input(): return sys.stdin.readline().rstrip() def main(): s=input() if len(s)==2:print(s) else:print(s[::-1]) if __name__=='__main__': main()
52e24c59cf1ba45ebea9a276fd030f94948fe43a
335e07c271bd181e21295986612b1e94964100f3
/3d.py
818fd8de8efdeaf1678ad4a78941b268054b22d9
[]
no_license
johnql/eecs-Molecular
0df36796e328688f077ed6dfd80c99e826260cbb
ce59f406f0ba40521abb2b7e9fd9f53f90526dcd
refs/heads/master
2021-07-25T11:57:57.792284
2021-01-06T16:14:49
2021-01-06T16:14:49
236,077,323
0
0
null
null
null
null
UTF-8
Python
false
false
608
py
# -*- coding: utf-8 -*- import ase import pandas as pd struct_file = pd.read_csv('../champs-scalar-coupling/structures.csv') import random # Select a molecule random_molecule = random.choice(struct_file['molecule_name'].unique()) molecule = struct_file[struct_file['molecule_name'] == random_molecule] display(molecule) # Get atomic coordinates atoms = molecule.iloc[:, 3:].values print(atoms) # Get atomic symbols symbols = molecule.iloc[:, 2].values print(symbols) from ase import Atoms import ase.visualize system = Atoms(positions=atoms, symbols=symbols) ase.visualize.view(system, viewer="x3d")
823010365cec2bba9e72158d01b1943f84ed8217
b782c69e18bdd074c40d7fad0983afa0743f8b4a
/Problem_31.py
8cd863bbb3e1caf867102351f2196e212197669e
[]
no_license
danjoh94/My_Project_Euler_Solutions
a4dc90b85b8b49a4a149efb9756896cf4f1d1d45
c7a8ca82da32473176b5290ce56157105aa7976e
refs/heads/master
2020-03-26T22:31:55.041731
2018-08-20T20:13:17
2018-08-20T20:13:17
145,466,207
0
0
null
null
null
null
UTF-8
Python
false
false
1,246
py
#!/usr/bin/env python3 # -*- coding: cp1252 -*- ''' Problem 31: Coin Sum https://projecteuler.net/problem=31 Problem definition In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). It is possible to make £2 in the following way: 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many different ways can £2 be made using any number of coins? BY: Daniel Johansson DATE: 2018/08/20 ''' def coin_sum(n, coins): """ Calculates the coin sum Algorithm coinsum(n) = Table[n-coin][coin] + Table[n][coins[-1]] if n == 1 return 1 Parameters ---------- n : int the value to calculate the coin sum from coins : list list of coins that is available Returns ------- int returns the coin sum """ if(len(coins)<=1): return 1 coin = coins[-1] if(coin > n): return coin_sum(n,coins[:-1]) if(coin <= 1): return 1 if(n<=1): return 1 return coin_sum(n,coins[:-1]) + coin_sum(n-coin,coins) if __name__ == '__main__': print(coin_sum(n=200,coins=[1,2,5,10,20,50,100,200]))
b3398fa2ff067bc32bfe54cd1d0f1e55c10c2916
77c91f553b6fae236f341868b9da0c4821ee5048
/tictactoe.py
498ba9d208da6f8508088bd3c622205d04966dd0
[]
no_license
awsdcrafting/SmartTicTacToe
b191dd512764e7985b547a9119ff98ded68d195c
5600db89abc9ee4b30911865942780133332deef
refs/heads/master
2023-01-09T01:47:29.367263
2020-11-11T10:36:19
2020-11-11T10:36:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,596
py
import sys import numpy as np class TicTacToe: def __init__(self): self.game_board = np.zeros((3, 3), dtype=np.int16) def make_move(self, player_id, x, y): if not self.game_board[y][x] == 0: sys.exit("Error: Tried to make a move on an already occupied tile") self.game_board[y][x] = player_id def possibilities(self): empty = np.where(self.game_board == 0) first = empty[1].tolist() second = empty[0].tolist() return [x for x in zip(first, second)] def check_if_won(self): winner = None for player_id in [1, -1]: if self.row_win(player_id): winner = player_id elif self.col_win(player_id): winner = player_id elif self.diag_win(player_id): winner = player_id if np.all(self.game_board != 0) and winner is None: winner = 0 return winner def row_win(self, player_id): return np.any(np.all(self.game_board == player_id, axis=1)) def col_win(self, player_id): return np.any(np.all(self.game_board == player_id, axis=0)) def diag_win(self, player_id): diag1 = np.array([self.game_board[0, 0], self.game_board[1, 1], self.game_board[2, 2]]) diag2 = np.array([self.game_board[0, 2], self.game_board[1, 1], self.game_board[2, 0]]) return np.all(diag1 == player_id) or np.all(diag2 == player_id) def print_game_board(self): print("GameBoard:") for row in self.game_board: print(row) print()
db028508c74e67d79784aae349aac5f05d584df9
abfe7041f66b9441e5748d3eeae36abedf94e708
/contactform/views.py
e854f3bff3a0e60f8869736f5003808766a99e29
[]
no_license
SaurabhKumarVerma/newsfeed
743333ff10354723f234fa6513927693ff4f9449
57271b3f4e45e7cde500e0eff8cd0874bd796172
refs/heads/main
2022-12-30T22:45:07.114578
2020-10-22T10:08:49
2020-10-22T10:08:49
303,373,271
1
0
null
null
null
null
UTF-8
Python
false
false
2,060
py
from django.shortcuts import render , get_object_or_404,redirect from . models import ContactForm from news.models import News from cat.models import Cat from subcat.models import SubCat from django.contrib.auth import authenticate, login , logout import datetime def contact_add(request): perm = 0 for i in request.user.groups.all(): if i.name == 'masteruser' : perm =1 if perm == 0: error = 'URL Not Found' return render(request, 'back/error.html', {'error':error}) now = datetime.datetime.now() year = now.year month = now.month day = now.day if len(str(day)) == 1: day = "0" + str(day) if len(str(month)) == 1: month = "0" + str(month) today = (str(year) +"/"+ str(month) +"/"+ str(day)) time = str(now.hour) + ":"+ str(now.minute) if request.method == "POST": name = request.POST.get('name') email = request.POST.get('email') txt = request.POST.get('msg') print(time) if name == "" or email == "" or txt == "" : msg = "All Feild Required" return render(request, 'fornt/msgbox.html', {'msg':msg} ) b = ContactForm(name=name,email=email,txt=txt,date=today,time=time) b.save() msg = "Your Message Recevied" return render(request, 'front/msgbox.html', {'msg':msg} ) return render(request, 'front/msgbox.html') def contact_show(request): perm = 0 for i in request.user.groups.all(): if i.name == 'masteruser' : perm =1 if perm == 0: error = 'URL Not Found' return render(request, 'back/error.html', {'error':error}) if not request.user.is_authenticated : return redirect("mylogin") msg = ContactForm.objects.all() return render(request, 'back/contact_show.html' , {'msg':msg} ) def contact_delete(request, pk): perm = 0 for i in request.user.groups.all(): if i.name == 'masteruser' : perm =1 if perm == 0: error = 'URL Not Found' return render(request, 'back/error.html', {'error':error}) if not request.user.is_authenticated : return redirect("mylogin") b = ContactForm.objects.filter(pk=pk) b.delete() return redirect(contact_show)
6d79597dadc347377df75d911a978524b5fe957d
4226cc08b0f619a3455327f665d34fdaae1fb4f4
/Automated Forex Trading System/Fnc_Main.py
cf998783c569a07a4e215f896348b69c429efedd
[]
no_license
andrewlai61616/personal_website
25d3f2f49c443b12e14ba541d0a5105fd26fca12
99e30d975fb3948f51afdc6e40e0cb66da0edb99
refs/heads/master
2022-11-22T20:36:20.963801
2020-07-26T17:42:38
2020-07-26T17:42:38
266,386,595
1
1
null
null
null
null
UTF-8
Python
false
false
4,011
py
import VAR import Get_On_Browser import Visit_Web import os, time, getopt, datetime from bs4 import BeautifulSoup def check_1_day_restart_web( password ): if datetime.datetime.today() > VAR.last_web_open_time + datetime.timedelta(days = 1): print("One day passed. Web restarting...") VAR.web = None Visit_Web.visit( demo_account = VAR.demo_account, password = password ) # Visit webpage from scp import SCPClient import paramiko def get_predict(): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) print('\tGetting prediction value from 36.227.33.26') client.connect('36.227.33.26', 22, 'godlai', VAR.ex_params['str_get']) #local '192.168.1.5' scp = SCPClient(client.get_transport()) scp.get('/home/godlai/Documents/forex/predict.txt', 'predict.txt') scp.close() client.close() f = open('predict.txt', 'r') t, predict = f.read().split(',') f.close() t = datetime.datetime.strptime(t,'%Y-%m-%d %H:%M:%S') predict = float(predict) VAR.predict_t, VAR.predict_rate = t, predict def print_status(): now = datetime.datetime.today() now = now.replace(microsecond = 0) print(now, "\n" + "{:>18}".format("Total=" + str(VAR.total_amount)) + "{:>18}".format("\tBought=" + str(VAR.bought_amount)) + "{:>18}".format("\tUsable=" + str(VAR.usable_amount)) + "{:>18}".format("\tProfit=" + str(VAR.current_total_profit)) ) print( "\tPredict time=" + str(VAR.predict_t) + "{:>18}".format("rate=" + str(VAR.predict_rate)) ) print( "\tLast trade time:", VAR.last_trade_time ) print("\tInvestments:\n") for item in VAR.invest: print(item) def import_external_parameters(): # Import external parameters VAR.ex_params = {} with open ('external_parameters.csv', 'r') as fp: line = fp.readline() # 第一行為 標題 line = fp.readline() while line: values = line.split(',') VAR.ex_params[values[0]] = values[1] line = fp.readline() VAR.ex_params['str_get'] = VAR.ex_params['str_get'].replace('\'','') VAR.threshold = float(VAR.ex_params['threshold']) VAR.rate_per_buy = float(VAR.ex_params['rate_per_buy']) VAR.currency = VAR.ex_params['currency'] VAR.multiplier = int(VAR.ex_params['multiplier']) VAR.permit_weekday_end = int(VAR.ex_params['permit_weekday_end']) VAR.permit_weekday_start = int(VAR.ex_params['permit_weekday_start']) VAR.permit_hour_end = int(VAR.ex_params['permit_hour_end']) VAR.permit_hour_start = int(VAR.ex_params['permit_hour_start']) VAR.commission_rate = float(VAR.ex_params['commission_rate']) VAR.wait_period = int(VAR.ex_params['wait_period']) def get_arguments(argv): VAR.demo_account = False try: opts, args = getopt.getopt(argv,"o:") for opt, arg in opts: if opt == '-o': if str(arg).replace(' ','') == 'demo': VAR.demo_account = True print("Using demo account") except getopt.GetoptError: print("ERROR getting parameters! Neglecting all.") pass def loop_weekend(): tm_wday = time.gmtime().tm_wday tm_hour = time.gmtime().tm_hour while((tm_wday == 4 and tm_hour >= 21) or tm_wday == 5 or (tm_wday == 6 and tm_hour < 21)): os.system('cls') print("\n\n\nLibertex is currently not available (weekends).\nCurrent time is: " + time.ctime() + " (GMT+8)") print("Libertex will start working at Monday 05:00 (GMT+8) and so will Main_System.py. Good luck!") print("\n\nWaiting 1 minute...") time.sleep(60) tm_wday = time.gmtime().tm_wday tm_hour = time.gmtime().tm_hour def Check_Weekend(): tm_wday = time.gmtime().tm_wday tm_hour = time.gmtime().tm_hour if((tm_wday == 4 and tm_hour >= 21) or tm_wday == 5 or (tm_wday == 6 and tm_hour < 21)): loop_weekend() print("HEY! Remember to try to close VAR.web and open up a new browser") while True: a = 1 def Web_Update(): VAR.soup = BeautifulSoup(VAR.web.page_source, 'lxml') # Get_On_Browser.get_currency_list() Get_On_Browser.get_usable_and_bought() Get_On_Browser.update_user_invest_list() # Get_On_Browser.update_buy_lists()
56b1362b2bb0522b8eee7d20ce388801ae547fc8
cf97fddb63f82c65f622319070b1103d34abe0e9
/Ordenador/PrimosMP.py
6a5eeafd5c3fe8b11004fc2b90c0cbbac37c3c35
[]
no_license
ESapenaVentura/ComputAv
c0ead563d5106952859e16aec8140b7c1291ddc6
5376b45a62548e794358b207d220ea43dbb4b82f
refs/heads/master
2020-04-05T22:05:14.868298
2018-11-12T16:43:15
2018-11-12T16:43:15
157,244,353
0
0
null
null
null
null
UTF-8
Python
false
false
3,503
py
# -*- coding: utf-8 -*- """ Created on Sat Oct 6 14:56:59 2018 @author: Enrique """ import sys from math import sqrt from multiprocessing import Pool,Manager from queue import Empty CURRENT_VERSION = sys.version_info REQUESTED_VERSION = (3, 7) if (CURRENT_VERSION >= REQUESTED_VERSION): from time import time_ns else: from time import time as time_ns def suma_Digitos(num): suma = 0 while True: for Digito in str(num): suma += int(Digito) else: if len(str(suma)) == 1: break else: num = suma suma = 0 return suma def ajustar_Indice_Inicial(i): if (i < 7): return 7 else: ultimo_char = str(i)[-1] if (ultimo_char == '4'): i += 2 elif (ultimo_char in ["0", "2", "5", "6", "8"]): i += 1 return i def repartir_Indices(numero, hilos): num_anadir = 0 divisor = int(sqrt(numero)) // hilos args = [] for i in range(hilos): temp = [] temp.append(numero) temp.append(num_anadir) num_anadir += divisor if (i == hilos - 1): num_anadir += divisor % hilos temp.append(num_anadir) args.append(temp) temp = [] return args def es_Primo(num, i_Inicial, i_Final, evento, terminado): if (i_Inicial < 7): if str(num)[-1] in ["0", "2", "4", "5", "6", "8"]: evento.set() return elif suma_Digitos(num) % 3 == 0: evento.set() return i_Inicial = ajustar_Indice_Inicial(i_Inicial) mult_3 = i_Inicial % 3 if (mult_3 == 2): mult_3 = 1 elif (mult_3 == 1): mult_3 = 2 mult_5 = i_Inicial % 10 if (mult_5 > 5): mult_5 = (mult_5 - 5)/2 else: mult_5 = (mult_5 + 5)/2 for i in iter(range(i_Inicial, i_Final, 2)): if (evento.is_set()): break if (mult_3 == 0 or mult_5 == 0): mult_5 += 1 mult_3 += 1 continue if (num % i == 0): evento.set() return mult_3 += 1 mult_5 += 1 if (mult_3 == 3): mult_3 = 0 if (mult_5 == 5): mult_5 = 0 terminado.set() def Main(): t_i = time_ns() numero = 524287 procesos = 8 args = repartir_Indices(numero, procesos) mana = Manager() noPrimo = mana.Event() terminado = [mana.Event() for i in range(len(args))] for i in range(len(args)): args[i].append(noPrimo) args[i].append(terminado[i]) workers = Pool(procesos) workers.starmap(es_Primo, args) while (True): lista = [] for i in range(len(args)): if terminado[i].is_set(): lista.append(True) if (len(lista) == len(args)): break if (noPrimo.is_set()): break workers.terminate() if (noPrimo.is_set()): print("No es primo") else: print("Es primo") """ if (procesos == 0): workers.terminate() print("Es primo") """ t_f = time_ns() print("Tiempo final: {}s".format((t_f - t_i))) return if __name__ == "__main__": Main()
88849cbaefdac0da35473ee45aca6e6b65848d1d
f211bdc7eb567529dcab51547ad9147ac9b21d0b
/divisible.py
4e958f61c4f412917ff2118dfbd66d999cbde175
[]
no_license
Hamza746/assigment
6551f1d7fdfe4eb4f1a652ace80e5b384d1d8b12
d67051771f5fce826dde10134fd852a030453c5f
refs/heads/master
2020-09-12T09:26:46.506888
2019-11-18T07:15:04
2019-11-18T07:15:04
222,381,770
0
0
null
null
null
null
UTF-8
Python
false
false
343
py
# Write a Python function to check whether a number is completely divisible by another number. # Accept two integer values form the user a = int(input("put numerator:")) b = int(input("put denuminator:")) c = a%b print(c) if c==0: print("both numbers are completely divisible") else: print("both numbers are not completely divisible")
b6bbb6f5cdddba874b8e7c74471e4bb45a157100
30f4230650a73d3cb112ab17a46c9c9375734308
/Covid_chat_bot.py
72ef13f0267f5701e927d37a5585c60fb0487005
[]
no_license
suyash-dubey/PROJECT-2-COVID-CHATBOT
f47108b44aebb23e1b33f59d8e17591bffd8f306
7fc147b56268697355e5b1c606c680860c89cd29
refs/heads/main
2023-06-10T02:00:04.503911
2021-07-03T07:54:08
2021-07-03T07:54:08
382,557,861
1
0
null
null
null
null
UTF-8
Python
false
false
2,864
py
import random from newspaper import Article import string import nltk from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics.pairwise import cosine_similarity import numpy as np import warnings warnings.filterwarnings('ignore') #pip install newspaper3k nltk.download('punkt',quiet=True) #get the Article article=Article('https://en.wikipedia.org/wiki/COVID-19') article.download() article.parse() article.nlp() corpus=article.text #tokenisation test=corpus sentence_list=nltk.sent_tokenize(test)#list of sentences #function to return a random greeting msg to user def greet_res(text): text=text.lower() #boots greetin response bot_greetings=['hello','hi','hey'] #user greeting response user_greetings=['hello','hi','hey','hii','wassup','lo','hellooooooo'] for word in text.split(): if word in user_greetings: return random.choice(bot_greetings) #function to sort index_sort def index_sort(list_var): length=len(list_var) list_index=list(range(0,length)) x=list_var for i in range(length): for j in range(length): if x[list_index[i]]>x[list_index[j]]: temp=list_index[i] list_index[i]=list_index[j] list_index[j]=temp return list_index #function for bot response def bot_res(user_input): user_input=user_input.lower() sentence_list.append(user_input) bot_res='' #convert the whole sentence in form of vector cm=CountVectorizer().fit_transform(sentence_list) #check input matches in our sentence lst or not s_score=cosine_similarity(cm[-1],cm)#cm[-1]means last jo hmne append kia tha input s_score_list=s_score.flatten()#we have conerted the s_score into a list index=index_sort(s_score_list) index=index[1:] res_flag=0 j=0 for i in range(len(index)): if s_score_list[index[i]]>0.0: bot_res=bot_res+' '+sentence_list[index[i]] res_flag=1 j=j+1 #if we want to print max 2 sentence i response not more than that if j>2: break if res_flag==0: bot_res=bot_res+' I apologise that i have not understood ur meaning plz be specific' sentence_list.remove(user_input) return bot_res #start chat print('Covid Helpline: I m here to help u with the information regarding corona virus. If u want to exit type nye or exit or quit') exit_list=['bye','exit','byeee','quit'] while(True): user_input=input() if user_input.lower() in exit_list: print('Bot: Thanks for ur queries') break else: if greet_res(user_input)!=None: print('Bot:'+greet_res(user_input)) else: print('Bot:'+bot_res(user_input))
ddf47d224f7d5fdde321387abe4c3738cc0dd469
75669dfdd9099abe887f92a380c05691ea705653
/requests/utils.py
f960d315839ff603e54f4efdfb9b1ae6089e27b9
[]
no_license
robspychala/viva-viva-viva
34c20015a5467b1774933ee65288cbf7b87f0a4d
c818e6f82c254756ca6f2be33d232df0aa643fa6
refs/heads/master
2016-09-06T08:43:29.734456
2012-02-27T19:07:05
2012-02-27T19:07:05
702,397
0
0
null
null
null
null
UTF-8
Python
false
false
12,713
py
# -*- coding: utf-8 -*- """ requests.utils ~~~~~~~~~~~~~~ This module provides utility functions that are used within Requests that are also useful for external consumption. """ import cgi import codecs import os import random import re import zlib from netrc import netrc, NetrcParseError from .compat import parse_http_list as _parse_list_header from .compat import quote, cookielib, SimpleCookie, is_py2, urlparse from .compat import basestring, bytes NETRC_FILES = ('.netrc', '_netrc') def get_netrc_auth(url): """Returns the Requests tuple auth for a given url from netrc.""" locations = (os.path.expanduser('~/{0}'.format(f)) for f in NETRC_FILES) netrc_path = None for loc in locations: if os.path.exists(loc) and not netrc_path: netrc_path = loc # Abort early if there isn't one. if netrc_path is None: return netrc_path ri = urlparse(url) # Strip port numbers from netloc host = ri.netloc.split(':')[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth pass def dict_from_string(s): """Returns a MultiDict with Cookies.""" cookies = dict() c = SimpleCookie() c.load(s) for k, v in list(c.items()): cookies.update({k: v.value}) return cookies def guess_filename(obj): """Tries to guess the filename of the given object.""" name = getattr(obj, 'name', None) if name and name[0] != '<' and name[-1] != '>': return name # From mitsuhiko/werkzeug (used with permission). def parse_list_header(value): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It basically works like :func:`parse_set_header` just that items may appear multiple times and case sensitivity is preserved. The return value is a standard :class:`list`: >>> parse_list_header('token, "quoted value"') ['token', 'quoted value'] To create a header from the :class:`list` again, use the :func:`dump_header` function. :param value: a string with a list header. :return: :class:`list` """ result = [] for item in _parse_list_header(value): if item[:1] == item[-1:] == '"': item = unquote_header_value(item[1:-1]) result.append(item) return result # From mitsuhiko/werkzeug (used with permission). def parse_dict_header(value): """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. :param value: a string with a dict header. :return: :class:`dict` """ result = {} for item in _parse_list_header(value): if '=' not in item: result[item] = None continue name, value = item.split('=', 1) if value[:1] == value[-1:] == '"': value = unquote_header_value(value[1:-1]) result[name] = value return result # From mitsuhiko/werkzeug (used with permission). def unquote_header_value(value, is_filename=False): r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. :param value: the header value to unquote. """ if value and value[0] == value[-1] == '"': # this is not the real unquoting, but fixing this so that the # RFC is met will result in bugs with internet explorer and # probably some other browsers as well. IE for example is # uploading files with "C:\foo\bar.txt" as filename value = value[1:-1] # if this is a filename and the starting characters look like # a UNC path, then just return the value without quotes. Using the # replace sequence below on a UNC path has the effect of turning # the leading double slash into a single slash and then # _fix_ie_filename() doesn't work correctly. See #458. if not is_filename or value[:2] != '\\\\': return value.replace('\\\\', '\\').replace('\\"', '"') return value def header_expand(headers): """Returns an HTTP Header value string from a dictionary. Example expansion:: {'text/x-dvi': {'q': '.8', 'mxb': '100000', 'mxt': '5.0'}, 'text/x-c': {}} # Accept: text/x-dvi; q=.8; mxb=100000; mxt=5.0, text/x-c (('text/x-dvi', {'q': '.8', 'mxb': '100000', 'mxt': '5.0'}), ('text/x-c', {})) # Accept: text/x-dvi; q=.8; mxb=100000; mxt=5.0, text/x-c """ collector = [] if isinstance(headers, dict): headers = list(headers.items()) elif isinstance(headers, basestring): return headers elif isinstance(headers, str): # As discussed in https://github.com/kennethreitz/requests/issues/400 # latin-1 is the most conservative encoding used on the web. Anyone # who needs more can encode to a byte-string before calling return headers.encode("latin-1") elif headers is None: return headers for i, (value, params) in enumerate(headers): _params = [] for (p_k, p_v) in list(params.items()): _params.append('%s=%s' % (p_k, p_v)) collector.append(value) collector.append('; ') if len(params): collector.append('; '.join(_params)) if not len(headers) == i + 1: collector.append(', ') # Remove trailing separators. if collector[-1] in (', ', '; '): del collector[-1] return ''.join(collector) def randombytes(n): """Return n random bytes.""" if is_py2: L = [chr(random.randrange(0, 256)) for i in range(n)] else: L = [chr(random.randrange(0, 256)).encode('utf-8') for i in range(n)] return b"".join(L) def dict_from_cookiejar(cj): """Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. """ cookie_dict = {} for _, cookies in list(cj._cookies.items()): for _, cookies in list(cookies.items()): for cookie in list(cookies.values()): # print cookie cookie_dict[cookie.name] = cookie.value return cookie_dict def cookiejar_from_dict(cookie_dict): """Returns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar. """ # return cookiejar if one was passed in if isinstance(cookie_dict, cookielib.CookieJar): return cookie_dict # create cookiejar cj = cookielib.CookieJar() cj = add_dict_to_cookiejar(cj, cookie_dict) return cj def add_dict_to_cookiejar(cj, cookie_dict): """Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. """ for k, v in list(cookie_dict.items()): cookie = cookielib.Cookie( version=0, name=k, value=v, port=None, port_specified=False, domain='', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False ) # add cookie to cookiejar cj.set_cookie(cookie) return cj def get_encodings_from_content(content): """Returns encodings from given content string. :param content: bytestring to extract encodings from. """ charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I) return charset_re.findall(content) def get_encoding_from_headers(headers): """Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. """ content_type = headers.get('content-type') if not content_type: return None content_type, params = cgi.parse_header(content_type) if 'charset' in params: return params['charset'].strip("'\"") if 'text' in content_type: return 'ISO-8859-1' def stream_decode_response_unicode(iterator, r): """Stream decodes a iterator.""" if r.encoding is None: for item in iterator: yield item return decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace') for chunk in iterator: rv = decoder.decode(chunk) if rv: yield rv rv = decoder.decode('', final=True) if rv: yield rv def get_unicode_from_response(r): """Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. every encodings from ``<meta ... charset=XXX>`` 3. fall back and replace all unicode characters """ tried_encodings = [] # Try charset from content-type encoding = get_encoding_from_headers(r.headers) if encoding: try: return str(r.content, encoding) except UnicodeError: tried_encodings.append(encoding) # Fall back: try: return str(r.content, encoding, errors='replace') except TypeError: return r.content def stream_decompress(iterator, mode='gzip'): """ Stream decodes an iterator over compressed data :param iterator: An iterator over compressed data :param mode: 'gzip' or 'deflate' :return: An iterator over decompressed data """ if mode not in ['gzip', 'deflate']: raise ValueError('stream_decompress mode must be gzip or deflate') zlib_mode = 16 + zlib.MAX_WBITS if mode == 'gzip' else -zlib.MAX_WBITS dec = zlib.decompressobj(zlib_mode) try: for chunk in iterator: rv = dec.decompress(chunk) if rv: yield rv except zlib.error: # If there was an error decompressing, just return the raw chunk yield chunk # Continue to return the rest of the raw data for chunk in iterator: yield chunk else: # Make sure everything has been returned from the decompression object buf = dec.decompress(bytes()) rv = buf + dec.flush() if rv: yield rv def stream_untransfer(gen, resp): if 'gzip' in resp.headers.get('content-encoding', ''): gen = stream_decompress(gen, mode='gzip') elif 'deflate' in resp.headers.get('content-encoding', ''): gen = stream_decompress(gen, mode='deflate') return gen # The unreserved URI characters (RFC 3986) UNRESERVED_SET = frozenset( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~") def unquote_unreserved(uri): """Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded. """ parts = uri.split('%') for i in range(1, len(parts)): h = parts[i][0:2] if len(h) == 2: c = chr(int(h, 16)) if c in UNRESERVED_SET: parts[i] = c + parts[i][2:] else: parts[i] = '%' + parts[i] else: parts[i] = '%' + parts[i] return ''.join(parts) def requote_uri(uri): """Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. """ # Unquote only the unreserved characters # Then quote only illegal characters (do not quote reserved, unreserved, # or '%') return quote(unquote_unreserved(uri), safe="!#$%&'()*+,/:;=?@[]~")
9fd7523e1e92abd108de38b09b2a4cc62bdc466a
c291ae69a84071a2ef4498e1fd9d3bfe858b2a39
/lists/migrations/0002_item_text.py
d01868b305a83e745386c1e023c49eb7d4edc120
[]
no_license
frnnditl/tdd-project
b89dd1f78c50bf34921484d130147abc44d59cd2
b44db65787213160b80905fd3603acf8f17596fe
refs/heads/main
2023-07-09T18:15:02.051074
2021-08-11T02:17:44
2021-08-11T02:17:44
392,816,847
0
0
null
null
null
null
UTF-8
Python
false
false
430
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-08-05 23:27 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('lists', '0001_initial'), ] operations = [ migrations.AddField( model_name='item', name='text', field=models.TextField(default=''), ), ]
ecf95813235c0c0c2163b797af72deef230472e6
925aae508fa819f970aa08650673263be53499b7
/day14/code/main.py
40e3df0bc0faee6d14104bdb11268a3f17190bd6
[ "MIT" ]
permissive
JoseTomasTocino/AdventOfCode2020
b1a8fa044d8d30d6e892b83887dabf706d52792f
19b22c3f9ef2331f08c2ad78f49f200a5f4adfc9
refs/heads/main
2023-02-07T02:49:06.184815
2020-12-25T07:16:48
2020-12-25T07:16:48
317,473,074
0
0
null
null
null
null
UTF-8
Python
false
false
2,678
py
import logging import re logger = logging.getLogger(__name__) def sum_memory_values(inp): mask = None mem_values = {} for line in inp.split("\n"): if line.startswith("mask"): mask = line.split(" = ")[1] logger.info(f"Mask set to {mask}") elif line.startswith("mem"): match = re.match(r"^mem\[(\d+)\] = (\d+)$", line) write_position = int(match.group(1)) write_value = bin(int(match.group(2)))[2:].zfill(len(mask)) logger.info(f"Write at position {write_position}, value = {write_value}") if mask is None: continue actual_value = ''.join([mask[i] if mask[i] != 'X' else write_value[i] for i in range(len(mask))]) logger.info(f" Actual value: {actual_value}") mem_values[write_position] = actual_value return sum(int(x, 2) for x in mem_values.values()) def sum_memory_values_v2(inp): mask = None mem_values = {} for line in inp.split("\n"): if line.startswith("mask"): mask = line.split(" = ")[1] logger.info(f"Mask set to {mask}") elif line.startswith("mem"): match = re.match(r"^mem\[(\d+)\] = (\d+)$", line) write_position = bin(int(match.group(1)))[2:].zfill(len(mask)) write_value = int(match.group(2)) logger.info(f"Write at position: {write_position}, value = {write_value}") # Apply mask to write_position new_write_position = ''.join([write_position[i] if mask[i] == '0' else mask[i] for i in range(len(mask))]) logger.info(f"Actual write position: {new_write_position}") floating_bit_indices = [m.start() for m in re.finditer('X', mask)] logger.info(f"Floating bits positions: {floating_bit_indices}") for i in range(2 ** len(floating_bit_indices)): replacement = bin(i)[2:].zfill(len(floating_bit_indices)) logger.info(f" Replacement: {replacement}") generated_position = list(new_write_position) for j in range(len(floating_bit_indices)): logger.info(f" Rewriting bit at position {floating_bit_indices[j]} with bit {replacement[j]}") generated_position[floating_bit_indices[j]] = replacement[j] generated_position = ''.join(generated_position) logger.info(f" Generated position: {generated_position} (decimal {int(generated_position, 2)})") mem_values[int(generated_position, 2)] = write_value return sum(mem_values.values())
29a36a063b1630bee078dd539e430c484d598da9
c61eb1a59f66d36ad0c2a3dffc172614d9259623
/week1/the_real_deal/bomberman_test.py
5cb62cf6d68e52c87113ddca8c7ae2fc6c96863a
[ "BSD-3-Clause" ]
permissive
sevgo/Programming101
d8361a057f78bc91110082584c7d4cbc05746f10
ac25c4d9695563b449a629c60ec77a739c9f5be3
refs/heads/master
2021-09-28T16:52:22.290888
2021-09-16T07:12:53
2021-09-16T07:12:53
30,528,205
0
0
BSD-3-Clause
2021-09-16T07:12:54
2015-02-09T09:28:31
Python
UTF-8
Python
false
false
633
py
#!/usr/bin/env python3 import unittest import bomberman as bman class Test_Bomberman(unittest.TestCase): def setUp(self): self.matrix = [[1, 2, 3], [4 ,5 ,6], [7, 8, 9]] self.current_position = (2, 1) def test_move_up(self): self.assertIsInstance(bman.move_up(self.current_position), tuple) def test_value_of_new_position(self): x, y = bman.move_up(self.current_position) self.assertEqual(self.matrix[x][y], 5) def test_final_result_type(self): self.assertIsInstance(bman.matrix_bombing_plan(self.matrix), dict) if __name__ == "__main__": unittest.main()
11cd4d65d01665c0d10e4866ca5ef1b2c881800c
be9d18c3ac86921e8899a830ec42d35edd440919
/moztrap/view/runtests/finders.py
233321205408e7918ea9601274a03b83139b0057
[ "BSD-2-Clause" ]
permissive
AlinT/moztrap
abcbf74893d10f7bcf77b4ed44fa77bd017353d6
13927ae3f156b27e4dd064ea37f2feae14728398
refs/heads/master
2021-01-18T08:21:52.894687
2012-09-26T19:54:57
2012-09-26T19:54:57
null
0
0
null
null
null
null
UTF-8
Python
false
false
906
py
""" Finder for running tests. """ from django.core.urlresolvers import reverse from ... import model from ..lists import finder class RunTestsFinder(finder.Finder): template_base = "runtests/finder" columns = [ finder.Column( "products", "_products.html", model.Product.objects.order_by("name"), ), finder.Column( "productversions", "_productversions.html", model.ProductVersion.objects.all(), ), finder.Column( "runs", "_runs.html", model.Run.objects.filter(status=model.Run.STATUS.active), ), ] def child_query_url(self, obj): if isinstance(obj, model.Run): return reverse("runtests_environment", kwargs={"run_id": obj.id}) return super(RunTestsFinder, self).child_query_url(obj)
f6bc22245c7cb103030cdfa5a1ef7c3f73147fed
eebd761d1f298e1917dcbbbe01931fc946da9037
/tests/test_elb_scaler.py
faedccecb19d1f1f19231227473236c89bbf4384
[ "MIT" ]
permissive
rjw1/notifications-paas-autoscaler
9f293b7770f3100360d2b5b3dc3fdd83e4f0875e
753a2e40fd832129dfed4c7d1fce84e7a9ab08ff
refs/heads/master
2023-08-03T09:30:39.081481
2018-12-21T17:15:00
2018-12-21T17:15:00
179,267,030
0
0
MIT
2023-07-22T01:26:52
2019-04-03T10:29:40
Python
UTF-8
Python
false
false
2,843
py
from unittest.mock import patch, Mock import datetime from freezegun import freeze_time from app.elb_scaler import ElbScaler @patch('app.base_scalers.boto3') class TestElbScaler: input_attrs = { 'min_instances': 1, 'max_instances': 2, 'threshold': 1500, 'elb_name': 'notify-paas-proxy', 'request_count_time_range': {'minutes': 10}, } def test_init_assigns_relevant_values(self, mock_boto3): elb_scaler = ElbScaler(**self.input_attrs) assert elb_scaler.min_instances == self.input_attrs['min_instances'] assert elb_scaler.max_instances == self.input_attrs['max_instances'] assert elb_scaler.threshold == self.input_attrs['threshold'] assert elb_scaler.elb_name == self.input_attrs['elb_name'] assert elb_scaler.request_count_time_range == self.input_attrs['request_count_time_range'] def test_cloudwatch_client_initialization(self, mock_boto3): mock_client = mock_boto3.client elb_scaler = ElbScaler(**self.input_attrs) elb_scaler.statsd_client = Mock() assert elb_scaler.cloudwatch_client is None elb_scaler.get_desired_instance_count() assert elb_scaler.cloudwatch_client == mock_client.return_value mock_client.assert_called_with('cloudwatch', region_name='eu-west-1') @freeze_time("2018-03-15 15:10:00") def test_get_desired_instance_count(self, mock_boto3): # set to 5 minutes, to have a smaller mocked response self.input_attrs['request_count_time_range'] = {'minutes': 5} cloudwatch_client = mock_boto3.client.return_value cloudwatch_client.get_metric_statistics.return_value = { 'Datapoints': [ {'Sum': 1500, 'Timestamp': 111111110}, {'Sum': 1600, 'Timestamp': 111111111}, {'Sum': 5500, 'Timestamp': 111111112}, {'Sum': 5300, 'Timestamp': 111111113}, {'Sum': 2100, 'Timestamp': 111111114}, ]} elb_scaler = ElbScaler(**self.input_attrs) elb_scaler.statsd_client = Mock() assert elb_scaler.get_desired_instance_count() == 2 cloudwatch_client.get_metric_statistics.assert_called_once_with( Namespace='AWS/ELB', MetricName='RequestCount', Dimensions=[ { 'Name': 'LoadBalancerName', 'Value': self.input_attrs['elb_name'] }, ], StartTime=elb_scaler._now() - datetime.timedelta(**self.input_attrs['request_count_time_range']), EndTime=elb_scaler._now(), Period=60, Statistics=['Sum'], Unit='Count') elb_scaler.statsd_client.gauge.assert_called_once_with("{}.request-count".format(elb_scaler.app_name), 5500)
ba11fe85c801d07e0e7c25b58d3aee09665d8952
77a7508c3a647711191b924959db80fb6d2bd146
/src/gamesbyexample/worms.py
2bea231d0dbdaeacc62cad083fcc56fafc920fb4
[ "MIT" ]
permissive
surlydev/PythonStdioGames
ff7edb4c8c57a5eb6e2036e2b6ebc7e23ec994e0
d54c2509c12a5b1858eda275fd07d0edd456f23f
refs/heads/master
2021-05-22T21:01:15.529159
2020-03-26T07:34:10
2020-03-26T07:34:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,750
py
"""Worm animation, by Al Sweigart [email protected] A screensaver of multicolor worms moving around. NOTE: Do not resize the terminal window while this program is running. Tags: large, artistic, simulation, bext""" __version__ = 0 import random, shutil, sys, time try: import bext except ImportError: print('''This program requires the bext module, which you can install by opening a Terminal window (on macOS & Linux) and running: python3 -m pip install --user bext or a Command Prompt window (on Windows) and running: python -m pip install --user bext''') sys.exit() # Set up the constants: PAUSE_LENGTH = 0.1 # Get the size of the terminal window: WIDTH, HEIGHT = shutil.get_terminal_size() # We can't print to the last column on Windows without it adding a # newline automatically, so reduce the width by one: WIDTH -= 1 WIDTH //= 2 NUMBER_OF_WORMS = 12 # (!) Try changing this value. MIN_WORM_LENGTH = 6 # (!) Try changing this value. MAX_WORM_LENGTH = 16 # (!) Try changing this value. ALL_COLORS = bext.ALL_COLORS NORTH = 'north' SOUTH = 'south' EAST = 'east' WEST = 'west' BLOCK = chr(9608) # Character 9608 is '█' def main(): # Generate worm data structures: worms = [] for i in range(NUMBER_OF_WORMS): worms.append(Worm()) bext.clear() while True: # Main simulation loop. # Draw quit message. bext.fg('white') bext.goto(0, 0) print('Ctrl-C to quit.', end='') for worm in worms: worm.display() for worm in worms: worm.moveRandom() sys.stdout.flush() time.sleep(PAUSE_LENGTH) class Worm: def __init__(self): self.length = random.randint(MIN_WORM_LENGTH, MAX_WORM_LENGTH) coloration = random.choice(['solid', 'stripe', 'random']) if coloration == 'solid': self.colors = [random.choice(ALL_COLORS)] * self.length elif coloration == 'stripe': color1 = random.choice(ALL_COLORS) color2 = random.choice(ALL_COLORS) self.colors = [] for i in range(self.length): self.colors.append((color1, color2)[i % 2]) elif coloration == 'random': self.colors = [] for i in range(self.length): self.colors.append(random.choice(ALL_COLORS)) x = random.randint(0, WIDTH - 1) y = random.randint(0, HEIGHT - 1) self.body = [] for i in range(self.length): self.body.append((x, y)) x, y = getRandomNeighbor(x, y) def moveNorth(self): headx, heady = self.body[0] if self.isBlocked(NORTH): return False self.body.insert(0, (headx, heady - 1)) self._eraseLastBodySegment() return True def moveSouth(self): headx, heady = self.body[0] if self.isBlocked(SOUTH): return False self.body.insert(0, (headx, heady + 1)) self._eraseLastBodySegment() return True def moveEast(self): headx, heady = self.body[0] if self.isBlocked(EAST): return False self.body.insert(0, (headx + 1, heady)) self._eraseLastBodySegment() return True def moveWest(self): headx, heady = self.body[0] if self.isBlocked(WEST): return False self.body.insert(0, (headx - 1, heady)) self._eraseLastBodySegment() return True def isBlocked(self, direction): headx, heady = self.body[0] if direction == NORTH: return heady == 0 or (headx, heady - 1) in self.body elif direction == SOUTH: return heady == HEIGHT - 1 or (headx, heady + 1) in self.body elif direction == EAST: return headx == WIDTH - 1 or (headx + 1, heady) in self.body elif direction == WEST: return headx == 0 or (headx - 1, heady) in self.body def moveRandom(self): if self.isBlocked(NORTH) and self.isBlocked(SOUTH) and self.isBlocked(EAST) and self.isBlocked(WEST): self.body.reverse() if self.isBlocked(NORTH) and self.isBlocked(SOUTH) and self.isBlocked(EAST) and self.isBlocked(WEST): return False hasMoved = False while not hasMoved: direction = random.choice([NORTH, SOUTH, EAST, WEST]) if direction == NORTH: hasMoved = self.moveNorth() elif direction == SOUTH: hasMoved = self.moveSouth() elif direction == EAST: hasMoved = self.moveEast() elif direction == WEST: hasMoved = self.moveWest() def _eraseLastBodySegment(self): # Erase the last body segment: bext.goto(self.body[-1][0] * 2, self.body[-1][1]) print(' ', end='') self.body.pop() # Delete the last (x, y) tuple in self.body. def display(self): for i, (x, y) in enumerate(self.body): bext.goto(x * 2, y) bext.fg(self.colors[i]) print(BLOCK + BLOCK, end='') def getRandomNeighbor(x, y): while True: direction = random.choice((NORTH, SOUTH, EAST, WEST)) if direction == NORTH and y != 0: return (x, y - 1) elif direction == SOUTH and y != HEIGHT - 1: return (x, y + 1) elif direction == EAST and x != WIDTH - 1: return (x + 1, y) elif direction == WEST and x != 0: return (x - 1, y) # If this program was run (instead of imported), run the game: if __name__ == '__main__': try: main() except KeyboardInterrupt: sys.exit() # When Ctrl-C is pressed, end the program.
0b879b61c2d2b1641c7c52ec97b5e9506509dfd9
300cd7b8c6a4f05c3d1c455d4a37d7a1dd12bd28
/something.py
ead38d2c401f6ef69fdbdb8dc02ed7d85e47230d
[]
no_license
cravenormality/portfolioterm3
5a370b7bfd46f192b1719eee9e0dcbd169e8db6a
0273ab8adeb963fbb3a382e9367666a55e5204c0
refs/heads/master
2020-04-29T01:33:37.442705
2019-03-15T17:02:12
2019-03-15T17:02:12
175,734,716
0
0
null
null
null
null
UTF-8
Python
false
false
3,808
py
class Book: def __init__(self,id,bookName,authorName,nextNode=None): self.id = id self.bookName = bookName self.authorName = authorName self.nextNode = nextNode def getId(self): return self.id def getBookName(self): return self.bookName def getAuthorName(self): return self.authorName def getNextNode(self): return self.nextNode def setNextNode(self,val): self.nextNode = val class LinkedList: def __init__(self,head = None): self.head = head self.size = 0 def getSize(self): return self.size def AddBookToFront(self,newBook): newBook.setNextNode(self.head) self.head = newBook self.size+=1 def DisplayBook(self): curr = self.head while curr: print(curr.getId(),curr.getBookName(),curr.getAuthorName()) curr = curr.getNextNode() def RemoveBookAtPosition(self,n): prev = None curr = self.head curPos = 0 while curr: if curPos == n: if prev: prev.setNextNode(curr.getNextNode()) else: self.head = curr.getNextNode() self.size = self.size - 1 return True prev = curr curr = curr.getNextNode() curPos = curPos + 1 return False def AddBookAtPosition(self,newBook,n): curPos = 1 if n == 0: newBook.setNextNode(self.head) self.head = newBook self.size+=1 return else: currentNode = self.head while currentNode.getNextNode() is not None: if curPos == n: newBook.setNextNode(currentNode.getNextNode()) currentNode.setNextNode(newBook) self.size+=1 return currentNode = currentNode.getNextNode() curPos = curPos + 1 if curPos == n: newBook.setNextNode(None) currentNode.setNextNode(newBook) self.size+=1 else: print("cannot add",newBook.getId(),newBook.getBookName(),"at that position") def SortByAuthorName(self): for i in range(1,self.size): node1 = self.head node2 = node1.getNextNode() while node2 is not None: if node1.authorName > node2.authorName: temp = node1.id temp2 = node1.bookName temp3 = node1.authorName node1.id = node2.id node1.bookName = node2.bookName node1.authorName = node2.authorName node2.id = temp node2.bookName = temp2 node2.authorName = temp3 node1 = node1.getNextNode() node2 = node2.getNextNode() myLinkedList = LinkedList() nodeA = Book("#1","cool","Isaac") nodeB = Book("#2","amazing","Alfred") nodeC = Book("#3","hello","John") nodeD = Book("#4","why","Chase") nodeE = Book("#5","good","Mary") nodeF = Book("#6","hahaha","Radin") myLinkedList.AddBookToFront(nodeA) myLinkedList.AddBookToFront(nodeB) myLinkedList.AddBookToFront(nodeC) myLinkedList.AddBookAtPosition(nodeD,1) myLinkedList.AddBookAtPosition(nodeE,1) myLinkedList.AddBookAtPosition(nodeF,1) myLinkedList.RemoveBookAtPosition(2) myLinkedList.RemoveBookAtPosition(2) myLinkedList.DisplayBook() myLinkedList.SortByAuthorName() print(myLinkedList.getSize()) myLinkedList.DisplayBook()
d6d512c136236a1eaa11f240711e2585c457e14b
a19862a780b9a210be52dab1312fb579d58eb1c4
/Listeners/main.py
77386a9be1038a8c095aa35d8e0c50e707025175
[]
no_license
artbakulev/design_patterns
e8915f5e5f664adbce5a56f5f5c2116c043b45dc
dd958a7539d8c61f6d21030bf462f89d617206bf
refs/heads/master
2021-02-25T20:20:44.378522
2020-03-06T16:06:34
2020-03-06T16:06:34
245,462,206
0
0
null
null
null
null
UTF-8
Python
false
false
655
py
from Listeners.WeatherStation import WeatherStation from Listeners.Widgets import CurrentTemperatureWidget, CurrentHumidityWidget, \ CurrentWindSpeedWidget import threading if __name__ == '__main__': weather_station = WeatherStation() temperature_widget = CurrentTemperatureWidget() humidity_widget = CurrentHumidityWidget() weather_station.add_listener(temperature_widget) weather_station.add_listener(humidity_widget) wind_speed_widget = CurrentWindSpeedWidget(weather_station) wind_speed_widget_thread = threading.Thread(target=wind_speed_widget.run) wind_speed_widget_thread.start() weather_station.run()
ecf839c9ca68216641195e95ef5da5bca7e6347b
2315b173b7a04c8c94b188394aff4656a3b82a9b
/lib/net/rpn.py
d8e3a899db703fd57da78a00b123dd86c96395f7
[ "MIT" ]
permissive
StiphyJay/WS3D
a551b7c169990cf0699ddd48a43d59c1148f2aeb
db90ba12026fb1c4a12e9b791117d6af4ccb052f
refs/heads/master
2022-11-27T23:52:00.387317
2020-08-15T04:58:58
2020-08-15T04:58:58
288,369,260
1
1
MIT
2020-08-18T06:03:39
2020-08-18T06:03:38
null
UTF-8
Python
false
false
3,375
py
import torch.nn as nn import torch.nn.functional as F import numpy as np import pointnet2_lib.pointnet2.pytorch_utils as pt_utils import lib.utils.loss_utils as loss_utils from lib.config import cfg import importlib class RPN(nn.Module): def __init__(self, use_xyz=True, mode='TRAIN',old_model=False): super().__init__() self.training_mode = (mode == 'TRAIN') # backbone network MODEL = importlib.import_module(cfg.RPN.BACKBONE) self.backbone_net = MODEL.get_model(input_channels=int(cfg.RPN.USE_INTENSITY), use_xyz=use_xyz) # classification branch cls_layers = [] pre_channel = cfg.RPN.FP_MLPS[0][-1] for k in range(0, cfg.RPN.CLS_FC.__len__()): cls_layers.append(pt_utils.Conv1d(pre_channel, cfg.RPN.CLS_FC[k], bn=cfg.RPN.USE_BN)) pre_channel = cfg.RPN.CLS_FC[k] cls_layers.append(pt_utils.Conv1d(pre_channel, 1, activation=None)) if cfg.RPN.DP_RATIO >= 0: cls_layers.insert(1, nn.Dropout(cfg.RPN.DP_RATIO)) self.rpn_cls_layer = nn.Sequential(*cls_layers) # regression branch per_loc_bin_num = int(cfg.RPN.LOC_SCOPE / cfg.RPN.LOC_BIN_SIZE) * 2 reg_channel = per_loc_bin_num * 4 if old_model: reg_channel = per_loc_bin_num * 4 + 12 * 2 + 3 reg_channel += 1 reg_layers = [] pre_channel = cfg.RPN.FP_MLPS[0][-1] for k in range(0, cfg.RPN.REG_FC.__len__()): reg_layers.append(pt_utils.Conv1d(pre_channel, cfg.RPN.REG_FC[k], bn=cfg.RPN.USE_BN)) pre_channel = cfg.RPN.REG_FC[k] reg_layers.append(pt_utils.Conv1d(pre_channel, reg_channel, activation=None)) if cfg.RPN.DP_RATIO >= 0: reg_layers.insert(1, nn.Dropout(cfg.RPN.DP_RATIO)) self.rpn_reg_layer = nn.Sequential(*reg_layers) # LOSS defination if cfg.RPN.LOSS_CLS == 'DiceLoss': self.rpn_cls_loss_func = loss_utils.DiceLoss(ignore_target=-1) elif cfg.RPN.LOSS_CLS == 'SigmoidFocalLoss': self.rpn_cls_loss_func = loss_utils.SigmoidFocalClassificationLoss(alpha=cfg.RPN.FOCAL_ALPHA[0], gamma=cfg.RPN.FOCAL_GAMMA) elif cfg.RPN.LOSS_CLS == 'BinaryCrossEntropy': self.rpn_cls_loss_func = F.binary_cross_entropy else: raise NotImplementedError self.init_weights() def init_weights(self): if cfg.RPN.LOSS_CLS in ['SigmoidFocalLoss']: pi = 0.01 nn.init.constant_(self.rpn_cls_layer[2].conv.bias, -np.log((1 - pi) / pi)) nn.init.normal_(self.rpn_reg_layer[-1].conv.weight, mean=0, std=0.001) def forward(self, input_data): """ :param input_data: dict (point_cloud) :return: """ pts_input = input_data['pts_input'] backbone_xyz, backbone_features = self.backbone_net(pts_input) # (B, N, 3), (B, C, N) rpn_cls = self.rpn_cls_layer(backbone_features).transpose(1, 2).contiguous() # (B, N, 1) rpn_reg = self.rpn_reg_layer(backbone_features).transpose(1, 2).contiguous() # (B, N, C) ret_dict = {'rpn_cls': rpn_cls, 'rpn_reg': rpn_reg, 'backbone_xyz': backbone_xyz, 'backbone_features': backbone_features} return ret_dict
39d5d73a87262faab89558aa4446f0842fe38201
80b9a0ed15abb992c93b3d9d4dab2a36243d0708
/player.py
56fae7266e1f99cacea026998ba45c5702a43190
[]
no_license
munir78/80sBeatUmUp
8a1ec049e21086afe0af5d3cbed98c9d745c3b44
576a558bb9dc307cc56edf83c2b700ac07eecb94
refs/heads/master
2020-12-02T19:17:08.597421
2017-08-20T21:24:12
2017-08-20T21:24:12
96,318,567
0
0
null
null
null
null
UTF-8
Python
false
false
464
py
import pygame class Player: x = 200 y = 300 dx = 0 dy = 0 falling = False def update(self, screen): self.x += self.dx self.dx *= 0.9 print(self.dy) self.y += self.dy self.dx = self.dx * 0.8 self.dy = self.dy * 0.8 pygame.draw.rect(screen, (255, 255, 255), (self.x, self.y, 100, 100)) def move(self, dx): self.dx += dx def jump(self, dy): self.dy += dy
9c911e28796afc83e4f20e3b1df900cd2030b006
4c7a2a7896dc8d23d084d6ef7a1212efd45f705c
/EarningsCallsMultipleStacksCNN.py
9155e5261cbafe68e649684abceb0926bac5d4ad
[]
no_license
aditya-radhakrishnan/MGMT_Research
989d6bb487620909bb8d4b5c3ed4d4dd44b55d51
2fe311eba8ee99c05de375cdc31f858765158d80
refs/heads/master
2021-01-19T01:06:42.194930
2016-06-07T16:42:44
2016-06-07T16:42:44
59,845,001
0
0
null
null
null
null
UTF-8
Python
false
false
8,796
py
import numpy as np import tensorflow as tf import math from Preprocessor_Wrapper import PreprocessorWrapper files_list = ['/home/raditya/Documents/untitled folder/multi1.txt', '/home/raditya/Documents/untitled folder/multi1.txt', '/home/raditya/Documents/untitled folder/multi1.txt'] models_list = ['/home/raditya/Documents/untitled folder/multimodel1.txt', '/home/raditya/Documents/untitled folder/multimodel1.txt', '/home/raditya/Documents/untitled folder/multimodel1.txt'] ratios_list = [0.5, 0.25, 0.25] processor = PreprocessorWrapper(files_list, models_list, ratios_list, need_to_make_models=False) preprocessor = processor.get_first_preprocessor() ''' Three independent stacks Two convolutional layers on each stack (max pooling and normalization after each layer) Fully connected layer combines three stacks, followed by dropout One convolutional layer Fully connected layer, followed by dropout Softmax layer ''' # Count of training, test and validation sets num_steps = 10000 # Document dimensions dropout_keep_prob = 0.5 word_length = preprocessor.gensim_maker_obj.get_dimension_of_a_word() num_words = preprocessor.max_num_words train_s1 = processor.get_training_data_from_channel(channel_num=0) train_s2 = processor.get_training_data_from_channel(channel_num=1) train_s3 = processor.get_training_data_from_channel(channel_num=2) train_labels = processor.get_training_data_labels() test_s1 = processor.get_test_data_from_channel(channel_num=0) test_s2 = processor.get_test_data_from_channel(channel_num=1) test_s3 = processor.get_test_data_from_channel(channel_num=2) test_labels = processor.get_test_data_labels() valid_s1 = processor.get_validation_data_from_channel(channel_num=0) valid_s2 = processor.get_validation_data_from_channel(channel_num=1) valid_s3 = processor.get_validation_data_from_channel(channel_num=2) valid_labels = processor.get_validation_data_labels() num_train_docs = train_labels.shape[0] num_test_docs = test_labels.shape[0] num_valid_docs = valid_labels.shape[0] num_labels = train_labels.shape[1] # Neural network constants batch_size = int(math.floor(num_train_docs / 50)) patch_size_s1_c1 = 20 patch_size_s1_c2 = 5 patch_size_s2_c1 = 20 patch_size_s2_c2 = 5 patch_size_s3_c1 = 20 patch_size_s3_c2 = 5 pool_size_s1_c1 = 2 pool_size_s1_c2 = 2 pool_size_s2_c1 = 2 pool_size_s2_c2 = 2 pool_size_s3_c1 = 2 pool_size_s3_c2 = 2 num_feat_s1_c1 = 16 num_feat_s1_c2 = 16 num_feat_s2_c1 = 16 num_feat_s2_c2 = 16 num_feat_s3_c1 = 16 num_feat_s3_c2 = 16 num_full_conn_1 = 32 patch_size_integ = 4 pool_size_integ = 4 num_feat_integ = 8 num_full_conn_2 = 32 beta = 0.01 def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1, dtype=tf.float32) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape, dtype=tf.float32) return tf.Variable(initial) def weight_bias_variables(shape): return weight_variable(shape), bias_variable([shape[len(shape) - 1]]) def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='VALID') def max_pool(x, num_filter_words): return tf.nn.max_pool(x, ksize=[1, 1, num_filter_words, 1], strides=[1, 1, num_filter_words, 1], padding='VALID') def accuracy(predictions, labels): return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) / predictions.shape[0]) graph = tf.Graph() with graph.as_default(): def gen_tf_data_labels(data_stack1, data_stack2, data_stack3, labels): return tf.constant(data_stack1, dtype=tf.float32), tf.constant(data_stack2, dtype=tf.float32), \ tf.constant(data_stack3, dtype=tf.float32), tf.constant(labels, dtype=tf.float32) tf_train_s1 = tf.placeholder(dtype=tf.float32) tf_train_s2 = tf.placeholder(dtype=tf.float32) tf_train_s3 = tf.placeholder(dtype=tf.float32) tf_train_labels = tf.placeholder(dtype=tf.float32) tf_test_s1, tf_test_s2, tf_test_s3, tf_test_labels = gen_tf_data_labels(test_s1, test_s2, test_s3, test_labels) tf_valid_s1, tf_valid_s2, tf_valid_s3, tf_valid_labels = gen_tf_data_labels(valid_s1, valid_s2, valid_s3, valid_labels) ''' Setting up first two convolutional layers for stack 1 ''' def stack_model(tf_stack_data, patch_size_c1, patch_size_c2, num_feat_c1, num_feat_c2, pool_size_c1, pool_size_c2): weights_c1, biases_c1 = weight_bias_variables([word_length, patch_size_c1, 1, num_feat_c1]) weights_c2, biases_c2 = weight_bias_variables([1, patch_size_c2, num_feat_c1, num_feat_c2]) first_conv_dim = int(math.floor((num_words - (patch_size_c1 - 1)) / pool_size_c1)) second_conv_dim = int(math.floor((first_conv_dim - (patch_size_c2 - 1)) / pool_size_c2)) size = second_conv_dim * 1 * num_feat_c2 weights_full_conn1, biases_full_conn1 = weight_bias_variables([size, num_full_conn_1]) h_conv1 = tf.nn.relu(conv2d(tf_stack_data, weights_c1) + biases_c1) h_pool1 = max_pool(h_conv1, pool_size_c1) h_norm1 = tf.nn.local_response_normalization(h_pool1) h_conv2 = tf.nn.relu(conv2d(h_norm1, weights_c2) + biases_c2) h_pool2 = max_pool(h_conv2, pool_size_c2) h_norm2 = tf.nn.local_response_normalization(h_pool2) h_norm2_flat = tf.reshape(h_norm2, [-1, size]) return tf.matmul(h_norm2_flat, weights_full_conn1) + biases_full_conn1 flat_integ_dim = int(math.floor((num_full_conn_1 - (patch_size_integ - 1)) / pool_size_integ)) reshaped_size = flat_integ_dim * num_feat_integ weights_conv_integ, biases_conv_integ = weight_bias_variables([1, patch_size_integ, 1, num_feat_integ]) weights_full_conn2, biases_full_conn2 = weight_bias_variables([reshaped_size, num_full_conn_2]) weights_output, biases_output = weight_bias_variables([num_full_conn_2, num_labels]) def model(tf_s1, tf_s2, tf_s3, keep_prob=tf.constant(1.0)): h_s1 = stack_model(tf_s1, patch_size_s1_c1, patch_size_s1_c2, num_feat_s1_c1, num_feat_s1_c2, pool_size_s1_c1, pool_size_s1_c2) h_s2 = stack_model(tf_s2, patch_size_s2_c1, patch_size_s2_c2, num_feat_s2_c1, num_feat_s2_c2, pool_size_s2_c1, pool_size_s2_c2) h_s3 = stack_model(tf_s3, patch_size_s3_c1, patch_size_s3_c2, num_feat_s3_c1, num_feat_s3_c2, pool_size_s3_c1, pool_size_s3_c2) h_full_conn_1 = tf.nn.relu(h_s1 + h_s2 + h_s3) h_drop1 = tf.nn.dropout(h_full_conn_1, keep_prob) h_reshaped = tf.reshape(h_drop1, [-1, 1, num_full_conn_1, 1]) h_conv_integ = tf.nn.relu(conv2d(h_reshaped, weights_conv_integ) + biases_conv_integ) h_pool_integ = max_pool(h_conv_integ, pool_size_integ) h_norm_integ = tf.nn.local_response_normalization(h_pool_integ) h_flat_integ = tf.reshape(h_norm_integ, [-1, reshaped_size]) h_full_conn2 = tf.nn.relu(tf.matmul(h_flat_integ, weights_full_conn2) + biases_full_conn2) h_drop2 = tf.nn.dropout(h_full_conn2, keep_prob) return tf.matmul(h_drop2, weights_output) + biases_output logits = model(tf_train_s1, tf_train_s2, tf_train_s3, dropout_keep_prob) # Using gradient descent to minimize loss loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels)) loss = tf.reduce_mean(loss + beta * tf.nn.l2_loss(weights_output)) optimizer = tf.train.AdamOptimizer().minimize(loss) train_prediction = tf.nn.softmax(logits) test_prediction = tf.nn.softmax(model(tf_test_s1, tf_test_s2, tf_test_s3)) valid_prediction = tf.nn.softmax(model(tf_valid_s1, tf_valid_s2, tf_valid_s3, dropout_keep_prob)) with tf.Session(graph=graph) as session: tf.initialize_all_variables().run() print('Initialized') for step in range(num_steps): batch_indices = np.random.choice(num_train_docs, size=batch_size, replace=False) batch_s1 = train_s1[batch_indices, :, :, :] batch_s2 = train_s2[batch_indices, :, :, :] batch_s3 = train_s3[batch_indices, :, :, :] batch_labels = train_labels[batch_indices, :] feed_dict = {tf_train_s1: batch_s1, tf_train_s2: batch_s2, tf_train_s3: batch_s3, tf_train_labels: batch_labels} _, l, predictions = session.run([optimizer, loss, train_prediction], feed_dict=feed_dict) if step % 500 == 0: print('Minibatch loss at step %d: %f' % (step, l)) print('Minibatch accuracy: %.1f%%' % accuracy(predictions, batch_labels)) print('Validation accuracy: %.1f%%' % accuracy(valid_prediction.eval(), valid_labels)) print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))
d8c1443a5dde68ef5f215e0ee6e2f1456193d716
f8868b09e6f0c72a5e4c0dc488be7c60865d25d1
/rrt_utils/rrt/rrt_star.py
caa2d31076fe407e582e5dfa7c569faea82fb7c0
[]
no_license
arush/motion-planning-project
8730964493e02edca916ad9e25ba412f7634594f
81836a111186f214273b5569467216e6683ec206
refs/heads/master
2021-05-18T01:05:38.393835
2020-04-02T08:35:12
2020-04-02T08:35:12
251,039,249
0
1
null
null
null
null
UTF-8
Python
false
false
4,887
py
# This file is subject to the terms and conditions defined in # file 'LICENSE', which is part of this source code package. from operator import itemgetter from rrt_utils.rrt.heuristics import cost_to_go from rrt_utils.rrt.heuristics import segment_cost, path_cost from rrt_utils.rrt.rrt import RRT class RRTStar(RRT): def __init__(self, X, Q, x_init, x_goal, max_samples, r, prc=0.01, rewire_count=None): """ RRT* Search :param X: Search Space :param Q: list of lengths of edges added to tree :param x_init: tuple, initial location :param x_goal: tuple, goal location :param max_samples: max number of samples to take :param r: resolution of points to sample along edge when checking for collisions :param prc: probability of checking whether there is a solution :param rewire_count: number of nearby vertices to rewire """ super().__init__(X, Q, x_init, x_goal, max_samples, r, prc) self.rewire_count = rewire_count if rewire_count is not None else 0 self.c_best = float('inf') # length of best solution thus far def get_nearby_vertices(self, tree, x_init, x_new): """ Get nearby vertices to new vertex and their associated path costs from the root of tree as if new vertex is connected to each one separately. :param tree: tree in which to search :param x_init: starting vertex used to calculate path cost :param x_new: vertex around which to find nearby vertices :return: list of nearby vertices and their costs, sorted in ascending order by cost """ X_near = self.nearby(tree, x_new, self.current_rewire_count(tree)) L_near = [(path_cost(self.trees[tree].E, x_init, x_near) + segment_cost(x_near, x_new), x_near) for x_near in X_near] # noinspection PyTypeChecker L_near.sort(key=itemgetter(0)) return L_near def rewire(self, tree, x_new, L_near): """ Rewire tree to shorten edges if possible Only rewires vertices according to rewire count :param tree: int, tree to rewire :param x_new: tuple, newly added vertex :param L_near: list of nearby vertices used to rewire :return: """ for c_near, x_near in L_near: curr_cost = path_cost(self.trees[tree].E, self.x_init, x_near) tent_cost = path_cost(self.trees[tree].E, self.x_init, x_new) + segment_cost(x_new, x_near) if tent_cost < curr_cost and self.X.collision_free(x_near, x_new, self.r): self.trees[tree].E[x_near] = x_new def connect_shortest_valid(self, tree, x_new, L_near): """ Connect to nearest vertex that has an unobstructed path :param tree: int, tree being added to :param x_new: tuple, vertex being added :param L_near: list of nearby vertices """ # check nearby vertices for total cost and connect shortest valid edge for c_near, x_near in L_near: if c_near + cost_to_go(x_near, self.x_goal) < self.c_best and self.connect_to_point(tree, x_near, x_new): break def current_rewire_count(self, tree): """ Return rewire count :param tree: tree being rewired :return: rewire count """ # if no rewire count specified, set rewire count to be all vertices if self.rewire_count is None: return self.trees[tree].V_count # max valid rewire count return min(self.trees[tree].V_count, self.rewire_count) def rrt_star(self): """ Based on algorithm found in: Incremental Sampling-based Algorithms for Optimal Motion Planning http://roboticsproceedings.org/rss06/p34.pdf :return: set of Vertices; Edges in form: vertex: [neighbor_1, neighbor_2, ...] """ self.add_vertex(0, self.x_init) self.add_edge(0, self.x_init, None) while True: for q in self.Q: # iterate over different edge lengths for i in range(q[1]): # iterate over number of edges of given length to add x_new, x_nearest = self.new_and_near(0, q) if x_new is None: continue # get nearby vertices and cost-to-come L_near = self.get_nearby_vertices(0, self.x_init, x_new) # check nearby vertices for total cost and connect shortest valid edge self.connect_shortest_valid(0, x_new, L_near) if x_new in self.trees[0].E: # rewire tree self.rewire(0, x_new, L_near) solution = self.check_solution() if solution[0]: return solution[1]
68c3596f7b0719e22f39a5bb9add3cf40d285973
893f83189700fefeba216e6899d42097cc0bec70
/bioinformatics/photoscan-pro/python/lib/python3.5/site-packages/qtconsole/jupyter_widget.py
c2a8969866d3d2b0203d59d00013fe1e00dc58b6
[ "GPL-3.0-only", "Apache-2.0", "MIT", "Python-2.0" ]
permissive
pseudoPixels/SciWorCS
79249198b3dd2a2653d4401d0f028f2180338371
e1738c8b838c71b18598ceca29d7c487c76f876b
refs/heads/master
2021-06-10T01:08:30.242094
2018-12-06T18:53:34
2018-12-06T18:53:34
140,774,351
0
1
MIT
2021-06-01T22:23:47
2018-07-12T23:33:53
Python
UTF-8
Python
false
false
22,144
py
"""A FrontendWidget that emulates a repl for a Jupyter kernel. This supports the additional functionality provided by Jupyter kernel. """ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. from collections import namedtuple import os.path import re from subprocess import Popen import sys import time from textwrap import dedent from qtconsole.qt import QtCore, QtGui from qtconsole import __version__ from traitlets import Bool, Unicode from .frontend_widget import FrontendWidget from . import styles #----------------------------------------------------------------------------- # Constants #----------------------------------------------------------------------------- # Default strings to build and display input and output prompts (and separators # in between) default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: ' default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: ' default_input_sep = '\n' default_output_sep = '' default_output_sep2 = '' # Base path for most payload sources. zmq_shell_source = 'ipykernel.zmqshell.ZMQInteractiveShell' if sys.platform.startswith('win'): default_editor = 'notepad' else: default_editor = '' #----------------------------------------------------------------------------- # JupyterWidget class #----------------------------------------------------------------------------- class IPythonWidget(FrontendWidget): """Dummy class for config inheritance. Destroyed below.""" class JupyterWidget(IPythonWidget): """A FrontendWidget for a Jupyter kernel.""" # If set, the 'custom_edit_requested(str, int)' signal will be emitted when # an editor is needed for a file. This overrides 'editor' and 'editor_line' # settings. custom_edit = Bool(False) custom_edit_requested = QtCore.Signal(object, object) editor = Unicode(default_editor, config=True, help=""" A command for invoking a system text editor. If the string contains a {filename} format specifier, it will be used. Otherwise, the filename will be appended to the end the command. """) editor_line = Unicode(config=True, help=""" The editor command to use when a specific line number is requested. The string should contain two format specifiers: {line} and {filename}. If this parameter is not specified, the line number option to the %edit magic will be ignored. """) style_sheet = Unicode(config=True, help=""" A CSS stylesheet. The stylesheet can contain classes for: 1. Qt: QPlainTextEdit, QFrame, QWidget, etc 2. Pygments: .c, .k, .o, etc. (see PygmentsHighlighter) 3. QtConsole: .error, .in-prompt, .out-prompt, etc """) syntax_style = Unicode(config=True, help=""" If not empty, use this Pygments style for syntax highlighting. Otherwise, the style sheet is queried for Pygments style information. """) # Prompts. in_prompt = Unicode(default_in_prompt, config=True) out_prompt = Unicode(default_out_prompt, config=True) input_sep = Unicode(default_input_sep, config=True) output_sep = Unicode(default_output_sep, config=True) output_sep2 = Unicode(default_output_sep2, config=True) # JupyterWidget protected class variables. _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number']) _payload_source_edit = 'edit_magic' _payload_source_exit = 'ask_exit' _payload_source_next_input = 'set_next_input' _payload_source_page = 'page' _retrying_history_request = False _starting = False #--------------------------------------------------------------------------- # 'object' interface #--------------------------------------------------------------------------- def __init__(self, *args, **kw): super(JupyterWidget, self).__init__(*args, **kw) # JupyterWidget protected variables. self._payload_handlers = { self._payload_source_edit : self._handle_payload_edit, self._payload_source_exit : self._handle_payload_exit, self._payload_source_page : self._handle_payload_page, self._payload_source_next_input : self._handle_payload_next_input } self._previous_prompt_obj = None self._keep_kernel_on_exit = None # Initialize widget styling. if self.style_sheet: self._style_sheet_changed() self._syntax_style_changed() else: self.set_default_style() #--------------------------------------------------------------------------- # 'BaseFrontendMixin' abstract interface # # For JupyterWidget, override FrontendWidget methods which implement the # BaseFrontend Mixin abstract interface #--------------------------------------------------------------------------- def _handle_complete_reply(self, rep): """Support Jupyter's improved completion machinery. """ self.log.debug("complete: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('complete') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): content = rep['content'] matches = content['matches'] start = content['cursor_start'] end = content['cursor_end'] start = max(start, 0) end = max(end, start) # Move the control's cursor to the desired end point cursor_pos = self._get_input_buffer_cursor_pos() if end < cursor_pos: cursor.movePosition(QtGui.QTextCursor.Left, n=(cursor_pos - end)) elif end > cursor_pos: cursor.movePosition(QtGui.QTextCursor.Right, n=(end - cursor_pos)) # This line actually applies the move to control's cursor self._control.setTextCursor(cursor) offset = end - start # Move the local cursor object to the start of the match and # complete. cursor.movePosition(QtGui.QTextCursor.Left, n=offset) self._complete_with_items(cursor, matches) def _handle_execute_reply(self, msg): """Support prompt requests. """ msg_id = msg['parent_header'].get('msg_id') info = self._request_info['execute'].get(msg_id) if info and info.kind == 'prompt': content = msg['content'] if content['status'] == 'aborted': self._show_interpreter_prompt() else: number = content['execution_count'] + 1 self._show_interpreter_prompt(number) self._request_info['execute'].pop(msg_id) else: super(JupyterWidget, self)._handle_execute_reply(msg) def _handle_history_reply(self, msg): """ Handle history tail replies, which are only supported by Jupyter kernels. """ content = msg['content'] if 'history' not in content: self.log.error("History request failed: %r"%content) if content.get('status', '') == 'aborted' and \ not self._retrying_history_request: # a *different* action caused this request to be aborted, so # we should try again. self.log.error("Retrying aborted history request") # prevent multiple retries of aborted requests: self._retrying_history_request = True # wait out the kernel's queue flush, which is currently timed at 0.1s time.sleep(0.25) self.kernel_client.history(hist_access_type='tail',n=1000) else: self._retrying_history_request = False return # reset retry flag self._retrying_history_request = False history_items = content['history'] self.log.debug("Received history reply with %i entries", len(history_items)) items = [] last_cell = u"" for _, _, cell in history_items: cell = cell.rstrip() if cell != last_cell: items.append(cell) last_cell = cell self._set_history(items) def _insert_other_input(self, cursor, content): """Insert function for input from other frontends""" cursor.beginEditBlock() start = cursor.position() n = content.get('execution_count', 0) cursor.insertText('\n') self._insert_html(cursor, self._make_in_prompt(n)) cursor.insertText(content['code']) self._highlighter.rehighlightBlock(cursor.block()) cursor.endEditBlock() def _handle_execute_input(self, msg): """Handle an execute_input message""" self.log.debug("execute_input: %s", msg.get('content', '')) if self.include_output(msg): self._append_custom(self._insert_other_input, msg['content'], before_prompt=True) def _handle_execute_result(self, msg): """Handle an execute_result message""" if self.include_output(msg): self.flush_clearoutput() content = msg['content'] prompt_number = content.get('execution_count', 0) data = content['data'] if 'text/plain' in data: self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) text = data['text/plain'] # If the repr is multiline, make sure we start on a new line, # so that its lines are aligned. if "\n" in text and not self.output_sep.endswith("\n"): self._append_plain_text('\n', True) self._append_plain_text(text + self.output_sep2, True) def _handle_display_data(self, msg): """The base handler for the ``display_data`` message.""" # For now, we don't display data from other frontends, but we # eventually will as this allows all frontends to monitor the display # data. But we need to figure out how to handle this in the GUI. if self.include_output(msg): self.flush_clearoutput() data = msg['content']['data'] metadata = msg['content']['metadata'] # In the regular JupyterWidget, we simply print the plain text # representation. if 'text/plain' in data: text = data['text/plain'] self._append_plain_text(text, True) # This newline seems to be needed for text and html output. self._append_plain_text(u'\n', True) def _handle_kernel_info_reply(self, rep): """Handle kernel info replies.""" content = rep['content'] self.kernel_banner = content.get('banner', '') if self._starting: # finish handling started channels self._starting = False super(JupyterWidget, self)._started_channels() def _started_channels(self): """Make a history request""" self._starting = True self.kernel_client.kernel_info() self.kernel_client.history(hist_access_type='tail', n=1000) #--------------------------------------------------------------------------- # 'FrontendWidget' protected interface #--------------------------------------------------------------------------- def _process_execute_error(self, msg): """Handle an execute_error message""" content = msg['content'] traceback = '\n'.join(content['traceback']) + '\n' if False: # FIXME: For now, tracebacks come as plain text, so we can't use # the html renderer yet. Once we refactor ultratb to produce # properly styled tracebacks, this branch should be the default traceback = traceback.replace(' ', '&nbsp;') traceback = traceback.replace('\n', '<br/>') ename = content['ename'] ename_styled = '<span class="error">%s</span>' % ename traceback = traceback.replace(ename, ename_styled) self._append_html(traceback) else: # This is the fallback for now, using plain text with ansi escapes self._append_plain_text(traceback) def _process_execute_payload(self, item): """ Reimplemented to dispatch payloads to handler methods. """ handler = self._payload_handlers.get(item['source']) if handler is None: # We have no handler for this type of payload, simply ignore it return False else: handler(item) return True def _show_interpreter_prompt(self, number=None): """ Reimplemented for IPython-style prompts. """ # If a number was not specified, make a prompt number request. if number is None: msg_id = self.kernel_client.execute('', silent=True) info = self._ExecutionRequest(msg_id, 'prompt') self._request_info['execute'][msg_id] = info return # Show a new prompt and save information about it so that it can be # updated later if the prompt number turns out to be wrong. self._prompt_sep = self.input_sep self._show_prompt(self._make_in_prompt(number), html=True) block = self._control.document().lastBlock() length = len(self._prompt) self._previous_prompt_obj = self._PromptBlock(block, length, number) # Update continuation prompt to reflect (possibly) new prompt length. self._set_continuation_prompt( self._make_continuation_prompt(self._prompt), html=True) def _show_interpreter_prompt_for_reply(self, msg): """ Reimplemented for IPython-style prompts. """ # Update the old prompt number if necessary. content = msg['content'] # abort replies do not have any keys: if content['status'] == 'aborted': if self._previous_prompt_obj: previous_prompt_number = self._previous_prompt_obj.number else: previous_prompt_number = 0 else: previous_prompt_number = content['execution_count'] if self._previous_prompt_obj and \ self._previous_prompt_obj.number != previous_prompt_number: block = self._previous_prompt_obj.block # Make sure the prompt block has not been erased. if block.isValid() and block.text(): # Remove the old prompt and insert a new prompt. cursor = QtGui.QTextCursor(block) cursor.movePosition(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor, self._previous_prompt_obj.length) prompt = self._make_in_prompt(previous_prompt_number) self._prompt = self._insert_html_fetching_plain_text( cursor, prompt) # When the HTML is inserted, Qt blows away the syntax # highlighting for the line, so we need to rehighlight it. self._highlighter.rehighlightBlock(cursor.block()) self._previous_prompt_obj = None # Show a new prompt with the kernel's estimated prompt number. self._show_interpreter_prompt(previous_prompt_number + 1) #--------------------------------------------------------------------------- # 'JupyterWidget' interface #--------------------------------------------------------------------------- def set_default_style(self, colors='lightbg'): """ Sets the widget style to the class defaults. Parameters ---------- colors : str, optional (default lightbg) Whether to use the default light background or dark background or B&W style. """ colors = colors.lower() if colors=='lightbg': self.style_sheet = styles.default_light_style_sheet self.syntax_style = styles.default_light_syntax_style elif colors=='linux': self.style_sheet = styles.default_dark_style_sheet self.syntax_style = styles.default_dark_syntax_style elif colors=='nocolor': self.style_sheet = styles.default_bw_style_sheet self.syntax_style = styles.default_bw_syntax_style else: raise KeyError("No such color scheme: %s"%colors) #--------------------------------------------------------------------------- # 'JupyterWidget' protected interface #--------------------------------------------------------------------------- def _edit(self, filename, line=None): """ Opens a Python script for editing. Parameters ---------- filename : str A path to a local system file. line : int, optional A line of interest in the file. """ if self.custom_edit: self.custom_edit_requested.emit(filename, line) elif not self.editor: self._append_plain_text('No default editor available.\n' 'Specify a GUI text editor in the `JupyterWidget.editor` ' 'configurable to enable the %edit magic') else: try: filename = '"%s"' % filename if line and self.editor_line: command = self.editor_line.format(filename=filename, line=line) else: try: command = self.editor.format() except KeyError: command = self.editor.format(filename=filename) else: command += ' ' + filename except KeyError: self._append_plain_text('Invalid editor command.\n') else: try: Popen(command, shell=True) except OSError: msg = 'Opening editor with command "%s" failed.\n' self._append_plain_text(msg % command) def _make_in_prompt(self, number): """ Given a prompt number, returns an HTML In prompt. """ try: body = self.in_prompt % number except TypeError: # allow in_prompt to leave out number, e.g. '>>> ' from xml.sax.saxutils import escape body = escape(self.in_prompt) return '<span class="in-prompt">%s</span>' % body def _make_continuation_prompt(self, prompt): """ Given a plain text version of an In prompt, returns an HTML continuation prompt. """ end_chars = '...: ' space_count = len(prompt.lstrip('\n')) - len(end_chars) body = '&nbsp;' * space_count + end_chars return '<span class="in-prompt">%s</span>' % body def _make_out_prompt(self, number): """ Given a prompt number, returns an HTML Out prompt. """ try: body = self.out_prompt % number except TypeError: # allow out_prompt to leave out number, e.g. '<<< ' from xml.sax.saxutils import escape body = escape(self.out_prompt) return '<span class="out-prompt">%s</span>' % body #------ Payload handlers -------------------------------------------------- # Payload handlers with a generic interface: each takes the opaque payload # dict, unpacks it and calls the underlying functions with the necessary # arguments. def _handle_payload_edit(self, item): self._edit(item['filename'], item['line_number']) def _handle_payload_exit(self, item): self._keep_kernel_on_exit = item['keepkernel'] self.exit_requested.emit(self) def _handle_payload_next_input(self, item): self.input_buffer = item['text'] def _handle_payload_page(self, item): # Since the plain text widget supports only a very small subset of HTML # and we have no control over the HTML source, we only page HTML # payloads in the rich text widget. data = item['data'] if 'text/html' in data and self.kind == 'rich': self._page(data['text/html'], html=True) else: self._page(data['text/plain'], html=False) #------ Trait change handlers -------------------------------------------- def _style_sheet_changed(self): """ Set the style sheets of the underlying widgets. """ self.setStyleSheet(self.style_sheet) if self._control is not None: self._control.document().setDefaultStyleSheet(self.style_sheet) bg_color = self._control.palette().window().color() self._ansi_processor.set_background_color(bg_color) if self._page_control is not None: self._page_control.document().setDefaultStyleSheet(self.style_sheet) def _syntax_style_changed(self): """ Set the style for the syntax highlighter. """ if self._highlighter is None: # ignore premature calls return if self.syntax_style: self._highlighter.set_style(self.syntax_style) else: self._highlighter.set_style_sheet(self.style_sheet) #------ Trait default initializers ----------------------------------------- def _banner_default(self): return "Jupyter QtConsole {version}\n".format(version=__version__) # clobber IPythonWidget above: class IPythonWidget(JupyterWidget): """Deprecated class. Use JupyterWidget""" def __init__(self, *a, **kw): warn("IPythonWidget is deprecated, use JupyterWidget") super(IPythonWidget, self).__init__(*a, **kw)
b2c759567b93cac768c610e6337ebe2ca19626e0
735a315ea82893f2acd5ac141f1a9b8be89f5cb9
/pylib/v6.1.84/mdsscalar.py
7cf7fe6e0ba174ecd9dc55b37dbdca77b5786088
[]
no_license
drsmith48/pppl-mdsplus-python
5ce6f7ccef4a23ea4b8296aa06f51f3a646dd36f
0fb5100e6718c8c10f04c3aac120558f521f9a59
refs/heads/master
2021-07-08T02:29:59.069616
2017-10-04T20:17:32
2017-10-04T20:17:32
105,808,853
0
0
null
null
null
null
UTF-8
Python
false
false
7,108
py
if '__package__' not in globals() or __package__ is None or len(__package__)==0: def _mimport(name,level): return __import__(name,globals()) else: def _mimport(name,level): return __import__(name,globals(),{},[],level) import numpy,copy _dtypes=_mimport('_mdsdtypes',1) _data=_mimport('mdsdata',1) def makeScalar(value): if isinstance(value,str): return String(value) if isinstance(value,Scalar): return copy.deepcopy(value) if isinstance(value,numpy.generic): if isinstance(value,numpy.string_): return String(value) try: if isinstance(value,numpy.bytes_): return String(str(value,encoding='utf8')) except: pass if isinstance(value,numpy.bool_): return makeScalar(int(value)) return globals()[value.__class__.__name__.capitalize()](value) try: if isinstance(value,long): return Int64(value) if isinstance(value,int): return Int32(value) except: if isinstance(value,int): return Int64(value) if isinstance(value,float): return Float32(value) if isinstance(value,str): return String(value) if isinstance(value,bytes): return String(value.decode()) if isinstance(value,bool): return Int8(int(value)) if isinstance(value,complex): return Complex128(numpy.complex128(value)) if isinstance(value,numpy.complex64): return Complex64(value) if isinstance(value,numpy.complex128): return Complex128(value) raise TypeError('Cannot make Scalar out of '+str(type(value))) class Scalar(_data.Data): def __new__(cls,value=0): try: import numpy _array=_mimport('mdsarray',1) if (isinstance(value,_array.Array)) or isinstance(value,list) or isinstance(value,numpy.ndarray): return _array.__dict__[cls.__name__+'Array'](value) except: pass return super(Scalar,cls).__new__(cls) def __init__(self,value=0): if self.__class__.__name__ == 'Scalar': raise TypeError("cannot create 'Scalar' instances") if self.__class__.__name__ == 'String': self._value=numpy.string_(value) return self._value=numpy.__dict__[self.__class__.__name__.lower()](value) def __getattr__(self,name): return self._value.__getattribute__(name) def _getValue(self): """Return the numpy scalar representation of the scalar""" return self._value value=property(_getValue) def __str__(self): formats={'Int8':'%dB','Int16':'%dW','Int32':'%d','Int64':'0X%0xQ', 'Uint8':'%uBU','Uint16':'%uWU','Uint32':'%uLU','Uint64':'0X%0xQU', 'Float32':'%g'} ans=formats[self.__class__.__name__] % (self._value,) if ans=='nan': ans="$ROPRAND" elif isinstance(self,Float32) and ans.find('.')==-1: ans=ans+"." return ans def decompile(self): return str(self) def __int__(self): """Integer: x.__int__() <==> int(x) @rtype: int""" return self._value.__int__() def __long__(self): """Long: x.__long__() <==> long(x) @rtype: int""" return self.__value.__long__() def _unop(self,op): return _data.makeData(getattr(self.value,op)()) def _binop(self,op,y): try: y=y.value except AttributeError: pass ans=getattr(self.value,op)(y) return _data.makeData(ans) def _triop(self,op,y,z): try: y=y.value except AttributeError: pass try: z=z.value except AttributeError: pass return _data.makeData(getattr(self.value,op)(y,z)) def _getMdsDtypeNum(self): return {'Uint8':DTYPE_BU,'Uint16':DTYPE_WU,'Uint32':DTYPE_LU,'Uint64':DTYPE_QU, 'Int8':DTYPE_B,'Int16':DTYPE_W,'Int32':DTYPE_L,'Int64':DTYPE_Q, 'String':DTYPE_T, 'Float32':DTYPE_FS, 'Float64':DTYPE_FT,'Complex64':DTYPE_FSC,'Complex128':DTYPE_FTC}[self.__class__.__name__] mdsdtype=property(_getMdsDtypeNum) def all(self): return self._unop('all') def any(self): return self._unop('any') def argmax(self,*axis): if axis: return self._binop('argmax',axis[0]) else: return self._unop('argmax') def argmin(self,*axis): if axis: return self._binop('argmin',axis[0]) else: return self._unop('argmin') def argsort(self,axis=-1,kind='quicksort',order=None): return _data.makeData(self.value.argsort(axis,kind,order)) def astype(self,type): return _data.makeData(self.value.astype(type)) def byteswap(self): return self._unop('byteswap') def clip(self,y,z): return self._triop('clip',y,z) class Int8(Scalar): """8-bit signed number""" class Int16(Scalar): """16-bit signed number""" class Int32(Scalar): """32-bit signed number""" class Int64(Scalar): """64-bit signed number""" class Uint8(Scalar): """8-bit unsigned number""" class Uint16(Scalar): """16-bit unsigned number""" class Uint32(Scalar): """32-bit unsigned number""" class Uint64(Scalar): """64-bit unsigned number""" def _getDate(self): return _data.Data.execute('date_time($)',self) date=property(_getDate) class Float32(Scalar): """32-bit floating point number""" class Complex64(Scalar): """32-bit complex number""" def __str__(self): return "Cmplx(%g,%g)" % (self._value.real,self._value.imag) class Float64(Scalar): """64-bit floating point number""" def __str__(self): return ("%E" % self._value).replace("E","D") class Complex128(Scalar): """64-bit complex number""" def __str__(self): return "Cmplx(%s,%s)" % (str(Float64(self._value.real)),str(Float64(self._value.imag))) class String(Scalar): """String""" def __radd__(self,y): """Reverse add: x.__radd__(y) <==> y+x @rtype: Data""" return self.execute('$//$',y,self) def __add__(self,y): """Add: x.__add__(y) <==> x+y @rtype: Data""" return self.execute('$//$',self,y) def __str__(self): """String: x.__str__() <==> str(x) @rtype: String""" if len(self._value) > 0: return str(self.value.tostring().decode()) else: return '' def __len__(self): return len(str(self)) def decompile(self): if len(self._value) > 0: return repr(self._value.tostring()) else: return "''" class Int128(Scalar): """128-bit number""" def __init__(self): raise TypeError("Int128 is not yet supported") class Uint128(Scalar): """128-bit unsigned number""" def __init__(self): raise TypeError("Uint128 is not yet supported")
066a1a08d39f24abbd696adde173c63c13eaef9c
52022b2780a257e1de5c551e2f0e2a2ecdceb8b7
/crypto/analyser/final/data/Integration.py
2fcaf91b104ba5817e5862d5893ebed26cebb1b9
[]
no_license
pyqpyqpyq/Cryptocurrency-Analytics-Based-on-Machine-Learning
9e84b73e6e496b32abed29aecf97eb44c9682ed4
c4334af7984deab02594db2766702490d79159ea
refs/heads/master
2023-05-10T19:06:31.756084
2019-10-31T09:51:07
2019-10-31T09:51:07
218,730,013
0
0
null
2023-05-07T04:06:03
2019-10-31T09:31:28
Jupyter Notebook
UTF-8
Python
false
false
10,065
py
import pymongo import pandas as pd from datetime import datetime, timedelta, date, time as dtime import gc import logging import os, pickle import time import numpy as np def save_pickle(data, filepath): save_documents = open(filepath, 'wb') pickle.dump(data, save_documents) save_documents.close() def load_pickle(filepath): documents_f = open(filepath, 'rb') file = pickle.load(documents_f) documents_f.close() return file def gover_sentiment(username, sentiment): if username in gov_list: if sentiment == '+': return '+' elif sentiment == '-': return '-' return '0' def percentage(dfnew, history): df1 = dfnew.sentiment.to_dict() df2 = {} for i, x in df1.items(): if x['compound'] > 0: df2[i] = '+' elif x['compound'] == 0: df2[i] = '' else: df2[i] = '-' df3new = pd.DataFrame.from_dict(df2, orient='index') dfnew['New'] = df3new # history if history == 1: dfnew['timestamp'] = pd.to_datetime(dfnew['timestamp'], format='%Y-%m-%d') frequence = 'M' dfnew['media'] = dfnew.apply(lambda row: judge(row['fullname'], row['likes'], row['replies'], row['retweets']), axis=1) dfnew['GovSen'] = dfnew.apply(lambda row: gover_sentiment(row['fullname'], row['New']), axis=1) # recent stream elif history == 2: dfnew['timestamp'] = dfnew['timestamp_ms'].apply(lambda row: datetime.fromtimestamp(float(row) / 1000.0)) frequence = 'D' name = dfnew['user'].to_dict() n = {} for i, x in name.items(): n[i] = x['name'] dfnew['name'] = pd.DataFrame.from_dict(n, orient='index') dfnew['media'] = dfnew.apply( lambda row: judge(row['name'], row['favorite_count'], row['reply_count'], row['retweet_count']), axis=1) dfnew['GovSen'] = dfnew.apply(lambda row: gover_sentiment(row['name'], row['New']),axis=1) # archive else: dfnew['timestamp'] = pd.to_datetime(dfnew['created_at'], infer_datetime_format=True) dfnew['timestamp'] = dfnew['timestamp'].dt.date dfnew['timestamp'] = pd.to_datetime(dfnew['timestamp'], format='%Y-%m-%d') frequence = 'M' name = dfnew['user'].to_dict() n = {} for i, x in name.items(): n[i] = x['name'] dfnew['name'] = pd.DataFrame.from_dict(n, orient='index') dfnew['media'] = dfnew.apply( lambda row: judge(row['name'], row['favorite_count'], row['reply_count'], row['retweet_count']), axis=1) dfnew['GovSen'] = dfnew.apply(lambda row: gover_sentiment(row['name'], row['New']), axis=1) neu = dfnew.groupby([pd.Grouper(key='timestamp', freq=frequence, label='left')])['New'].apply( lambda x: (x == '').sum()).reset_index(name='neu') pos = dfnew.groupby([pd.Grouper(key='timestamp', freq=frequence, label='left')])['New'].apply( lambda x: (x == '+').sum()).reset_index(name='pos') neg = dfnew.groupby([pd.Grouper(key='timestamp', freq=frequence, label='left')])['New'].apply( lambda x: (x == '-').sum()).reset_index(name='neg') total = dfnew.groupby([pd.Grouper(key='timestamp', freq=frequence, label='left')]).size().reset_index(name='total') medium_influence = dfnew.groupby([pd.Grouper(key='timestamp', freq=frequence, label='left')])['media'].apply( lambda x: (x == '1').sum()).reset_index(name='MInfluence') Govpos = dfnew.groupby([pd.Grouper(key='timestamp', freq=frequence, label='left')])['GovSen'].apply( lambda x: (x == '+').sum()).reset_index(name='Govpos') Govneg = dfnew.groupby([pd.Grouper(key='timestamp', freq=frequence, label='left')])['GovSen'].apply( lambda x: (x == '-').sum()).reset_index(name='Govneg') Govtotal = dfnew.groupby([pd.Grouper(key='timestamp', freq=frequence, label='left')])['GovSen'].apply( lambda x: (x != '0').sum()).reset_index(name='Govtotal') dfnew = pd.merge(neu, pos) dfnew = pd.merge(dfnew, neg) dfnew = pd.merge(dfnew, total) dfnew = pd.merge(dfnew, medium_influence) dfnew = pd.merge(dfnew, Govpos) dfnew = pd.merge(dfnew, Govneg) dfnew = pd.merge(dfnew, Govtotal) dfnew['neu%'] = dfnew['neu'] / dfnew['total'] dfnew['pos%'] = dfnew['pos'] / dfnew['total'] dfnew['neg%'] = dfnew['neg'] / dfnew['total'] dfnew['Govpos%'] = (dfnew['Govpos']/dfnew['Govtotal']).replace(np.nan, 0) dfnew['Govneg%'] = (dfnew['Govneg']/dfnew['Govtotal']).replace(np.nan, 0) dfnew = dfnew.dropna() dfnew = dfnew.reset_index() dfnew = dfnew.drop(columns=['index']) return dfnew def difference(history): history['pos_change'] = history['pos%'].diff() history['neg_change'] = history['neg%'].diff() history['Govpos_change'] = history['Govpos%'].diff() history['Govneg_change'] = history['Govneg%'].diff() history['GovIspos'] = history['Govpos_change'].apply(lambda x: tag(x)) history['GovIsneg'] = history['Govneg_change'].apply(lambda x: tag(x)) history['Ispos'] = history['pos_change'].apply(lambda x: tag(x)) history['Isneg'] = history['neg_change'].apply(lambda x: tag(x)) # history['timestamp'] = history.index # history.index = history['timestamp'] # history = history.set_index('timestamp').resample('D').ffill() return history def tag(context): if context is None: return 0 elif context > 0: return 1 return 0 gov_list = ['KUCOIN', 'Bitcoin', 'The Onion', 'Coinbase', 'CoinPulse Exchange', 'The Spectator Index', 'Netkoin', 'Substratum', 'Bitcoin Turbo Koin', 'Crypto Airdrops', 'Bethereum', 'PO8', 'CCN.com', 'The FREE COIN', 'CryptoTown', 'CryptoPuppies', 'OPEN Platform', 'Bitstamp', 'Phore Blockchain', 'CoinDesk', 'cotrader.com', 'Altcoins Talks', 'Crypto Rand', 'Cointelegraph', 'CryptoKing', 'Crypto Boss', 'INSCoin', 'eBTCS', 'CNBC', 'The Economist', 'ABCC Exchange', 'BitPlay™', 'WuxinBTC-NEWS', 'InvestInBlockchain.com', 'Bitcoin Modern Vision', 'ABCC Exchange', 'Storm Play', 'Bitcoin Plus Cash', 'Altcoin.io Exchange', 'CoinBene Global', 'Cryptelo', 'Coincheck(コインチェック)', 'MarketWatch', 'CryptoCret | Bitcoin and Cryptocurrency News', 'NeedsCoin', 'Poloniex Exchange', 'Crypto Currency', 'Cash App'] def judge(fullname, likes, replies, retweets): if fullname in gov_list: return '2' elif likes>9 and replies>3 and retweets>8: return '1' else: return '0' try: gc.enable() logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) file_handler = logging.FileHandler('sentiment.log') formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) logger.addHandler(file_handler) logger.info('============================================') start_date = datetime.combine(date.today() - timedelta(days=1), dtime(14, 0)) end_date = datetime.combine(date.today(), dtime(14, 0)) logger.info("Start date: {}; end date: {}.".format((start_date + timedelta(days=1)).strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d'))) client = pymongo.MongoClient('localhost', 27017) db = client['twitter_db'] file_extraction_start = time.time() # collection = db['twitter_collection_2016-2018'] # history = pd.DataFrame(list(collection.find())) # history = percentage(history, 1) # collection = db['twitter_collection_5_8_17'] # archive = pd.DataFrame(list(collection.find())) # archive = percentage(archive, 0) # collection = db['twitter_collection_13_10'] # archiveold = pd.DataFrame(list(collection.find())) # archiveold = percentage(archiveold, 0) history=load_pickle(os.path.join('history1.p')) collection = db['twitter_collection'] recent = pd.DataFrame(list(collection.find())) recent = percentage(recent, 2) # history = pd.concat([archiveold, history], sort=True) # history = pd.concat([history, archive], sort=True) history = pd.concat([history, recent], sort=True) history.index = history['timestamp'] history.sort_index(inplace=True) # # datetime_object = datetime.strptime('Sep 13 2011', '%b %d %Y') # # # print(history.iloc[0]) # # history.loc[0] = [0, 0, 5, 1, 5, 0, 455, 0.080000, 3450, 0.630000, 1640, 0.298182, datetime_object, 5500] # # print('second') # # print(history) # # history.sort_index(inplace=True) history=difference(history) # if history['timestamp'].iloc[len(history)-1].date()==datetime.now().date(): # history.drop(history.tail(1).index, inplace = True) datetime1 = datetime.strftime(datetime.now() - timedelta(1), '%Y-%m-%d') new = history.iloc[len(history) - 1] new = new.to_dict() history = history.append(pd.DataFrame(new, index=[datetime1])) history['timestamp'] = history.index history.index = history['timestamp'] history = history.drop_duplicates(subset='timestamp', keep="first") history = history.resample('D').ffill() history['timestamp'] = history.index old = load_pickle(os.path.join("../data/stock_price.p")) history['date'] = history.index old['date'] = old.index history = pd.merge(old, history, how='left') history.index = history['timestamp'] print(history) save_pickle(history, os.path.join('final.p')) file_extraction_end = time.time() # # client = pymongo.MongoClient('localhost', 27017) # # db = client['twitter_backup'] # # collection = db['ProcessBackup'] # # collection.insert_many(history.to_dict('records')) logger.info("Final sentiment saved. Time takes {}s.".format(str(file_extraction_end-file_extraction_start))) gc.collect() except Exception as e: logger.error(e)
5f6ac666d9265fdaba9d9dffc042793d684732b2
a3ee120ce3b32d20184df44eeb35b38a3423e322
/image_utils.py
8d4098ab115428b822978bf48c6d852ba87f4a0b
[ "MIT" ]
permissive
Ikhwansong/ComputerSoftware_OCR
6857b3af121c5b7767893e72c7a10b27ef77ac87
e1664c7fd6081e00e39d9b5fbc48e902bbb5fdfc
refs/heads/master
2022-10-21T02:36:43.333591
2020-06-11T20:13:40
2020-06-11T20:13:40
271,306,157
0
0
null
null
null
null
UTF-8
Python
false
false
7,139
py
import os from PIL import Image import matplotlib.pyplot as plt import matplotlib.patches as patches import random import numpy as np import tensorflow as tf import math import cv2 from box_utils import compute_iou class ImageVisualizer_cv2(object): def __init__(self, idx_to_name, class_colors = None, save_dir = None): self.idx_to_name = idx_to_name self.color_matrix = self._colorizing() self.color_matrix = np.random.shuffle(self.color_matrix) if save_dir is None: self.save_dir = './' else: self.save_dir = save_dir os.makedirs(self.save_dir, exist_ok=True) def _colorizing(self,): factor = math.floor(math.pow(len(self.idx_to_name), 1/3)) color_divider = 255/factor color_matrix = np.zeros(((factor+1)*(factor+1)*(factor+1),3)) index = 0 for x in range(factor+1): for y in range(factor+1) : for z in range(factor+1) : color_matrix[index,:] = np.array([x*color_divider, y*color_divider, z*color_divider]) index = index + 1 return color_matrix[1:-1] def save_image(self, img_path, boxes, labels, name): img = cv2.imread(img_path) save_path = os.path.join(self.save_dir, name) for i, box in enumerate(boxes): idx = labels[i] -1 cls_name = self.idx_to_name[idx] top_left = (box[0], box[1]) bot_right = (box[2], box[3]) cv2.rectangle(img,top_left, bot_right, self.color_matrix[idx], 1 ) cv2.putText(img, cls_name, top_left,1, (255,255,255), 1) cv2.imwrite(save_path, img) class ImageVisualizer(object): """ Class for visualizing image Attributes: idx_to_name: list to convert integer to string label class_colors: colors for drawing boxes and labels save_dir: directory to store images """ def __init__(self, idx_to_name, class_colors=None, save_dir=None): self.idx_to_name = idx_to_name if class_colors is None or len(class_colors) != len(self.idx_to_name): self.class_colors = [[0, 255, 0]] * len(self.idx_to_name) else: self.class_colors = class_colors if save_dir is None: self.save_dir = './' else: self.save_dir = save_dir os.makedirs(self.save_dir, exist_ok=True) def save_image(self, img, boxes, labels, name): """ Method to draw boxes and labels then save to dir Args: img: numpy array (width, height, 3) boxes: numpy array (num_boxes, 4) labels: numpy array (num_boxes) name: name of image to be saved """ plt.figure() fig, ax = plt.subplots(1) ax.imshow(img) save_path = os.path.join(self.save_dir, name) for i, box in enumerate(boxes): idx = labels[i] - 1 cls_name = self.idx_to_name[idx] top_left = (box[0], box[1]) bot_right = (box[2], box[3]) ax.add_patch(patches.Rectangle( (box[0], box[1]), box[2] - box[0], box[3] - box[1], linewidth=2, edgecolor=(0., 1., 0.), facecolor="none")) plt.text( box[0], box[1], s=cls_name, fontsize = 'small', color="white", verticalalignment="top", bbox={"color": (0., 1., 0.), "pad": 0}, ) plt.axis("off") # plt.gca().xaxis.set_major_locator(NullLocator()) # plt.gca().yaxis.set_major_locator(NullLocator()) plt.savefig(save_path, bbox_inches="tight", pad_inches=0.0) plt.close('all') def generate_patch(boxes, threshold): """ Function to generate a random patch within the image If the patch overlaps any gt boxes at above the threshold, then the patch is picked, otherwise generate another patch Args: boxes: box tensor (num_boxes, 4) threshold: iou threshold to decide whether to choose the patch Returns: patch: the picked patch ious: an array to store IOUs of the patch and all gt boxes """ while True: patch_w = random.uniform(0.1, 1) scale = random.uniform(0.5, 2) patch_h = patch_w * scale patch_xmin = random.uniform(0, 1 - patch_w) patch_ymin = random.uniform(0, 1 - patch_h) patch_xmax = patch_xmin + patch_w patch_ymax = patch_ymin + patch_h patch = np.array( [[patch_xmin, patch_ymin, patch_xmax, patch_ymax]], dtype=np.float32) patch = np.clip(patch, 0.0, 1.0) ious = compute_iou(tf.constant(patch), boxes) if tf.math.reduce_any(ious >= threshold): break return patch[0], ious[0] def random_patching(img, boxes, labels): """ Function to apply random patching Firstly, a patch is randomly picked Then only gt boxes of which IOU with the patch is above a threshold and has center point lies within the patch will be selected Args: img: the original PIL Image boxes: gt boxes tensor (num_boxes, 4) labels: gt labels tensor (num_boxes,) Returns: img: the cropped PIL Image boxes: selected gt boxes tensor (new_num_boxes, 4) labels: selected gt labels tensor (new_num_boxes,) """ threshold = np.random.choice(np.linspace(0.1, 0.7, 4)) patch, ious = generate_patch(boxes, threshold) box_centers = (boxes[:, :2] + boxes[:, 2:]) / 2 keep_idx = ( (ious > 0.3) & (box_centers[:, 0] > patch[0]) & (box_centers[:, 1] > patch[1]) & (box_centers[:, 0] < patch[2]) & (box_centers[:, 1] < patch[3]) ) if not tf.math.reduce_any(keep_idx): return img, boxes, labels img = img.crop(patch) boxes = boxes[keep_idx] patch_w = patch[2] - patch[0] patch_h = patch[3] - patch[1] boxes = tf.stack([ (boxes[:, 0] - patch[0]) / patch_w, (boxes[:, 1] - patch[1]) / patch_h, (boxes[:, 2] - patch[0]) / patch_w, (boxes[:, 3] - patch[1]) / patch_h], axis=1) boxes = tf.clip_by_value(boxes, 0.0, 1.0) labels = labels[keep_idx] return img, boxes, labels def horizontal_flip(img, boxes, labels): """ Function to horizontally flip the image The gt boxes will be need to be modified accordingly Args: img: the original PIL Image boxes: gt boxes tensor (num_boxes, 4) labels: gt labels tensor (num_boxes,) Returns: img: the horizontally flipped PIL Image boxes: horizontally flipped gt boxes tensor (num_boxes, 4) labels: gt labels tensor (num_boxes,) """ img = img.transpose(Image.FLIP_LEFT_RIGHT) boxes = tf.stack([ 1 - boxes[:, 2], boxes[:, 1], 1 - boxes[:, 0], boxes[:, 3]], axis=1) return img, boxes, labels
5418444e1b1cde83a6aa6d7cba881c88dbc6d153
9eb00b3947fdaa4b0ae6ac446b7619076ab2d22e
/digital_acquisition.py
f7b6287fa0ebb2c41ab45a52050b82589ce4fae3
[]
no_license
boffomarco/RobPerc-Act_19-20_14
ecae98d0f79044661a1318df74696ed95de7b1e1
f2775572fad43ab89cad51b9761086dbfc6acea5
refs/heads/master
2022-08-01T09:09:36.323964
2020-05-27T10:07:17
2020-05-27T10:07:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,686
py
'''This file contains the method to acquire the data of the current converted in digital by the Arduino''' import RPi.GPIO as GPIO import time import csv DEBUG_MODE=False GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #arduino 2 corresponding to 20 pin GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #arduino 5 GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # 4 GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #3 GPIO.setup(9, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #arduino 2 corresponding to 2^0 pin GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #arduino 5 GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # 4 GPIO.setup(6, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #3 GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #arduino 2 corresponding to 2^0 pin GPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #arduino 5 '''Function to read the data received from the Arduino and to convert them in the corrisponding value in ampere''' def read_current(): val = GPIO.input(17)+GPIO.input(27)*2**1+GPIO.input(22)*2**2+GPIO.input(10)*2**3+GPIO.input(9)*2**4+GPIO.input(11)*2**5+GPIO.input(5)*2**6+GPIO.input(6)*2**7+GPIO.input(13)*2**8+GPIO.input(19)*2**9 voltage = val * (5.0 / 1023.0) #Sensitivity of the sensor: 625 mV/Ipn. Ipn = 50A, so the slope is 12.5 mV/A offset = 2.455 # Biased sensor val = (voltage-offset)/0.0125 return val #Old procedure used to test the data acquisition. Not used anymore''' # def old_procedure(): # try: # f = open("arduino.csv.txt", "w+") # writer = csv.writer(f) # head = ["value"] # writer.writerow(head) # while(True): # #print(GPIO.input(10)) # # Get the value # val = GPIO.input(17)+GPIO.input(27)*2**1+GPIO.input(22)*2**2+GPIO.input(10)*2**3+GPIO.input(9)*2**4+GPIO.input(11)*2**5+GPIO.input(5)*2**6+GPIO.input(6)*2**7+GPIO.input(13)*2**8+GPIO.input(19)*2**9 # writer.writerow(str(val)) # print(str(val)) # # if(DEBUG_MODE): # print(GPIO.input(17)) # print(GPIO.input(27)) # print(GPIO.input(22)) # print(GPIO.input(10)) # print(GPIO.input(9)) # print(GPIO.input(11)) # print(GPIO.input(5)) # print(GPIO.input(6)) # print(GPIO.input(13)) # print(GPIO.input(19)) # # # print() # time.sleep(1) # except KeyboardInterrupt as k: # print("Keyboard: " + str(k)) # except Exception as e: # print("Exception: " + str(e)) # finally: # f.close()
64e9cdf5997f59cef79b7aee0ab94042fa58a6e8
cba6cd07457a3a370c2cb5f2095b1c8760a5488d
/formatting.py
9f71d30c5416fda8488c3021e1d047f704bf8bd6
[]
no_license
bq999/python
e0576e4bbd249450efbe0ebc7ec5c7728ab83391
0909f33aee755011915a3acd9e90f4e26300bf8c
refs/heads/master
2021-05-08T16:01:51.792283
2018-02-03T23:16:15
2018-02-03T23:16:15
120,138,143
0
0
null
null
null
null
UTF-8
Python
false
false
982
py
#Formatting from datetime import datetime def main(): # Times and dates can be formatted using a set of predefined string # control codes now = datetime.now() # get the current date and time #### Date Formatting #### # %y/%Y - Year, %a/%A - weekday, %b/%B - month, %d - day of month print(" ") print("Date Formatting") print (now.strftime("%Y")) # full year with century print (now.strftime("%a, %d %B, %y")) # abbreviated day, num, full month, abbreviated year # %c - locale's date and time, %x - locale's date, %X - locale's time print(" ") print("Local Time") print (now.strftime("%c")) print (now.strftime("%x")) print (now.strftime("%X")) #### Time Formatting #### # %I/%H - 12/24 Hour, %M - minute, %S - second, %p - locale's AM/PM print(" ") print("Time Formatting") print (now.strftime("%I:%M:%S %p")) # 12-Hour:Minute:Second:AM print (now.strftime("%H:%M")) # 24-Hour:Minute if __name__ == "__main__": main();
f9808f85bde238a24b959b2f9ca94f6866dc7cf4
7f00fed1279c8f3a9dfca1830f087a666d59d195
/EAD_project/financial_planner/portfolio_opt.py
3f2e9522bc01326292a46e77825a06f50068fd71
[]
no_license
hardy17g/Financial-Planner
fdca3f14604d3a6abfa78047b82cb4e2e5853e2a
0b251339f5e2ec5357df447c9ad6b31ec92a3511
refs/heads/master
2022-04-24T18:59:47.812720
2020-04-30T17:19:17
2020-04-30T17:19:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
800
py
import yfinance as yf import pandas as pd from pypfopt import EfficientFrontier from pypfopt import risk_models from pypfopt.risk_models import CovarianceShrinkage from pypfopt import expected_returns def get_result(l): data = yf.download(tickers = l, period ="max", interval = "1d",auto_adjust = True) data = data['Close'] mu = expected_returns.mean_historical_return(data) S = CovarianceShrinkage(data).ledoit_wolf() ef = EfficientFrontier(mu, S) raw_weights = ef.max_sharpe() cleaned_weights = ef.clean_weights() data = [] for x in cleaned_weights.keys(): if cleaned_weights[x]!=0: data.append({'name':x, 'y':cleaned_weights[x] }) answer = { 'data': data, 'performance': ef.portfolio_performance() } return answer
3247b9e144b72c1d8b6e61c1368ab3973f6c9b42
933266c87ce0cf45ccdf2a101fd2bf483dee7055
/python/stack.py
3fb2db57c11b117a4e5970f5a4442707df8decbe
[]
no_license
maddff/practice
62cdcc59eec5c689a3361ce4291e23f19fd3692a
365e3385653f1245f66bbcedc0b3080ca0a2dde0
refs/heads/main
2023-01-24T00:59:27.246004
2020-11-25T22:22:25
2020-11-25T22:22:25
309,238,543
0
0
null
null
null
null
UTF-8
Python
false
false
659
py
class Stack(object): def __init__(self): self.data_list = [] def insert(self, data): self.data_list.append(data) def pop(self): if len(self.data_list) == 0: return None data = self.data_list[-1] del self.data_list[-1] return data def size(self): return len(self.data_list) stack = Stack() print("before insert, stack size: " + str(stack.size())) stack.insert("a") stack.insert("b") stack.insert("c") stack.insert("d") print("after insert, stack size: " + str(stack.size())) print("pop stack data:") print(stack.pop()) print(stack.pop()) print(stack.pop()) print(stack.pop())
0ec97c5ab8392c7cb7cdb4c1effd50efecf924ef
474743374414f48e924919c524ad05534af94f9c
/nyCommuting.py
32b8878bed161a5b2cc87e61982a1fac35ad5dda
[]
no_license
Perseus1993/nyMobility
aafbebcea28cd9950b329b967717b2d692960463
54b85a8638c5554ccad0c3c5c51e7695f1430ac7
refs/heads/master
2023-03-15T12:08:28.777956
2018-10-12T16:37:29
2018-10-12T16:37:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,756
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 5 17:25:14 2018 @author: doorleyr """ import pandas as pd import json from shapely.geometry import Point, shape def get_location(longitude, latitude, regions_json, name): # for a given lat and lon, and a given geojson, find the name of the feature into which the latLon falls point = Point(longitude, latitude) for record in regions_json['features']: polygon = shape(record['geometry']) if polygon.contains(point): return record['properties'][name] return 'None' #get communties geojson communities=json.load(open('./spatialData/communityDistrictsManhattanOnly.geojson')) ntas=json.load(open('./spatialData/Neighborhood Tabulation Areas.geojson')) nycCounties=json.load(open('./spatialData/nycCounties.geojson')) nj=json.load(open('./spatialData/newJersey.geojson')) #get OD data commuting=pd.read_csv('./od_data/tract2TractCommuting_NY.csv', skiprows=2) #commuting['RESIDENCE']=commuting.apply(lambda row: str(row['RESIDENCE']).split(',')[0], axis=1) #commuting['WORKPLACE']=commuting.apply(lambda row: str(row['WORKPLACE']).split(',')[0], axis=1) commuting=commuting[~commuting['Workers 16 and Over'].isnull()] commuting['Workers 16 and Over']=commuting.apply(lambda row: float(str(row['Workers 16 and Over']).replace(',',"")), axis=1)# in case there are commas for separating 000s #get tracts geojson tracts=json.load(open('./spatialData/2010 Census Tracts.geojson')) tractsManhattan=tracts.copy() #tractsManhattan['features']=[f for f in tracts['features'] if f['properties']['COUNTY']=='061'] tractsManhattan['features']=[f for f in tracts['features'] if f['properties']['boro_name']=='Manhattan'] #get the full list of origins and destination names allTracts=set(commuting['RESIDENCE']).union(set(commuting['WORKPLACE'])) #tractNamesGeo=[tractsManhattan['features'][i]['properties']['NAME'] for i in range(len(tractsManhattan['features']))] tractNamesGeo=[tractsManhattan['features'][i]['properties']['ctlabel'] for i in range(len(tractsManhattan['features']))] #create empty dict of name to custom zones #check if name contains New Jersey: map to NJ #if not, check if not in New York County: map to the boro name # if in NY county, look up the tract in the geojson and map to the ntaname # OR get the tract centroid and find which community district its in tracts2Comms={} tracts2Nhoods={} for t in allTracts: if 'New Jersey' in t: tracts2Comms[t]='New Jersey' tracts2Nhoods[t]='New Jersey' elif 'New York County' not in t: tracts2Comms[t]=t.split(', ')[1] tracts2Nhoods[t]=t.split(', ')[1] else: # tracts2Comms[t]=getLocation() tractNum=t.split(',')[0].split(' ')[2] tractInd=tractNamesGeo.index(tractNum) # tracts2Nhoods[t]=tractsManhattan['features'][tractInd]['properties']['ntaname'] tractCentroid=shape(tractsManhattan['features'][tractInd]['geometry']).centroid comm=get_location(tractCentroid.x, tractCentroid.y, communities, 'Name') nHood=get_location(tractCentroid.x, tractCentroid.y, ntas, 'ntaname') if comm=='None': print(t) if tractNum =='309': comm='Bronx County' #exception: this census tract is actually in New York County but not considered part of any of the Manhattan community districts if nHood=='None': print('nHood') print(t) tracts2Comms[t]=comm tracts2Nhoods[t]=nHood commuting['oComm']=commuting.apply(lambda row: tracts2Comms[row['RESIDENCE']], axis=1) commuting['dComm']=commuting.apply(lambda row: tracts2Comms[row['WORKPLACE']], axis=1) commuting['oNhood']=commuting.apply(lambda row: tracts2Nhoods[row['RESIDENCE']], axis=1) commuting['dNhood']=commuting.apply(lambda row: tracts2Nhoods[row['WORKPLACE']], axis=1) #commuting['simpleMode']=commuting.apply(lambda row: cpttModeDict[row['Means of Transportation 18']], axis=1) odComms=pd.crosstab(commuting['oComm'], commuting['dComm'], commuting['Workers 16 and Over'], aggfunc="sum").fillna(0) odNHoods=pd.crosstab(commuting['oNhood'], commuting['dNhood'], commuting['Workers 16 and Over'], aggfunc="sum").fillna(0) odComms.to_csv('./results/od_communityDistricts.csv') odNHoods.to_csv('./results/od_neighbourhoods.csv') odCommsMode=commuting.groupby(by=['oComm', 'dComm', 'Means of Transportation 18'], as_index=False).sum() odNHoodsMode=commuting.groupby(by=['oNhood', 'dNhood', 'Means of Transportation 18'], as_index=False).sum() #create a geojson including all the zones for the community district aggregation geoOutComms=nycCounties.copy() geoOutComms['features']=[] for g in nycCounties['features']: if g['properties']['NAME']+' County' in odComms.columns.values: geoOutComms['features'].append({'properties':{'Name': g['properties']['NAME']+' County', 'type':'County'}, 'geometry': g['geometry'], 'type':'Feature'}) for c in communities['features']: if c['properties']['Name'] in odComms.columns.values: geoOutComms['features'].append({'properties':{'Name': c['properties']['Name'], 'type':'Community'}, 'geometry': c['geometry'], 'type':'Feature'}) geoOutComms['features'].append({'properties':{'Name': 'New Jersey', 'type':'State'}, 'geometry': nj['features'][0]['geometry'], 'type':'Feature'}) #create a geojson including all the zones for the nta aggregation geoOutNHoods=nycCounties.copy() geoOutNHoods['features']=[] for g in nycCounties['features']: if g['properties']['NAME']+' County' in odNHoods.columns.values: geoOutNHoods['features'].append({'properties':{'Name': g['properties']['NAME']+' County', 'type':'County'}, 'geometry': g['geometry'], 'type':'Feature'}) for c in ntas['features']: if c['properties']['ntaname'] in odNHoods.columns.values: geoOutNHoods['features'].append({'properties':{'Name': c['properties']['ntaname'], 'type':'Neighbourhood'}, 'geometry': c['geometry'], 'type':'Feature'}) geoOutNHoods['features'].append({'properties':{'Name': 'New Jersey', 'type':'State'}, 'geometry': nj['features'][0]['geometry'], 'type':'Feature'}) #geoOutNHoods=nycCounties.copy() #geoOutNHoods['features']=[g for g in nycCounties['features'] if g['properties']['NAME']+' County' in odNHoods.columns.values] #for c in ntas['features']: # if c['properties']['ntaname'] in odNHoods.columns.values: # geoOutNHoods['features'].extend([c]) #geoOutNHoods['features'].extend([nj['features'][0]]) json.dump(geoOutComms, open('./results/allZonesComms.geojson', 'w')) json.dump(geoOutNHoods, open('./results/allZonesNHoods.geojson', 'w')) odCommsMode.to_csv('./results/od_communityDistricts_byMode.csv') odNHoodsMode.to_csv('./results/od_neighbourhoods_byMode.csv')
eb94a51b93a704547751ca94122f14ec027c77af
d91aa657b70768fd242796b2470b5e222c00a6c3
/WriteOn.py
b371a8d81a8660168bd0c590ce25134a23c163fa
[]
no_license
dreshfield/WriteOn
166b7d71ca538af8a753876b62f1bb8c22963b34
039b835b57bc614362341e1cd6c2c46015825309
refs/heads/master
2020-12-30T17:19:31.661035
2013-05-29T03:14:46
2013-05-29T03:14:46
2,522,300
0
0
null
null
null
null
UTF-8
Python
false
false
711
py
import curses, locale, sys, traceback # Gets system's default encoding for non-ASCII chars; "code" is then used for str.encode() calls locale.setlocale(locale.LC_ALL, '') code = locale.getpreferredencoding() """ This is a documentation comment. """ # -- Key Bindings -- # # Enter = switch between command/edit mode # CTRL-D = quit # # - Command Mode - # # l = new line # p = paragraph break # q = quote # s = save (prompt for directory and file to output if no file argv given at runtime) # T = title (center, bold, increase font-size) # t = subtitle # # - Editing Mode - # # Tab = Indent four spaces # # curses.textpad() # User enters command mode; make this toggleable at a later point? # User # if
856794859aa4e34f0efcddebb80b7314f97f9f4c
2c6e600de029d38478e3c4e4d4500d9a42b6dd98
/End to End Multipli Disease Prediction/models/diabetes.py
5b002b10b6b71b2d573735048b385db4a7fcbd6e
[]
no_license
githubybf/All-End-to-End-Projects
ae76434f49808a5076a5ec788f650c850b908cec
40d0d5f1016c3c7b7e6457d697e6dc727f8c388c
refs/heads/main
2023-03-07T09:07:19.289830
2021-02-07T08:06:08
2021-02-07T08:06:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
334
py
import numpy as np import pandas as pd from sklearn.linear_model import LogisticRegression import joblib data=pd.read_csv("diabetes.csv") print(data.head()) logreg=LogisticRegression() X=data.iloc[:,:8] print(X.shape[1]) y=data[["Outcome"]] X=np.array(X) y=np.array(y) logreg.fit(X,y.reshape(-1,)) joblib.dump(logreg,"model1")
f0714282ca1bed1a0bc706dfd5e96c9a2e87dc47
a94770c70704c22590c72d7a90f38e3a7d2e3e5c
/Algo/Leetcode/123BestTimeToBuyAndSellStockIII.py
2a292d28fef14431391bc62620bd69b4e46bf158
[]
no_license
lawy623/Algorithm_Interview_Prep
00d8a1c0ac1f47e149e95f8655d52be1efa67743
ca8b2662330776d14962532ed8994dfeedadef70
refs/heads/master
2023-03-22T16:19:12.382081
2023-03-21T02:42:05
2023-03-21T02:42:05
180,056,076
2
0
null
null
null
null
UTF-8
Python
false
false
409
py
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ buy1 = -2**31 buy2 = -2**31 sell1 = 0 sell2 = 0 for p in prices: buy1 = max(buy1, -p) sell1 = max(sell1, buy1+p) buy2 = max(buy2, sell1-p) sell2 = max(sell2, buy2+p) return sell2
4dceb544e9e5cb1d823f903dc4ef905e43deca34
264ff719d21f2f57451f322e9296b2f55b473eb2
/gvsoc/gvsoc/models/pulp/fll/fll_v1.py
4bba0a37a2e965a05864f2ac8ec5e53627d4f934
[ "Apache-2.0" ]
permissive
knmcguire/gap_sdk
06c9537c16fa45dea6b7f5c6b162b53953262915
7b0a09a353ab6f0550793d40bd46e98051f4a3d7
refs/heads/master
2020-12-20T06:51:19.580497
2020-01-21T14:52:28
2020-01-21T14:52:28
235,992,961
0
0
Apache-2.0
2020-01-24T11:45:59
2020-01-24T11:45:58
null
UTF-8
Python
false
false
772
py
# # Copyright (C) 2018 ETH Zurich and University of Bologna # # 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. # # Authors: Germain Haugou, ETH ([email protected]) import vp_core as vp class component(vp.component): implementation = 'pulp.fll.fll_v1_impl'
5bdcfc70c667b06dfdae9f296ca3cab66c8be15a
1f1c5ffab001852677030e1fd745d6ac426554ad
/C07_enum.py
c8ecc91ac600ea10173f3b256ce6fcdd2eb05b33
[ "MIT" ]
permissive
k501903/pythonstudy
be4c0b714d2d0b661efbfa50c4c12cb1bb84ebd6
f4eff76819cec2c479ec19a4940141406079cb9a
refs/heads/master
2021-09-06T20:55:49.222865
2018-02-11T07:54:57
2018-02-11T07:54:57
111,904,266
0
0
null
null
null
null
UTF-8
Python
false
false
634
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- '枚举类的练习' __author__ = 'Jacklee' # 导入模块 #import types # 月份常量 JAN = 1 FEB = 2 MAR = 3 # 枚举类 from enum import Enum, unique ## 第一种定义方式 @unique class Month(Enum): JAN = 0 FEB = 1 MAR = 2 ## 第二种定义方式 WeekDay = Enum('WeekDay', ('Mon', 'Tue', 'Wed', 'Tru', 'Fri', 'Sat', 'Sun')) ## 类的组成,JAN ... 是一个类成员 print('Month类的成员: ', dir(Month)) m = Month(0) print(m.name, m.value) print('Month对象实例的成员: ', dir(m)) m = Month(1) print(m.name, m.value) m = Month(2) print(m.name, m.value)
8d68dee440c678f91456f3f192d90e117ad537bf
3010e34c624c55b55b4264c33ac28f639c241233
/metareader/metadata_format.py
729e3b70324f612360358a74ad521074eecfddf6
[ "MIT" ]
permissive
valossalabs/metadata-reader
dfd29cc4654e6334f70260a0215987ca260f9262
3e7a6c06f12f27714ec89413d0d0acf13f0e07a3
refs/heads/master
2021-07-18T07:43:55.219251
2021-02-12T18:21:39
2021-02-12T18:21:39
94,876,117
2
0
null
null
null
null
UTF-8
Python
false
false
8,771
py
# -*- coding: utf-8 -*- """metadata_format.py""" # The newer version has all fields in earlier versions # TODO: Update to current version metadata_versions = { "1.3.2": { "detections": { "ID": { "a": { "similar_to": [{ # Is this correct: "role": "..." }] } } } }, "1.3.1": { "version_info": { "metadata_type": "[core,???]" } }, "1.3.0": { "version_info": { "metadata_format": "1.3.0", "backend": "", }, "job_info": { "job_id": "", "request": { "media": { "video": { "url": "" }, "transcript": { "url": "" }, "description": "[null,???]", "language": "[en_US,???]", "title": "" } } }, "media_info": { "technical": { "duration_s": 1234.56789, # Video length "fps": 24 }, "from_customer": { "title": "" } }, "transcript": {}, "detections": { "[1,2,...]": { "a": { # If "t" == "human.face" "gender": { "c": 0.123, # Confidence "value": "male/female" }, "s_visible": 1.23, "similar_to": [ # Optional { "c": 0.123, # Confidence, 0.5-1.0 "name": "..." } ] }, "cid": "Valossa Concept ID", # Optional "ext_refs": { # Optional "gkg": { # Google Knowledge Graph identifier "id": "/m/xxxxx" } }, "label": "...", "occs": [ { "c_max": 0.123, # Maximum confidence of occurrence, not in human.face "id": "[1,2,3,...]", # Occurrence identifier "ss": 12.34, # Second, start "se": 23.45 # Second, end }, {}, ], "t": "..." # Detection type }, }, "detection_groupings": { "by_detection_type": { # Only types that has contents are included. "human.face_group": [], # Each type has detections sorted by prominence. "visual.context": [], "audio.context": [], "...": [] }, "by_second": [ # List containing all seconds in order [ # Contains all occurrences in one second { "c": 0.123, # optional? "d": "dID", "o": [] } ], [] ] }, "segmentations": {} } } def get_all_detections(metadata, det_type=None, n_most_prominent=float("inf")): """List all detections unless type or count is limited""" if not det_type: for detection_type in metadata["detection_groupings"]["by_detection_type"]: for detection_id, detection in get_all_detections( metadata, det_type=detection_type, n_most_prominent=n_most_prominent ): yield detection_id, detection else: count = 0 for detection_id in metadata["detection_groupings"]["by_detection_type"][det_type]: if count > n_most_prominent: break yield detection_id, metadata["detections"][detection_id] count += 1 def get_all_occs_by_second_data(metadata, start=0, stop=None, det_type=None): """yields every second of metadata unless limited""" if stop is None: # Make sure that stop is bigger than index stop = float('inf') index = start for second in metadata["detection_groupings"]["by_second"][start:]: if index > stop: break for secdata in second: if det_type and metadata["detections"][secdata["d"]]["t"] not in det_type: continue yield secdata def get_subtitle_data(metadata, start=0, stop=None, det_type=None): """Yields data needed for subtitle generation Format: [start, stop, label/name] """ for secdata in get_all_occs_by_second_data(metadata, start, stop, det_type): detection = metadata[u"detections"][secdata[u"d"]] # Get start and stop times for detection: for occ in detection[u"occs"]: # Find the occ if occ[u"id"] == secdata[u"o"][0]: start = occ[u"ss"] stop = occ[u"se"] # Generate label: if "a" in detection: # human.face (most likely?) if "similar_to" in detection["a"]: label = detection["a"]["similar_to"][0]["name"] elif "gender" in detection["a"]: label = "unknown {}".format(detection["a"]["gender"]["value"]) else: label = "unknown person" elif "label" in detection: label = detection["label"] else: raise RuntimeError("No 'a' or 'label' in detection") yield [start, stop, label] def get_all_by_second_data(metadata, start=0, stop=None): """yields every second of metadata unless limited""" if stop is None: # Make sure that stop is bigger than index stop = float('inf') index = start for second in metadata["detection_groupings"]["by_second"][start:]: if index > stop: break yield second index += 1 def get_labels_by_second(metadata, start=0, stop=None, det_type=None, confidence=None): """Output just second with labels Format: [second, label,label,...] """ if stop is None: stop = float('inf') index = start for second in metadata["detection_groupings"]["by_second"][start:]: if index > stop: break labels = [index] for occ in second: if det_type and metadata["detections"][occ["d"]]["t"] not in det_type: continue if confidence and occ["c"] < confidence: continue label = metadata["detections"][occ["d"]]["label"] labels.append(label) yield labels index += 1 class LengthSum(object): """Class to allow changing addition type. Union type addition simply extends time range when adding Normal type addition just adds end-start each time """ def __init__(self, sum_type="normal"): self.compress_flag = False if sum_type == "union": self.add = self.add_union self.sum_type = "union" self.intervals = [] elif sum_type == "normal": self.add = self.add_normal self.sum_type = "normal" self.sum = 0.0 else: raise TypeError("sum_type must be either union or normal") def __str__(self): return str(self.__float__()) def __repr__(self): return repr(self.__float__()) def __float__(self): if self.compress_flag: self.intervals = self.compress(self.intervals) if self.sum_type == "union": r_sum = 0.0 for interval in self.intervals: r_sum += interval[1] - interval[0] return r_sum return self.sum def __div__(self, other): return self.__float__() / other def add_union(self, ss, se): self.intervals.append((ss, se)) self.compress_flag = True def add_normal(self, ss, se): self.sum += se - ss @staticmethod def compress(source_list): source_list.sort(key=lambda lis: lis[0]) return_list = [source_list[0]] for cell in source_list[1:]: if cell[0] > return_list[-1][1]: return_list.append(cell) elif return_list[-1][1] <= cell[1]: return_list[-1] = (return_list[-1][0], cell[1]) return return_list