blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
133
path
stringlengths
2
333
src_encoding
stringclasses
30 values
length_bytes
int64
18
5.47M
score
float64
2.52
5.81
int_score
int64
3
5
detected_licenses
listlengths
0
67
license_type
stringclasses
2 values
text
stringlengths
12
5.47M
download_success
bool
1 class
ba41479e5b95d63fd5f72590ed9929bcf26ac00c
Python
981377660LMT/algorithm-study
/22_专题/前缀与差分/差分数组/离散化/6044. 花期内花的数目-单点查询-差分+离散化.py
UTF-8
1,793
3.53125
4
[]
no_license
# 10^9值域 差分数组 # 6044. 花期内花的数目-单点查询-差分+离散化 from typing import List from bisect import bisect_right from collections import defaultdict from itertools import accumulate from 紧离散化模板 import Discretizer class Solution: def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]: """单点查询时:只对flowers离散化,开字典+二分查找query值被映射成啥""" diff = defaultdict(int) for left, right in flowers: diff[left] += 1 diff[right + 1] -= 1 # 离散化的keys、原数组前缀和 keys = sorted(diff) diff = list(accumulate((diff[key] for key in keys), initial=0)) return [diff[bisect_right(keys, p)] for p in persons] def fullBloomFlowers2(self, flowers: List[List[int]], persons: List[int]) -> List[int]: """单点查询时:如果同时也把person添加到离散化,就不用二分查找了/不用开字典了""" D = Discretizer() for left, right in flowers: D.add(left) D.add(right) for p in persons: D.add(p) D.build() diff = [0] * (len(D) + 10) for left, right in flowers: diff[D.get(left)] += 1 diff[D.get(right) + 1] -= 1 diff = list(accumulate(diff)) return [diff[D.get(p)] for p in persons] if __name__ == "__main__": print( Solution().fullBloomFlowers( flowers=[[1, 6], [3, 7], [9, 12], [4, 13]], persons=[2, 3, 7, 11] ) ) print( Solution().fullBloomFlowers2( flowers=[[1, 6], [3, 7], [9, 12], [4, 13]], persons=[2, 3, 7, 11] ) )
true
aca02c812f13e074069ae080d845cca0673b65c7
Python
CdtDelta/YOP
/yop-week17.py
UTF-8
1,774
2.734375
3
[]
no_license
# This script parses out the hash table in an index.dat file # It's still a work in progress I have some pieces to finish coding out # # # # Licensed under the GPL # http://www.gnu.org/copyleft/gpl.html # # By Tom Yarrish # Version 0.5 # # Usage yop-week17.py <index.dat> import sys import struct def hash_header(parse_header): ie_hash_header = parse_header[0:4] ie_hash_length = struct.unpack("<I", parse_header[4:8]) ie_hash_next_table = struct.unpack("<I", parse_header[8:12]) ie_hash_table_no = struct.unpack("<I", parse_header[12:16]) print "{}\nHash Table Length: {}\nNext Hash Table Offset: {}\nHash Table No: {}\n".format(ie_hash_header, (ie_hash_length[0] * 128), ie_hash_next_table[0], ie_hash_table_no[0]) return ie_hash_header, (ie_hash_length[0] * 128), ie_hash_next_table[0], ie_hash_table_no[0] def hash_table_records(parse_records): ie_hash_data = struct.unpack("<I", parse_records[0:4]) ie_hash_record_pointer = struct.unpack("<I", parse_records[4:8]) print "Hash Data: {}\t\tHash Record Pointer: {}".format(hex(ie_hash_data[0]), ie_hash_record_pointer[0]) return index_dat = sys.argv[1] with open(index_dat, "rb") as ie_file: ie_hash_parser = ie_file.read() ie_hash_head = ie_hash_parser[20480:20496] ie_hash_header = hash_header(ie_hash_head) ie_hash_record_start = 20496 ie_hash_record_end = 20504 ie_hash_record = ie_hash_parser[ie_hash_record_start:ie_hash_record_end] while ie_hash_record_start < (ie_hash_record_start + (int(ie_hash_header[1]) - 12)): ie_hash_record_table = hash_table_records(ie_hash_record) ie_hash_record_start = ie_hash_record_end ie_hash_record_end += 8 ie_hash_record = ie_hash_parser[ie_hash_record_start:ie_hash_record_end]
true
3ea58467ab0b0eb7a7f5b69af724c87b4f5f5308
Python
iceycc/daydayup
/python/Geek-00/代码/lesson11/1nlp/p4_wordvector2.py
UTF-8
1,459
3.203125
3
[]
no_license
import torch import torchtext from torchtext import vocab # 预先训练好的此向量 gv = torchtext.vocab.GloVe(name='6B', dim=50) # 40万个词,50个维度 len(gv.vectors), gv.vectors.shape # 获得单词的在Glove词向量中的索引(坐标) gv.stoi['tokyo'] # 查看tokyo的词向量 gv.vectors[1363] # 可以把坐标映射回单词 gv.itos[1363] # 把tokyo转换成词向量 def get_wv(word): return gv.vectors[gv.stoi[word]] get_wv('tokyo') # 找到距离最近的10个单词 def sim_10(word, n=10): all_dists = [(gv.itos[i], torch.dist(word, w)) for i, w in enumerate(gv.vectors)] return sorted(all_dists, key=lambda t: t[1])[:n] sim_10(get_wv('tokyo')) # [('tokyo', tensor(0.)), ('osaka', tensor(3.2893)), ('seoul', tensor(3.3802)), ('shanghai', tensor(3.6196)), ('japan', tensor(3.6599)), ('japanese', tensor(4.0788)), ('singapore', tensor(4.1160)), ('beijing', tensor(4.2423)), ('taipei', tensor(4.2454)), ('bangkok', tensor(4.2459))] def analogy(w1, w2, w3, n=5, filter_given=True): print(f'[ {w1} : {w2} :: {w3} : ? ]') # w2 - w1 + w3 = w4 closest_words = sim_10(get_wv(w2) - get_wv(w1) + get_wv(w3)) # 过滤防止输入参数出现在结果中 if filter_given: closest_words = [t for t in closest_words if t[0] not in [w1, w2, w3]] print(closest_words[:2]) analogy('beijing', 'china', 'tokyo') # [ beijing : china :: tokyo : ? ] # [('japan', tensor(2.7869)), ('japanese', tensor(3.6377))]
true
53bdbedefb710b2a822fc5ee18be75b4a0b9ff5f
Python
jfernand196/Ejercicios-Python
/funcion_num_cercanos.py
UTF-8
200
3.625
4
[]
no_license
# crear una funcion para determinar si un numero es cercano a 1000 o 2000 def cercania(): #return ((abs(1000 - n) < 100) and (abs(2000 - n) < 100)) return (False and False) print(cercania())
true
33fec514c0da839b563e2dc0beded2af477542de
Python
evwhiz/fish_oil
/ifos_oil.py
UTF-8
3,912
2.734375
3
[]
no_license
from datetime import date from lxml import html import os import pathlib import requests import time import urllib IFOS_SRC_URL = "http://consumer.nutrasource.ca/ifos/product-reports/" def get_etree(url): """ Returns report page's html.Element """ page = requests.get(url) etree = html.fromstring(page.content) return etree def get_report_urls(etree): "Returns list of report link strings" raw_reports = etree.xpath('//a[contains(@href,"/files/")]/@href') prefix = "http://consumer.nutrasource.ca" report_links = [prefix + urllib.parse.quote(url, safe="/") for url in raw_reports] return report_links def get_report_filename(url): today_stamp = str(date.today()) # example: "2018-11-22" filename = today_stamp + "-" + urllib.parse.unquote(url.split("/files/")[-1]) filename = filename.replace(" ", "").replace(",", "") return filename def validate_file(filename, epoch_age=60 * 60 * 24 * 30): "Returns True if file exists and is younger than epoch_age" if os.path.isfile(filename): now = time.time() created = os.stat(filename).st_mtime file_age = now - created print("file_age:{} <= epoch_age:{}".format(file_age, epoch_age)) return file_age <= epoch_age else: return False def archive_report(report_url, epoch_age=0, archive_dir="./tmp/"): """ Validates existense of file of at least the epoch_age, else collects and writes a new report file to the archive_dir """ filename = archive_dir + get_report_filename(report_url) if not validate_file(filename, epoch_age=epoch_age): if not os.path.exists(archive_dir): pathlib.Path(archive_dir).mkdir(parents=True, exist_ok=True) response = requests.get(report_url) print("Writing file to {}".format(filename)) with open(filename, "wb") as f: f.write(response.content) def expell_ifos_oil(archive_dir, epoch_age=60 * 60 * 24 * 30, pause=5, number=0): "Gets new files if files older than epoch_age. Default epoch_age is 30 days" etree = get_etree(IFOS_SRC_URL) report_urls = get_report_urls(etree) # if not number == 0: # number = min(number, len(report_urls)) # report_urls = report_urls[:number] for report_url in report_urls[:min(number, len(report_urls))]: archive_report(report_url, epoch_age=epoch_age, archive_dir=archive_dir) time.sleep(pause) ########### # PYTESTS # ########### TEST_SRC_URL = IFOS_SRC_URL TEST_REPORT_URL = r"http://consumer.nutrasource.ca/files/IFOS%20See%20Yourself%20Well%20Omega%203%201500%20Lemon.pdf" TEST_ARCHIVE_DIR = "./tmp/" def test_get_etree(): global TEST_ETREE TEST_ETREE = get_etree(url=TEST_SRC_URL) title = TEST_ETREE.xpath("//html/head/title")[0].text assert type(TEST_ETREE) == html.HtmlElement assert "Product Reports" in title def test_get_report_urls(): global TEST_REPORT_URLS TEST_REPORT_URLS = get_report_urls(TEST_ETREE) assert len(TEST_REPORT_URLS) > 0 assert ".pdf" in TEST_REPORT_URLS[0] for test_report_url in TEST_REPORT_URLS: assert "http://consumer.nutrasource.ca/files/" in test_report_url assert test_report_url[-4:] == ".pdf" assert " " not in test_report_url def test_get_report_filename(): print("TEST_REPORT_URLS[0]", TEST_REPORT_URLS[0]) global TEST_FILENAME TEST_FILENAME = get_report_filename(TEST_REPORT_URLS[0]) assert TEST_FILENAME == str(date.today()) + "-" + "IFOSSeeYourselfWellOmega31500Lemon.pdf" def test_archive_report(): archive_report(TEST_REPORT_URLS[0], epoch_age=0, archive_dir=TEST_ARCHIVE_DIR) assert os.path.isfile(TEST_ARCHIVE_DIR + TEST_FILENAME) def test_validate_file(): assert validate_file(TEST_ARCHIVE_DIR + TEST_FILENAME) assert not validate_file(TEST_ARCHIVE_DIR + TEST_FILENAME, epoch_age=-1)
true
bf25cc8f9b5c5e78e63affefdf356b4f7fafc56c
Python
BlueBrain/NeuroM
/examples/end_to_end_distance.py
UTF-8
4,392
2.734375
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#!/usr/bin/env python # Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project # All rights reserved. # # This file is part of NeuroM <https://github.com/BlueBrain/NeuroM> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. 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. # 3. Neither the name of the copyright holder 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 HOLDER 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. """Calculate and plot end-to-end distance of neurites.""" import neurom as nm from neurom import morphmath import numpy as np import matplotlib.pyplot as plt def path_end_to_end_distance(neurite): """Calculate and return end-to-end-distance of a given neurite.""" trunk = neurite.root_node.points[0] return max(morphmath.point_dist(l.points[-1], trunk) for l in neurite.root_node.ileaf()) def mean_end_to_end_dist(neurites): """Calculate mean end to end distance for set of neurites.""" return np.mean([path_end_to_end_distance(n) for n in neurites]) def make_end_to_end_distance_plot(nb_segments, end_to_end_distance, neurite_type): """Plot end-to-end distance vs number of segments.""" plt.figure() plt.plot(nb_segments, end_to_end_distance) plt.title(neurite_type) plt.xlabel('Number of segments') plt.ylabel('End-to-end distance') plt.show() def calculate_and_plot_end_to_end_distance(neurite): """Calculate and plot the end-to-end distance vs the number of segments for an increasingly larger part of a given neurite. Note that the plots are not very meaningful for bifurcating trees.""" def _dist(seg): """Distance between segmenr end and trunk.""" return morphmath.point_dist(seg[1], neurite.root_node.points[0]) end_to_end_distance = [_dist(s) for s in nm.iter_segments(neurite)] make_end_to_end_distance_plot(np.arange(len(end_to_end_distance)) + 1, end_to_end_distance, neurite.type) if __name__ == '__main__': # load a neuron from an SWC file filename = 'tests/data/swc/Neuron_3_random_walker_branches.swc' m = nm.load_morphology(filename) # print mean end-to-end distance per neurite type print('Mean end-to-end distance for axons: ', mean_end_to_end_dist(n for n in m.neurites if n.type == nm.AXON)) print('Mean end-to-end distance for basal dendrites: ', mean_end_to_end_dist(n for n in m.neurites if n.type == nm.BASAL_DENDRITE)) print('Mean end-to-end distance for apical dendrites: ', mean_end_to_end_dist(n for n in m.neurites if n.type == nm.APICAL_DENDRITE)) print('End-to-end distance per neurite (nb segments, end-to-end distance, neurite type):') for nrte in m.neurites: # plot end-to-end distance for increasingly larger parts of neurite calculate_and_plot_end_to_end_distance(nrte) # print (number of segments, end-to-end distance, neurite type) print(sum(len(s.points) - 1 for s in nrte.root_node.ipreorder()), path_end_to_end_distance(nrte), nrte.type)
true
39786d507085ea44bc3c3c4422c4cbc489209f50
Python
UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018
/students/AndyKwok/lesson06/calculator/calculator/adder.py
UTF-8
388
2.90625
3
[]
no_license
""" This module provides a addition operator """ class Adder: """ Class for adding """ @staticmethod def calc(operand_1, operand_2): """ Performs addition """ return operand_1 + operand_2 @staticmethod def dummy_calc(operand_1, operand_2): """ Dummy addition """ return operand_1 + operand_2
true
c6a272bb6c789cfc1e7ccfb6bb3cb4733f4d94ce
Python
sartim/django_shop_api
/order/status/models.py
UTF-8
467
2.515625
3
[]
no_license
from django.db import models from core.models import AbstractDateModel class OrderStatus(AbstractDateModel, models.Model): __tablename__ = 'order_statuses' name = models.CharField(max_length=255, unique=True) class Meta: ordering = ('-created',) db_table = 'order_status' def __str__(self): return 'Order {}'.format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all())
true
d1be59cea0208843cca83d8589a864d2a6aab246
Python
DomoXian/domo-python
/leetcode/__twoSum__.py
UTF-8
484
3.765625
4
[]
no_license
""" 两数之和 地址:https://leetcode-cn.com/problems/two-sum/ 实现思路 左右指针 """ # !/usr/bin/python class TwoSum: def twosum(self, nums, target): hashMap = {} for index, num in enumerate(nums): flag = hashMap.get(target-num) if flag is not None: return [index, flag] else: hashMap[num] = index t = TwoSum() list = {1, 2, 3, 34, 5, 5} result = t.twosum(list, 37) print(result)
true
7cdabba327d7499e06dc22a2521cf3c64641da5d
Python
ryosuke071111/algorithms
/AtCoder/ABC/111_c_2.py
UTF-8
574
3.171875
3
[]
no_license
#10:26- # from collections import Counter # n=int(input()) # V=list(map(int,input().split())) # v1=Counter(V[::2]).most_common() # v2=Counter(V[1::2]).most_common() # if len(v1) ==1: # v1.append([0,0]) # if len(v2) == 1: # v2.append([0,0]) # if v1[0][0]==v2[0][0]: # print(min(n-v1[0][1]-v2[1][1],n-v1[1][1]-v2[0][1])) # else: # print(n-v1[0][1]-v2[0][1]) # a,_,b=input() # print("DH"[a==b]) """ ・実装 ・処理 ・数学 ・アルゴリズム _計算量 """ from functools import reduce array=[20,1,2,3,4,5] print(reduce(lambda x,y:x+y,array)) array.index
true
b5f028e7d01e9e0e2ff1444242935f23429cba4c
Python
JohnpFitzgerald/OOP
/HelloPython.py
UTF-8
357
3.34375
3
[]
no_license
import datetime print("Hello world!") now = datetime.datetime.now() print ("Current date and time is ") print (now.strftime("%A, %d-%m-%Y : %H:%M")) firstSet = {1982,1989,1999,2002,2009,2013,2019} secondSet = {1985,1992,2001,2002,2005,2009,2015} thirdSet = {} #firstSet.difference_update(secondSet) thirdSet = firstSet.union(secondSet) print(thirdSet)
true
5ead7ecdc788a365f24afeb7764de4e31e3d8ca2
Python
Kawser-nerd/CLCDSA
/Source Codes/CodeJamData/10/11/7.py
UTF-8
1,449
2.71875
3
[]
no_license
#!/usr/bin/python3 # -*- coding: utf-8 -*- inp = open('input.txt','r') outp = open('output.txt','w') T = int(inp.readline()) for i in range(T): N,K=map(int,inp.readline().split()) S = [inp.readline().strip().replace('.','').rjust(N,'.') for x in range(N)] ls=[[0,'0'] for x in range(N)] rs=[[0,'0'] for x in range(N)] ts=[[0,'0'] for x in range(N)] fins = set() for x in S: bs=[0,'0'] lsn = [] rsn = [] for y in range(N): if bs[1]==x[y]: bs[0]+=1 else: bs[0]=1 bs[1]=x[y] if ts[y][1]==x[y]: ts[y][0]+=1 else: ts[y][0]=1 ts[y][1]=x[y] if y==0: lsn.append([1,x[y]]) elif ls[y-1][1]==x[y]: lsn.append((ls[y-1][0]+1,x[y])) else: lsn.append((1,x[y])) if y==N-1: rsn.append(([1,x[y]])) elif rs[y+1][1]==x[y]: rsn.append((rs[y+1][0]+1,x[y])) else: rsn.append((1,x[y])) if (bs[0]==K or ts[y][0]==K or lsn[-1][0]==K or rsn[-1][0]==K) and x[y]!='.': fins.add(x[y]) rs = rsn ls = lsn ans = { '' : "Neither", 'B' : "Blue", 'R' : "Red" } print ("Case #%d: %s"%(i+1,ans.get(''.join(fins),'Both')),file=outp)
true
960c62eaca96db4018d646a9fd34eee3862b21f7
Python
aseke7182/WebDevelopment
/Week10/python/informatics/operation/e.py
UTF-8
107
3.46875
3
[]
no_license
import math a = int(input()) b = int(input()) if a>b: print("1") elif a<b: print("2") else: print("0")
true
661076d1500f991e1f329e8ae9c43daa0a1aaa58
Python
bertrandlalo/offline_analysis
/offline_analysis/utils/io.py
UTF-8
1,138
2.53125
3
[]
no_license
from .analysis_config import AnalysisConfig import pandas as pd import os from warnings import warn class Loader(AnalysisConfig): def __init__(self, server_path): AnalysisConfig.__init__(self, server_path ) self._description = {} def convert_bname_to_fname(self, bname, ext= ".hdf5"): return os.path.join(self.data_path, bname + ext) def select_fnames(self, query): self.hdf_info.columns = [c.replace('-', "_") for c in self.hdf_info.columns] self._bnames = self.hdf_info.query(query).index self._iterbnames = iter(self._bnames) def load_dataset(self, bname, streams): self._bname = bname try: self._data = {s["name"]: pd.read_hdf(self.convert_bname_to_fname(bname), s["group"], columns = s["columns"]) for s in streams} except KeyError as exc: warn(f"Could not load all data from: {bname}: {exc}") self._data = {} def load_next(self, streams): try: self.load_dataset(next(self._iterbnames), streams) return True except StopIteration: return False
true
32f8bd2fc9043782da2916b7a6934e4eef504fb3
Python
zahimizrahi/FraudDetection
/DataProcessor.py
UTF-8
2,703
3.171875
3
[]
no_license
import os import pandas as pd class DataProcessor: raw_data_dir_path = 'resources/FraudedRawData/' raw_data_filename = 'User' num_of_segments = 150 num_of_users = 40 num_of_benign_segments = 50 sample_size = 100 def __init__(self): return """ load the raw data from resources of a single user sequentally (without division to segments). the result will be flat list with all the commands. """ def load_raw_data_single_user_all(self, num_user): path = os.path.join(self.raw_data_dir_path, self.raw_data_filename + str(num_user)) with open(path) as user_file: commands = [command.rstrip('\n').replace('-','').replace('.','') for command in user_file.readlines()] return ' '.join(commands) def split_raw_data_to_segments_user_all(self, num_user, num_of_segments=150): path = os.path.join(self.raw_data_dir_path, self.raw_data_filename + str(num_user)) with open(path,'rb') as user_file: lines = [r.rstrip('\n') for r in user_file.readlines()] user_segments = [] for i in range(num_of_segments): start = self.sample_size * i end = (self.sample_size * (i+1)) user_segments.append(lines[start:end]) return user_segments """ load the raw data from resources of a single segment for a single user. the result will be flat list with all the commands in this segment for the user. """ def load_raw_data_single_segment(self, num_user, num_segment): path = os.path.join(self.raw_data_dir_path, self.raw_data_filename + str(num_user)) with open(path) as user_file: commands = [command.rstrip('\n').replace('-','').replace('.','') for command in user_file.readlines()] start = self.sample_size * (num_segment) end = self.sample_size * (num_segment + 1) return ' '.join(commands[start:end]) """ load the raw data from resources of a single user divisioned to segments. the result will be list when element i will be the commands of the user in segment i. """ def load_raw_data_single_user_segments(self, num_user, num_of_segments=50): raw_data_list = [self.load_raw_data_single_segment(num_user, segment) for segment in range(0, num_of_segments)] return raw_data_list def get_all_commands_series(self): commands = {} for user in os.listdir(self.raw_data_dir_path): if user.startswith('User'): user_num = int(user.split('User')[1]) commands[user_num] = self.split_raw_data_to_segments_user_all(user_num, num_of_segments=150) return commands
true
4326211498dead986201cc8a1b9cebcd934bfaf1
Python
mihcaelcaplan/silkysnails
/simulation/plant.py
UTF-8
1,084
3.03125
3
[]
no_license
from mesa import Agent import re import numpy as np import io class Plant(Agent): # this will be the main lil organism def __init__(self, pos, model, text_start, source_name, length): super().__init__(pos, model) # print(pos) self.x, self.y = pos self.text_start = text_start self.source_name = source_name self.source = self.get_text_source(length) if not self.source: print("Warning! Plant instantiated with no text. Source %s seems to be too short for the number of agents."%source_name) #will get called in the __init__ to assign text to plant def get_text_source(self, length): # open a .txt file and pick some substring of complete words with io.open("corpus/%s"%self.source_name, 'r', encoding='windows-1252') as f: list = re.split('\W+', f.read()) #randomly subselect some section of the list x = np.random.randint(0, len(list)) source = list[self.text_start:self.text_start+length] # print(source) return source
true
411ccd5d9c77ac7303080fbb75cb656211118b43
Python
bright-night-sky/algorithm_study
/CodeUp/Python 기초 100제/6081번 ; 16진수 구구단 출력하기.py
UTF-8
783
3.65625
4
[]
no_license
# https://codeup.kr/problem.php?id=6081 # readline을 사용하기 위해 import합니다. from sys import stdin # 16진수로 한 자리 수를 입력합니다. # A ~ F 중 하나입니다. # 입력한 16진수 숫자를 10진수 숫자로 변환합니다. hex_num = int(stdin.readline(), 16) # 16진수 구구단을 출력하기 1부터 15까지 반복합니다. for num in range(1, 16): # 현재 반복 중인 수에 맞는 16진수 곱셈 결과를 저장하는 변수를 선언합니다. # 대문자가 있는 16진수로 표현해줍니다. result = '%X' % (hex_num * num) # 출력 형식에 맞게 16진수 구구단 각각의 식을 출력합니다. # 영어 부분은 대문자로 출력합니다. print(f'{"%X" % hex_num}*{"%X" % num}={result}')
true
675480f3a3b871c7913c7846218d6d131d966b16
Python
onionhoney/codesprint
/judge/sessions/2018Individual/ma3cheng2@gmail.com/PC_01.py
UTF-8
807
2.953125
3
[]
no_license
import sys total = int(sys.stdin.readline()) def get_root(uf, i): while i != uf[i]: i = uf[i] return i def union(uf, size, i, j): root_i = get_root(uf, i) root_j = get_root(uf, j) uf[root_i] = root_j size[root_j] = size[root_i] + size[root_j] size[root_i] = 0 for num in range(total): p = sys.stdin.readline() aaa = list(map(int, p.split())) n = aaa[0] uf = list(range(n)) size = [1] * n for i in range(aaa[1]): p = sys.stdin.readline() bbb = list(map(int, p.split())) union(uf, size, bbb[0] - 1, bbb[1] - 1) size = sorted(size) size.reverse() summm = 0 tmp = 0 for i in range(len(size)): if i < aaa[2]: tmp += size[i] elif i == aaa[2]: tmp += size[i] summm = tmp * (tmp - 1) / 2 else: if size[i] > 0: summm += size[i] - 1 print summm
true
a4ce2f560d69ad61172ef3ccbe32404855d76925
Python
eMUQI/Python-study
/old/cases/book_case02_列表.py
UTF-8
1,084
3.96875
4
[]
no_license
bicycles = ['terk','cannondale','redine','specialized'] #与C语言类似 print(bicycles) print(bicycles[0].title()) print("bicycles[-1]:") print(bicycles[-1].title()) #当索引为-1时即访问最后一个元素 print() print("修改元素后:") bicycles[2] = 'redline' #修改元素 print(bicycles) print() print("bicycles.append('just_a_bike'):") bicycles.append('just_a_bike') #在列表末尾添加元素 print(bicycles) print() print("insert:") bicycles.insert(0,'other_bike') #在列表中插入元素(在n处添加空间,并将值储存在该位置) print(bicycles) print() print("del:") del bicycles[0] #删除指定索引元素(后面元素自动前移) print(bicycles) print() print("pop:") temp=bicycles.pop() #默认弹出最后一个元素,可加参数弹出指定元素 print(bicycles) print(temp) print() print("remove:") #根据元素的值删除指定元素 bicycles.remove("redline") print(bicycles)
true
70869bc5dbb1ae85577a618d2dd7ba9aec7bd802
Python
klaerik/Advent-of-Code
/y2020/day03.py
UTF-8
694
3.375
3
[]
no_license
import shared #from math import prod # Go right 3, down 1, count trees def sled(right, down, field): count = 0 x,y = 0, 0 bottom = len(field) while y < bottom: thing = field[y][x] if thing == '#': count += 1 y += down x += right if x >= len(field[0]): x -= len(field[0]) return count file = '2020/input/day03.txt' raw = shared.read_file(file) # Part 1 part1 = sled(3, 1, raw) print(f'Part 1: Hit {part1} trees') # Part 2 slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] tree_hits = [sled(right, down, raw) for right,down in slopes] part2 = shared.product(tree_hits) print(f'Part 2: Multiple is {part2}')
true
dbe757c944a92cbe2b7ef34f114b6a3dee3f49c6
Python
han-tun/Resources
/Python/Math/is_divisible_by.py
UTF-8
601
3.53125
4
[]
no_license
""" ------------------------------------ Creation date : 22/04/2017 (fr) Last update : 23/04/2017 (fr) Author(s) : Nicolas DUPONT Contributor(s) : Tested on Python 3.6 ------------------------------------ """ def IsDivisbleBy(nb,x): if nb % x == 0: return True else: return False nb = 2 nb2 = 3 nb3 = 4 print("----------------") By = IsDivisbleBy(nb,2) print(By) print("----------------") By = IsDivisbleBy(nb2,2) print(By) print("----------------") By = IsDivisbleBy(nb3,3) print(By) print("----------------") By = IsDivisbleBy(nb3,4) print(By) print("----------------")
true
7d5fa3d5a45173e410b21ac266b176a8ac58fd79
Python
ENFORMIO/mediaharvest
/experiments/crawler/crawl_sitemap.py
UTF-8
1,019
2.609375
3
[]
no_license
import urllib.parse import urllib.request import urllib.error import ssl import xml.etree.ElementTree as ET start_url = 'https://www.krone.at/sitemap.xml' f = urllib.request.urlopen(start_url) sitemap_xml = f.read() sitemapindex = ET.fromstring(sitemap_xml) sitemaps = [] for sitemap in sitemapindex: for loc in sitemap: if 'loc' in loc.tag: sitemaps.append(loc.text) print ("found %s sitemaps in first attempt") urls = [] for sitemap in sitemaps: print ("----------------------------------------") print ("found %s urls" % len(urls)) print ("sitemap %s" % sitemap) print ("----------------------------------------") f = urllib.request.urlopen(sitemap) urlset_xml = f.read() urlset = ET.fromstring(urlset_xml) for url in urlset: for loc in url: if 'loc' in loc.tag: #print (loc.text) urls.append(loc.text) f = open('../../data/krone-sitemap-urls.txt', 'w') for url in urls: f.writeline(url) f.close()
true
97df8909021ee31ca9e12e6172b3fa65a80dbe84
Python
redcholove/interview_preparing
/64_minimun_path_sum.py
UTF-8
941
3.046875
3
[]
no_license
class Solution: def minPathSum(self, grid): #dp[i][j] = 到[i][j]的最小path sum if not grid: return 0 m = len(grid) n = len(grid[0]) dp = [[float('inf') for _ in range(n)] for _ in range(m)] for i in range(m): for j in range(n): if i == 0 and j == 0: dp[i][j] = grid[i][j] elif i == 0: dp[i][j] = dp[i][j-1] + grid[i][j] elif j == 0: dp[i][j] = dp[i-1][j] + grid[i][j] else: dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j] return dp[-1][-1] if __name__ == '__main__': sol = Solution() grid = [[1,3,1],[1,5,1],[4,2,1]] result = sol.minPathSum(grid) print(result) print('success') print('time complexity: O(m*n)') print('space complexity: O(m*n)')
true
acc0c040d0524d48babb988e56a37cafce4db10b
Python
tranj5371/studious-train
/P3HW2_MealTipTax_Tran.py
UTF-8
1,299
4.125
4
[]
no_license
# CTI-110 # P3HW2 - MealTipTax # Johnny Tran # February 26, 2019 # Ask user to input the charge for food at restaurant Charge = float(input("How much did the restaurant charge you for the food? ")) # Ask user how much they would like to tip Tip = float(input("How much would you like to tip? (15%/18%/20%) ")) # Calculates the tip percentage and 7 percent sales tax if Tip == 15: Tips = Charge * .15 SalesTax = Charge * .07 Total = Charge + Tips + SalesTax # Displays the tip, tax, and total print("Your tip is", "%.2f" % Tips, "dollars, your sales tax is", "%.2f" % SalesTax, "dollars, and your total is", "%.2f" % Total, "dollars") elif Tip == 18: Tips = Charge * .18 SalesTax = Charge * .07 Total = Charge + Tips + SalesTax # Displays the tip, tax, and total print("Your tip is", "%.2f" % Tips, "dollars, your sales tax is", "%.2f" % SalesTax, "dollars, and your total is", "%.2f" % Total, "dollars") elif Tip == 20: Tips = Charge * .20 SalesTax = Charge * .07 Total = Charge + Tips + SalesTax # Displays the tip, tax, and total print("Your tip is", "%.2f" % Tips, "dollars, your sales tax is", "%.2f" % SalesTax, "dollars, and your total is", "%.2f" % Total, "dollars") else: print("Error, run again, enter 15, 18, or 20")
true
d2ede3d8c558437c71dfc0ccfe9797594d26a353
Python
aaskov/non-linear-signal-processing-toolbox
/nn/nn_gradient.py
UTF-8
3,993
3.5
4
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """ Neural network - nsp """ from __future__ import division import numpy as np from nn_forward import nn_forward def nn_gradient(Wi, Wo, alpha_i, alpha_o, train_input, train_target): """Calculate the partial derivatives of the quadratic cost function wrt. to the weights. Derivatives of quadratic weight decay are included. Args: Wi: Matrix with input-to-hidden weights.\n Wo: Matrix with hidden-to-output weights.\n alpha_i: Weight decay parameter for input weights.\n alpha_o: Weight decay parameter for output weights.\n train_input: Matrix with examples as rows.\n train_target: Matrix with target values as rows. Yields: dWi: Matrix with gradient for input weights.\n dWo: Matrix with gradient for output weights. Examples: Calculate gradients >>> dWi, dWo = nn_gradient(...) """ # Determine the number of samples exam, inp = train_input.shape # ======================= # FORWARD PASS # ======================= # Calculate hidden and output unit activations Vj, yj = nn_forward(Wi, Wo, train_input) # ======================= # BACKWARD PASS # ======================= # Calculate derivative # by backpropagating the errors from the desired outputs # Output unit deltas delta_o = -(np.atleast_2d(train_target).T - yj) # Hidden unit deltas r, c = Wo.shape delta_h = (1.0 - np.power(Vj, 2)) * (delta_o.dot(Wo[:, :-1])) # Partial derivatives for the output weights dWo = delta_o.T.dot(np.concatenate((Vj, np.ones((exam, 1))), 1)) # Partial derivatives for the input weights dWi = delta_h.T.dot(np.concatenate((train_input, np.ones((exam, 1))), 1)) # Add derivative of the weight decay term dWi = dWi + alpha_i*Wi dWo = dWo + alpha_o*Wo return (dWi, dWo) if __name__ == "__main__": # Example Ni = 4 # Number of external inputs Nh = 5 # Number of hidden units No = 1 # Number of output units alpha_i = 0.0 # Input weight decay alpha_o = 0.0 # Ouput weight decay max_iter = 500 # Maximum number of iterations eta = 0.001 # Gradient decent parameter t_Nh = 2 # Number of hidden units in TEACHER net noise = 1.0 # Relative amplitude of additive noise ptrain = 100 # Number of training examples ptest = 100 # Number of test examples I_gr = 1 # Inital max gradient iterations range = 0.5 # Inital weight range # Load data from data_random import get_random_data train_input, train_target, te_input, te_target = get_random_data(Ni, t_Nh, No, ptrain, ptest, noise) # Initialize network weights Wi = range*np.random.randn(Nh, Ni+1) Wo = range*np.random.randn(No, Nh+1) # dWi, dWo = nn_gradient(Wi, Wo, alpha_i, alpha_o, train_input, train_target) # Determine the number of samples exam, inp = train_input.shape # ###################### # # #### FORWARD PASS #### # # ###################### # # Calculate hidden and output unit activations Vj, yj = nn_forward(Wi, Wo, train_input) # ###################### # # #### BACKWARD PASS ### # # ###################### # # Calculate derivative of # by backpropagating the errors from the desired outputs # Output unit deltas delta_o = -(train_target - yj) # Hidden unit deltas r, c = Wo.shape delta_h = (1.0 - np.power(Vj, 2)) * (delta_o.dot(Wo[:, :c-1])) # Partial derivatives for the output weights dWo = delta_o.T.dot(np.concatenate((Vj, np.ones((exam, 1))), 1)) # Partial derivatives for the input weights dWi = delta_h.T.dot(np.concatenate((train_input, np.ones((exam, 1))), 1)) # Add derivative of the weight decay term dWi = dWi + alpha_i*Wi dWo = dWo + alpha_o*Wo
true
0564467595041d7d491c6c86d57a285993636bcd
Python
vancher85/hwork
/hw8/serializer1.py
UTF-8
1,496
3.890625
4
[]
no_license
# 1. Создать класс для сериализации данных Serializer. Объект класса принимает на вход сложный объект(list, dict, etc), и обладает методами loads и dumps. Эти методы работают так же как и json.loads и json.dumps. # 2. dumps принимает на вход один параметр - contetnt_type(это может быть json или pickle) и на выходе возвращает строку в нужном формате(json или pickle). # 3. Метод loads принимает два параметра - data и content_type, и возвращает новый объект типа Serializer со сложным объектом внутри import json import pickle serializers = {'json': json, 'pickle': pickle} class Serializer: def __init__(self, obj=None): self.obj = obj def get_method(self, content_type): return serializers.get(content_type) def dumps(self, content_type=None): print(self.get_method(content_type).dumps(self.obj)) def loads(self, data=None, content_type=None): print(self.get_method(content_type).loads(data)) d = Serializer() c = Serializer(obj={1: 2}) print('-pickle example-') c.dumps(content_type='pickle') d.loads(data=b'\x80\x03}q\x00K\x01K\x02s.', content_type='pickle') print('-json example-') c.dumps(content_type='json') d.loads(data='{"1": 2}', content_type='json')
true
a2eae89c82674dd0077f77556fa4538666c1b9e8
Python
DavidP92/kataChallenges
/summing_NumbersDigits.py
UTF-8
531
4.625
5
[]
no_license
##`Write a function named sumDigits which takes a number as input and returns the sum of the absolute value of each of the number's decimal digits. For example: ## sumDigits(10) # Returns 1 ## sumDigits(99) # Returns 18 ## sumDigits(-32) # Returns 5 ## Let's assume that all numbers in the input will be integer values. def sumDigits(number): conversion_str = str(abs(number)) conversion_list = list(conversion_str) placeHolderList = [int(x) for x in conversion_list] return sum(placeHolderList)
true
7f997b3debd89cba20ad4adaa4038fcd27ba01a7
Python
WyattBlue/auto-editor
/auto_editor/utils/chunks.py
UTF-8
1,209
2.875
3
[ "LGPL-3.0-only", "LicenseRef-scancode-public-domain", "Unlicense" ]
permissive
from __future__ import annotations from fractions import Fraction from typing import TYPE_CHECKING if TYPE_CHECKING: from numpy.typing import NDArray Chunk = tuple[int, int, float] Chunks = list[Chunk] # Turn long silent/loud array to formatted chunk list. # Example: [1, 1, 1, 2, 2], {1: 1.0, 2: 1.5} => [(0, 3, 1.0), (3, 5, 1.5)] def chunkify(arr: NDArray, smap: dict[int, float]) -> Chunks: arr_length = len(arr) chunks = [] start = 0 for j in range(1, arr_length): if arr[j] != arr[j - 1]: chunks.append((start, j, smap[arr[j - 1]])) start = j chunks.append((start, arr_length, smap[arr[j]])) return chunks def chunks_len(chunks: Chunks) -> Fraction: _len = Fraction(0) for chunk in chunks: if chunk[2] != 99999: speed = Fraction(chunk[2]) _len += Fraction(chunk[1] - chunk[0], speed) return _len def merge_chunks(all_chunks: list[Chunks]) -> Chunks: chunks = [] start = 0 for _chunks in all_chunks: for chunk in _chunks: chunks.append((chunk[0] + start, chunk[1] + start, chunk[2])) if _chunks: start += _chunks[-1][1] return chunks
true
d3bffcba8246d8e0cbdf6dc45796b7881f0d0857
Python
cbnsndwch/sagefy
/server/framework/database.py
UTF-8
2,478
2.6875
3
[ "Apache-2.0" ]
permissive
""" On each request, we create and close a new connection. Rethink was designed to work this way, no reason to be alarmed. """ import rethinkdb as r config = { 'rdb_host': 'localhost', 'rdb_port': 28015, 'rdb_db': 'sagefy', } def make_db_connection(): """ Create a database connection. """ return r.connect( host=config['rdb_host'], port=config['rdb_port'], db=config['rdb_db'], timeout=60 ) def close_db_connection(db_conn): """ Close the DB connection. """ db_conn.close() def setup_db(): """ Set up the database. Include a sequence to make sure databases and tables exist where they need to be. """ db_conn = make_db_connection() # add all setup needed here: if config['rdb_db'] not in r.db_list().run(db_conn): r.db_create(config['rdb_db']).run(db_conn) from models.user import User from models.notice import Notice from models.topic import Topic from models.post import Post from models.proposal import Proposal from models.vote import Vote from models.card import Card from models.unit import Unit from models.set import Set from models.card_parameters import CardParameters from models.unit_parameters import UnitParameters from models.set_parameters import SetParameters from models.follow import Follow from models.user_sets import UserSets from models.response import Response models = (User, Notice, Topic, Post, Proposal, Vote, Card, Unit, Set, CardParameters, UnitParameters, SetParameters, Follow, UserSets, Response) tables = r.db(config['rdb_db']).table_list().run(db_conn) for model_cls in models: tablename = getattr(model_cls, 'tablename', None) if tablename and tablename not in tables: (r.db(config['rdb_db']) .table_create(tablename) .run(db_conn)) tables.append(tablename) existant_indexes = (r.db(config['rdb_db']) .table(tablename) .index_list() .run(db_conn)) indexes = getattr(model_cls, 'indexes', []) for index in indexes: if index[0] not in existant_indexes: (r.db(config['rdb_db']) .index_create(*index) .run(db_conn)) close_db_connection(db_conn)
true
add647e472988ca2d598bdd5b590a011830db3d3
Python
hobart2018/python123
/linked_list.py
UTF-8
2,428
4.0625
4
[]
no_license
class Node: def __init__(self, value): self.value = value self.pointer = None print('定义 Node 完成') node1 = Node(1) node2 = Node(2) node3 = Node(3) node1.pointer = node2 node2.pointer = node3 def print_linked_list(node): if node.pointer: print(node.value, end='->') else: print(node.value,) if (node.pointer): print_linked_list(node.pointer) print_linked_list(node1) node4 = Node(4) node4.pointer = node1.pointer node1.pointer = node4 print_linked_list(node1) node4.pointer = node2.pointer print_linked_list(node1) def print_linked_list_length(node): #######################mark n = 0 ptr = node while ptr: n = n + 1 ptr = ptr.pointer return n print(print_linked_list_length(node1)) def is_value_in_linked_list(linkedlist, value): flag = False ptr = linkedlist while ptr: if ptr.value == value: flag = True ptr = ptr.pointer return flag print(is_value_in_linked_list(node1, 3)) class LinkedList(): def __init__(self): self.head = None def append(self, value): if not self.head: self.head = Node(value) return curr = self.head while curr.pointer: curr = curr.pointer curr.pointer = Node(value) def find(self, value): curr = self.head while curr and curr.value != value: curr = curr.pointer return curr def remove(self, value): #################################### tem_head = tem = Node(-1) curr = self.head while curr: if curr.value != value: tem.pointer = curr tem = tem.pointer curr = curr.pointer tem.pointer = None self.head = tem_head.pointer return def count (self): curr = self.head n = 0 while curr: n += 1 curr = curr.pointer return n def print_linked_list(linkedList): curr = linkedList.head while curr: print(curr.value, end='->') curr = curr.pointer print('\n') foo = LinkedList() print(foo.count(),'\n') foo.append(3) print(foo.count(),'\n') print_linked_list(foo) foo.append(1) print(foo.count(),'\n') print_linked_list(foo) foo.append(2) foo.append(3) print_linked_list(foo) foo.remove(3) print_linked_list(foo) print(foo.count(),'\n')
true
88e0b6d5765b35e338e8cf02247f71169b5d69c6
Python
ortiz1093/design-space
/dmaps_playground.py
UTF-8
3,948
2.765625
3
[]
no_license
import plotly.graph_objects as go import numpy as np from numpy.random import default_rng from numpy.linalg import norm, inv from scipy.linalg import eig, eigh from tqdm import tqdm from joblib import Parallel, delayed import sys import seaborn as sns import pandas as pd import plom.plom_v4_4 as plom from plom.plom_utils import setupArgs rng = default_rng(42) def rotate2D(X, deg, axis='origin'): vertical = True if X.shape[1]==2 else False X = X.T if vertical else X rad = np.radians(deg) R = np.array([[np.cos(rad), -np.sin(rad)], [np.sin(rad), np.cos(rad)]]) X_rot = R @ X return X_rot.T if vertical else X_rot # def minmax_cols(X): # n_rows, n_cols = X.shape # col_mins = np.tile(X.min(0), [n_rows, 1]) # col_maxs = np.tile(X.max(0), [n_rows, 1]) # return (X - col_mins) / (col_maxs - col_mins) # def diffusion_kernel(x0, x1, eps): # return np.exp(-norm(x0 - x1) / eps) # def compute_distance_matrix_element(i, j, X, eps): # return i, j, diffusion_kernel(X[i, :], X[j, :], eps) # def distance_matrix(X, n_dim, eps): # assert n_dim in X.shape, "X does not match the specified number of dimensions" # X = X if X.shape[1] == n_dim else X.T # n_pts = X.shape[0] # K = np.empty([n_pts, n_pts]) # # for i in tqdm(range(n_pts), desc='Building matrix K', position=0): # # for j in range(i, n_pts): # # K[i, j] = K[j, i] = diffusion_kernel(X[i, :], X[j, :], eps) # inputs = tqdm([(i, j) for i in range(num_pts) for j in range(i, num_pts)]) # params = [X, eps] # elements = Parallel(n_jobs=8)(delayed(compute_distance_matrix_element)(*i, *params) for i in inputs) # for i, j, K_ij in elements: # K[i, j] = K[j, i] = K_ij # return K # def dmaps(X, n_dim, eps=10): # """ # Computes the diffusion map of X and returns the transformed dataset. Each column of Y is one point in the dataset. # Rows in Y are sorted by descending importance, i.e. the first coordinate/row of each point is the most import, etc. # """ # assert X.shape[1] == n_dim, "X must be vertical array (samples->rows, features->columns)" # X_scaled = minmax_cols(X) # t1 = time() # K = distance_matrix(X_scaled, n_dim, eps) # # print(f'Distance Matrix time: {round(time() - t1, 2)}s') # D = np.diag(K.sum(1)) # t2 = time() # P = inv(D) @ K # # print(f'Inversion time: {round(time() - t2, 2)}s') # t3 = time() # # w, v_left = eigh(P) # w, v_left = eig(P, left=True, right=False) # # print(f'Eigenvalues time: {round(time() - t3, 2)}s') # w = np.real(w) # i_sort = np.flip(w.argsort()) # w = w[i_sort] # v_left = v_left[i_sort] # return np.diag(w) @ v_left.T from time import time t0 = time() num_grps = 5 num_pts = 500 num_turns = 4 r = 1 h = 3 theta = np.linspace(0, 2 * np.pi * num_turns, num_pts) x = r * np.cos(theta) y = r * np.sin(theta) z = np.linspace(-h, h, num_pts) X = np.array([x, y, z]).T grp_size = num_pts // num_grps grp_labels = np.array([[i]*grp_size for i in range(num_grps)]).flatten()[:num_pts] t_plom = time() epsilon = 30 args_plom = setupArgs(X, epsilon, sampling=True) plom_dict = plom.initialize(**args_plom) plom.run(plom_dict) print(f'PLoM took {round(time() - t_plom, 2)}s') X_plom = plom_dict['dmaps']['basis'] plomDF = pd.DataFrame(X_plom[:,1:6]) plomDF['group'] = grp_labels # sns.pairplot(plomDF.loc[:,[0,2,'group']], hue='group', palette='hls') sns.pairplot(plomDF, hue='group', palette='hls') # import matplotlib.pyplot as plt # plt.show() # quit() Z = np.array([ [0.0001, 0.0001, 0.0002, -1, 1], [-0.0002, -0.0001, 0.0002, 1, -1], [0.0002, 0.0002, 0, 0, 0] ]) X_new = plom._inverse_dmaps(Z, X_plom[:,1:6]) fig = go.Figure(data=[ go.Scatter3d(x=X[:, 0], y=X[:, 1], z=X[:, 2]), go.Scatter3d(x=X_new[:, 0], y=X_new[:, 1], z=X_new[:, 2]) ] ) fig.show()
true
48dc3092822c3dc2ac9af3f2ed77ad4c249880f1
Python
suryaaathhi/guvi-program
/factno.py
UTF-8
67
3.28125
3
[]
no_license
val1=int(input()) n=1 for i in range(1,val1+1): n=n*i print(n)
true
711f4eae0d89a2146818423daf951a62a842d26b
Python
Aasthaengg/IBMdataset
/Python_codes/p03161/s612812265.py
UTF-8
341
2.765625
3
[]
no_license
n,k = map(int,input().split()) arr = list(map(int,input().split())) dp = [0] * n dp[0] = 0 dp[1] = abs(arr[1] - arr[0]) for i in range(2,n): for j in range(1,k+1): if i - j < 0: break if j == 1: dp[i] = dp[i-j]+abs(arr[i-j] - arr[i]) else: dp[i] = min(dp[i], dp[i-j]+abs(arr[i-j] - arr[i])) print(dp[-1])
true
f3eefe168776c1173fe236992812a1736c9464fd
Python
Spekks/python-SEAS-Ejercicios
/Ejercicios/Unidad 4/Caso/UD04_EG1.py
UTF-8
2,129
4.625
5
[]
no_license
# Ejercicio guiado. Unidad 4. # a) Vamos a dibujar cuadrados rellenos utilizando el carácter car que se pasará como argumento. Se pasan también el # desplazamiento de cada línea (valor de a) y el número de caracteres que se escriben (valor de b) que es igual al # número de líneas que se escriben. Todos ellos son de entrada (pasados por valor). comprobar = False while not comprobar: caracter = input("Escribe un carácter: ") if len(caracter) > 1: print("inténtalo otra vez.") else: comprobar = True x = int(input("Escribe un número:")) y = int(input("Escribe un número:")) def cuadrado(a, b, car): # Lo que pide el ejercicio for i in range(b): print(" " * a, (car + " ") * b) def cuadrado2(a, b, car): # Lo que para mí tendría sentido for i in range(a): print((car + " ") * b) cuadrado(x, y, caracter) cuadrado2(x, y, caracter) # b) En este ejercicio se utiliza en la izquierda una variable local s cuyo valor se quiere imprimir antes de haberle # asignado un valor. Genera un error. def f(): global s # Si no asignamos la variable s como global, que traeremos luego en ámbito global, no funciona. print(s) s = "Hola, ¿quién eres?" # Al haber definido s como global, esta instancia de s NO es local, es la variable global. print(s) s = "Hola, soy Pepe" f() print(s) # Imprimirá el nuevo valor de s instanciado dentro de la función f(), pues esta utiliza s global. # c) Vamos a usar parámetros mutables para ver el efecto del procedimiento sobre estos parámetros. Para ello, vamos a # pasar una lista de enteros a la función y vamos a hacer que devuelva la lista ordenada. Lo hacemos como ejercicio, ya # que en la práctica existe un método (sort) que realiza esta operación. lNumeros = [30, 1, 43, 2, 45, 1, 4, 4, 13] def ordenar(lst): for z in range(len(lst)-1): iControl = lst[z] for i in range(len(lst)-1): if lst[i] > lst[i+1]: iControl = lst[i+1] lst[i+1] = lst[i] lst[i] = iControl print(lst) ordenar(lNumeros)
true
62a37d08cd903def00191005604aabcd6e26cf09
Python
nayan5565/PythonFirstProject
/FileHandle.py
UTF-8
456
2.90625
3
[]
no_license
# w=write,r=read, a=append, rb=read binary fileWrite = open('abc', 'a') # fileWrite.write('Nurul',) fileRead = open('abc', 'r') # print(fileRead.read()) # for i in fileRead: # print(i, end='') # fileNewWrite = open('xyz', 'w') # for data in fileRead: # fileNewWrite.write(data) imgFile = open('images/laptop.jpg', 'rb') # for i in imgFile: # print(i) createImg = open('images/laptopNew.jpg', 'wb') for i in imgFile: createImg.write(i)
true
ddd3ba8433b63344af677d72c6c5f9e73519d383
Python
bcsummers/gh-action-testing
/tests/Custom/app.py
UTF-8
1,355
2.65625
3
[ "Apache-2.0" ]
permissive
"""Falcon app used for testing.""" # standard library import logging from typing import Any # third-party import falcon # first-party from gh_action_testing.middleware import LoggerMiddleware class LoggerCustomLoggerResource: """Logger middleware testing resource.""" log = None def on_get(self, req: falcon.Request, resp: falcon.Response) -> None: """Support GET method.""" key: str = req.get_param('key') self.log.debug(f'DEBUG {key}') self.log.info(f'INFO {key}') self.log.warning(f'WARNING {key}') self.log.error(f'ERROR {key}') self.log.critical(f'CRITICAL {key}') resp.text = f'Logged - {key}' def on_post(self, req: falcon.Request, resp: falcon.Response) -> None: """Support POST method.""" key: str = req.get_param('key') value: Any = req.get_param('value') self.log.debug(f'DEBUG {key} {value}') self.log.info(f'INFO {key} {value}') self.log.warning(f'WARNING {key} {value}') self.log.error(f'ERROR {key} {value}') self.log.critical(f'CRITICAL {key} {value}') resp.text = f'Logged - {key}' logger: object = logging.getLogger('custom') app_custom_logger = falcon.App(middleware=[LoggerMiddleware(logger=logger)]) app_custom_logger.add_route('/middleware', LoggerCustomLoggerResource())
true
e2290de649a5b94fb348281ad19c3904c96562b8
Python
MrNothing/General-AI-Modules
/Modules/DepthEstimator/DepthMapOptimizer/DepthEstimator/ImagesLoader.py
UTF-8
1,767
2.921875
3
[ "MIT" ]
permissive
from os import listdir from os.path import isfile, join import random as rand from PIL import Image import numpy as np #description Loader template #type data source #icon fa fa-sort-numeric-asc #param int image_width = 64 #param int input_size = 10 #param int labels_size = 2 #param int batch_size = 100 #param folder rgb_folder = "" #param folder depth_folder = "" self.onlyfiles = [f for f in listdir(self.rgb_folder) if not isfile(join(self.rgb_folder, f))] Log("rgb files: "+str(len(self.onlyfiles))) #This function is called by the trainer to fetch data #It output two arrays: one for the inputs, and the other for the labels #Example inputs: x=[[1, 0, 0], [0, 1, 0], ...] #Example labels: y=[[1, 0], [0, 1], ...] def getNextBatch(self): x = [] y = [] #TODO: fetch some data here... for i in range(self.batch_size): index = self.getRandomIndex() data = [] data += self.image_file_to_tensor(self.rgb_folder+"/"+self.onlyfiles[index]+"/sc_9.png") x.append(data) y.append(self.image_file_to_tensor(self.depth_folder+"/"+self.onlyfiles[index]+"/sc_9.png")) return x, y #same rules as 'getNextBatch' except this is from the test dataset def getTestBatch(self): x = [] y = [] #TODO: fetch some test data here... return x, y def getRandomIndex(self): return rand.randint(0, len(self.onlyfiles)-1) def image_file_to_tensor(self, path): imgpil = Image.open(path) # anciennement np.asarray img = np.array(imgpil.getdata()).reshape(imgpil.size[0], imgpil.size[1], 3) return self.rgb_to_grayscale(img) def rgb_to_grayscale(self, img_orig): r_im = np.copy(img_orig) # On fait une copie de l'original im = [] for i in range(self.image_width): for j in range(self.image_width): r, g, b = r_im[i, j] im.append(r/255) return im
true
7ff135d93da6ffa355bb7cf1e4638ba5856a28bc
Python
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_54/278.py
UTF-8
637
2.953125
3
[]
no_license
import sys sys.setrecursionlimit(100000) def gcd(a,b): if a<b: c=a a=b b=c if b==0: return a else: return gcd(b,a%b) def gcd_n(input_list,n): if n==1: return input_list[0] return gcd(input_list[n-1],gcd_n(input_list,n-1)) inp=raw_input() times=int(inp) for i in range(1,times+1): eachline=raw_input() each_split=eachline.split() n=int(each_split[0]) data=[] for j in range(1,n): data.append(abs(int(each_split[j])-int(each_split[j+1]))) result=gcd_n(data,n-1) if int(each_split[1]) % result==0: print 'Case #'+str(i)+': 0' else: print 'Case #'+str(i)+': '+str(result-(int(each_split[1])%result))
true
038efe54ebff88b116ce71aebdb701d83e323365
Python
xiaoyaoyth/AeroSandbox
/tutorial/1 - Optimization and Math/2 - 2D Rosenbrock, constrained.py
UTF-8
1,959
4.4375
4
[ "MIT" ]
permissive
""" Let's do another example with the Rosenbrock problem that we just solved. Let's try adding a constraint to the problem that we previously solved. Recall that the unconstrained optimum that we found occured at (x, y) == (1, 1). What if we want to know the minimum function value that is still within the unit circle. Clearly, (1, 1) is not inside the unit circle, so we expect to find a different answer. Let's see what we get: """ import aerosandbox as asb opti = asb.Opti() # Define optimization variables x = opti.variable(init_guess=1) # Let's change our initial guess to the value we found before, (1, 1). y = opti.variable(init_guess=1) # As above, change 0 -> 1 # Define objective f = (1 - x) ** 2 + 100 * (y - x ** 2) ** 2 opti.minimize(f) # Define constraint r = (x ** 2 + y ** 2) ** 0.5 # r is the distance from the origin opti.subject_to( r <= 1 # Constrain the distance from the origin to be less than or equal to 1. ) """ Note that in continuous optimization, there is no difference between "less than" and "less than or equal to". (At least, not when we solve them numerically on a computer - contrived counterexamples can be made.) So, use < or <=, whatever feels best to you. """ # Optimize sol = opti.solve() # Extract values at the optimum x_opt = sol.value(x) y_opt = sol.value(y) # Print values print(f"x = {x_opt}") print(f"y = {y_opt}") """ Now, we've found a new optimum that lies on the unit circle. The point that we've found is (0.786, 0.618). Let's check that it lies on the unit circle. """ r_opt = sol.value(r) # Note that sol.value() can be used to evaluate any object, not just design variables. print(f"r = {r_opt}") """ This prints out 1, so we're satisfied that the point indeed lies within (in this case, on, the unit circle). If we look close, the value isn't exactly 1 - mine says `r = 1.0000000099588466`; yours may be different. This is due to convergence error and isn't a big deal. """
true
0b73e8adfac8219ce4ed111f9ad1ba2f698e0165
Python
tugceseren/12.03.2021-ve-ncesi-al-malar
/örnek 4.py
UTF-8
911
3.609375
4
[]
no_license
a=5 b=4 c=3 if a>b: if a>c: print("a:", a, "en büyük") if b>c: print("c:", c, "en küçük") print("b:", b) elif b==c: print("b:", b, " ve", "c:", c, "en küçük") elif a==c: print("a:", a, " ve ", "c:", c, "en büyük, ", "b:", b, "en küçük") if b>a: if b>c: print("b:", b, "en büyük") if a>c: print("c:", c, "en küçük") print("a:", a) elif a==c: print("a:", a, " ve", "c:", c, "en küçük") elif b==c: print("b:", b, " ve ", "c:", c, "en büyük, ", "a:", a, "en küçük") if c>a: if c>b: print("c:", c, "en büyük") if a>b: print("b:", b, "en küçük") print("c:", c) elif a==b: print("a:", a, " ve", "b:", b, "en küçük") elif c==b: print("c:", c, " ve ", "b:", b, "en büyük, ", "a:", a, "en küçük") else: print("hatalı sayı girdiniz") print("---BİTTİ---")
true
4e8ab373953f4bd8651d3c605da6aa627a905003
Python
FAMAF-resources/anfamaf2021
/codigos/lab2/ej7.py
UTF-8
576
3.09375
3
[]
no_license
import ej1 import ej3 import ej5 import math def lab2ej7bisec(x): # calcula u(x) = y fun_auxiliar = lambda y : y - math.exp(-(1-x*y)**2) hy, hu = ej1.rbisec(fun_auxiliar, [0.0,2.0], 1e-6, 100) y = hy[-1] return y def lab2ej7newton(x): # calcula u(x) = y fun_auxiliar = lambda y : (y - math.exp(-(1-x*y)**2), \ 1 - math.exp(-(1-x*y)**2)*(-2*(1-x*y)*(-x))) hy, hu = ej3.rnewton(fun_auxiliar, 1.0, 1e-6, 100) y = hy[-1] return y def lab2ej7ipf(x): fun_auxiliar = lambda y : math.exp(-(1-x*y)**2) hy = ej5.ripf(fun_auxiliar, 1.0, 1e-6, 100) y = hy[-1] return y
true
0d597965d02bebe52e908ca2a5788f9ad22423c3
Python
lalitpa/N-QUEEN-CONSOLE-GAME
/N queen.py
UTF-8
1,876
3.28125
3
[]
no_license
print("IF U WANT TO DELETE PREVIOUS ONE OF THE INPUT. ENTER 'delete' IN 'row' INPUT") print('ROW AND COLUMN ENTRIES STARTING FROM 0') n=int(input('no. of grids')) print('LEVEL',n,' STARTED') def GAME(n): a=n l=[] def deleteinput(): l.remove(l[-1]) def deletepriviousentry(): x=int(input('deleterow')) y=int(input('deletecolumn')) l.remove([x,y]) print('DELETED') def game(a): x=input('row') if x=='delete': deletepriviousentry() return game(a+1) y=int(input('column')) z=int(x) if z<n and y<n: l.append([z,y]) if a==n: print('queen',a,'is added') else: for j in l[0:-1]: if block(j[0],j[1])==0: deleteinput() print('enter again') return game(a) break else: print('queen ',(a),'is added') if a-1==0: print('YOU COMPLETED LEVEL',n,' SUCCESSFULLY') print('NEXT LEVEL',n+1,' STARTED') a=n+1 return GAME(n+1) else: return game(a-1) else: print('ENTER THE ROW AND COLUMN ONE LESS THAN LEVEL NUMBER') return game(a) def block(r,c): #after input blocked boxex k=l[-1] x=k[0] y=k[1] t=[] #POSSIBLE POSITIONS LIST for i in range(min(r,c)+1): (a,b)=(r,c) (a,b)=(r+i,c-i) t.append([a,b]) t.append([b,a]) if (x-y)==r-c or x==r or y==c or [x,y] in t: return 0 else: return 1 game(a) GAME(n)
true
479b66298961d2090e7e6319d94892b7ac4c3472
Python
ahchen0/Tasker
/TaskerGui/TaskerTreeView.py
UTF-8
10,466
2.53125
3
[]
no_license
# Tasker treeview class import tkinter as tk from tkinter import ttk from tkinter.filedialog import askopenfilename from tkinter import messagebox import h5py import matplotlib.pyplot as plt from tkinter import PhotoImage from TreeViewPlus import TreeViewPlus from PIL import Image, ImageTk, ImageOps from TaskerPoint import Point import MenuBar class TaskerTreeView(tk.Frame): """ Creates the Treeview for use in the Tasker GUI. :ivar spacecraft[] satList: List of satellites plotted :ivar Point[] pointList: List of points plotted :ivar masterList: List of satellites and points plotted :param Application master: The parent application of the treeview :param int width: the width of the tree view :param int height: the height of the tree view :param strfont_name: the font used for the text in the tree :param int font_size: the font size used for the text in the tree :param str font_color: the font color used for the text in the tree :param str indicator_foreground: the indicator foreground color :param str background: the background color """ satList = [] pointList = [] masterList = [] def __init__(self, master, width=500, height=500, font_name="Times", font_size=12, font_color="black", indicator_foreground="black", background="white"): tk.Frame.__init__(self, master) self.master = master self.subscribers = [] self.openFiles = [] self.ids = [] self.width=width self.height=height self.font_name = font_name self.font_size=font_size self.font_color=font_color self.indicator_foreground=indicator_foreground self.background=background self.treeview = TreeViewPlus(self, width=self.width, height=self.height, font_name=self.font_name, font_size=self.font_size, font_color=self.font_color, indicator_foreground=self.indicator_foreground, background=self.background) self.treeview.pack(side="left",fill=tk.BOTH,expand=True) self.treeview.bind('<<TreeviewSelect>>',self.select) ##self.treeview.bind('<<TreeviewMenuSelect>>',self.menu_select) def event_subscribe(self, obj_ref): """ Subscribes obj_ref to the TaskerGui. :param obj_ref: object to be subscribed to TaskerGui """ self.subscribers.append(obj_ref) def event_publish(self, cmd): """ Publishes an event to all subscribers :param str cmd: Command to be published """ for sub in self.subscribers: sub.event_receive(cmd) def event_receive(self,event): """ Receives an event from a subscription :param event: The event received from a subscription """ if len(event) > 0: type = event[0] if ( type == "TaskerMenuBar::addSatellite" or type == "TaskerButtonBar::addSatellite" ): if len(event)>1: filename = event[1] self.addSatellite(filename) else: return def addSatellite(self, satellite): """ Adds a satellite to the tree :param satellite satellite: Satellite to be added to the tree """ self.satList.append(satellite) self.masterList.append(satellite) file_options={} file_options["menu-options"] = {"tearoff": 0} ## not sure why I have to do this, but its only invoking ONE method, thelast one specified, ## so I am making that method do difft things basedon the value of choice. #file_options["menu-items"] = [ {"label":"", "command": self.fileMenu, "choice":"nothing"}, # {"label":"close", "command": self.fileMenu, "choice":"close"}, # ] file_options["menu-items"] = [ {"label":"close", "command": self.fileMenu, "choice":"close"}, ] f_id = self.treeview.insert('','end',values=(["text",satellite.name,file_options],), hidden="file") self.treeview.insert(f_id, 'end', values =(["text", "Catalog Num: " + satellite.catalogNumber],), hidden = "image") self.treeview.insert(f_id, 'end', values =(["text", "Intl Designator: " + satellite.intlDesignator],), hidden = "image") self.treeview.insert(f_id, 'end', values =(["text", "Epoch Year: " + satellite.epochYear],), hidden = "image") self.treeview.insert(f_id, 'end', values =(["text", "Epoch Day: " + satellite.epochDay],), hidden = "image") self.treeview.insert(f_id, 'end', values =(["text", "1st Deriv Mean Motion: " + satellite.firstDerivativeOfMeanMotion],), hidden = "image") self.treeview.insert(f_id, 'end', values =(["text", "2nd Deriv Mean Motion: " + satellite.secondDerivativeOfMeanMotion],), hidden = "image") self.treeview.insert(f_id, 'end', values =(["text", "Drag Term: " + satellite.dragTerm],), hidden = "image") self.treeview.insert(f_id, 'end', values =(["text", "Ephemeris Type: " + satellite.ephemerisType],), hidden = "image") self.treeview.insert(f_id, 'end', values =(["text", "Element Set Number: " + satellite.elementSetNumber],), hidden = "image") self.treeview.insert(f_id, 'end', values =(["text", "Inclination: " + satellite.inclination],), hidden = "image") self.treeview.insert(f_id, 'end', values =(["text", "R.A.A.N.: " + satellite.raan],), hidden = "image") self.treeview.insert(f_id, 'end', values =(["text", "Eccentricity: " + satellite.eccentricity],), hidden = "image") self.treeview.insert(f_id, 'end', values =(["text", "Arg of Perigee: " + satellite.argumentOfPerigee],), hidden = "image") self.treeview.insert(f_id, 'end', values =(["text", "Mean Anomaly: " + satellite.meanAnomaly],), hidden = "image") self.treeview.insert(f_id, 'end', values =(["text", "Mean Motion: " + satellite.meanMotion],), hidden = "image") self.treeview.insert(f_id, 'end', values =(["text", "Rev Num at Epoch: " + satellite.revolutionNumberAtEpoch],), hidden = "image") def addPoint(self, point): """ Adds a point to the tree :param Point point: Point to be added to the tree """ self.masterList.append(point) self.pointList.append(point) file_options={} file_options["menu-options"] = {"tearoff": 0} file_options["menu-items"] = [ {"label":"close", "command": self.fileMenu, "choice":"close"}, ] f_id = self.treeview.insert('','end',values=(["text",point.name,file_options],), hidden="file") self.treeview.insert(f_id, 'end', values =(["text", "Latitude: " + str(point.lat)],), hidden = "image") self.treeview.insert(f_id, 'end', values =(["text", "Longitude: " + str(point.lon)],), hidden = "image") ######################################################################## def fileMenu(self, choice=None, iid=None): """ Creates the file menu :param choice :param iid """ if iid is None: return #print("fileMenu: iid="+iid+", choice="+str(choice)) if choice == "close": file_name = self.item_text(self.treeview.item(iid,option="values")) self.treeview.delete_item(iid) self.event_publish(["TaskerTreeView::fileClose",file_name]) print("event published:"+"TaskerTreeView::fileClose, filename="+file_name) # Remove satellite from satList for sat in self.satList: if sat.name == file_name: self.satList.remove(sat) # Remove point from pointList for point in self.pointList: if point.name == file_name: self.pointList.remove(point) # Remove from masterList for obj in self.masterList: if obj.name == file_name: self.masterList.remove(obj) self.master.canvas.plotter.updateAll() def item_text(self,item): """ Given a tuple of values, return the text contents, or an empty string """ if item is None: return "" for entry in item: if entry[0]=="text": return entry[1] return "" def select(self,args): """ When the item's text is clicked on with mouse button 1. """ sel_id = self.treeview.selection()[0] item = self.treeview.item(sel_id,option="values") hidden = self.treeview.item(sel_id,option="hidden") #print("geostar-treeview:: select: selection="+str(sel_id)+", "+str(hidden)+", "+str(item)) print("geostar-treeview:: select: selection="+str(sel_id)+", "+str(hidden)) return
true
22a3cb21d85dc8c092824368e1f1c322a31aa02c
Python
marcomafcorp/synapse
/synapse/tests/test_lib_urlhelp.py
UTF-8
2,155
2.515625
3
[ "Apache-2.0" ]
permissive
import synapse.exc as s_exc import synapse.lib.urlhelp as s_urlhelp import synapse.tests.utils as s_t_utils class UrlTest(s_t_utils.SynTest): def test_urlchop(self): url = 'http://vertex.link:8080/hehe.html' info = s_urlhelp.chopurl(url) self.eq({'scheme': 'http', 'port': 8080, 'host': 'vertex.link', 'path': '/hehe.html', }, info ) url = 'tcp://pennywise:candy@vertex.link/' info = s_urlhelp.chopurl(url) self.eq({'scheme': 'tcp', 'user': 'pennywise', 'host': 'vertex.link', 'path': '/', 'passwd': 'candy', }, info ) url = 'tcp://pennywise@vertex.link' info = s_urlhelp.chopurl(url) self.eq({'scheme': 'tcp', 'user': 'pennywise', 'host': 'vertex.link', 'path': '', }, info ) url = 'tcp://1.2.3.4:8080/api/v1/wow?key=valu&foo=bar' info = s_urlhelp.chopurl(url) self.eq({'scheme': 'tcp', 'host': '1.2.3.4', 'port': 8080, 'path': '/api/v1/wow', 'query': {'key': 'valu', 'foo': 'bar', } }, info ) url = 'http://[1fff:0:a88:85a3::ac1f]:8001/index.html' info = s_urlhelp.chopurl(url) self.eq({'scheme': 'http', 'host': '1fff:0:a88:85a3::ac1f', 'port': 8001, 'path': '/index.html', }, info ) url = 'http://::1/index.html' info = s_urlhelp.chopurl(url) self.eq({'scheme': 'http', 'host': '::1', 'path': '/index.html', }, info ) self.raises(s_exc.BadUrl, s_urlhelp.chopurl, 'www.vertex.link')
true
f03a1b9723200c8ced4a481e87459dac3ab02882
Python
lnybrave/zzbook
/utils/public_fun.py
UTF-8
916
2.6875
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/python # -*- coding: utf-8 -*- import os import random import time # 构造文件名称 from django.core.mail import send_mail from ebook.settings import EMAIL_FROM def makename(name): # 文件扩展名 ext = os.path.splitext(name)[1] # 定义文件名,年月日时分秒随机数 fn = time.strftime('%Y%m%d%H%M%S') fn += '_%d' % random.randint(1, 10000) # 重写合成文件名 name = fn + ext return name # 随机生成验证码 def randomCode(length): num = '0123456789' return ''.join(random.sample(num, length)) # 发送邮箱验证码 def send_email_code(email, code, type=1): if type == 1: email_title = "注册" email_body = "验证码:{0}".format(code) send_status = send_mail(email_title, email_body, EMAIL_FROM, [email]) if send_status: pass return True else: return False
true
a22f2e7e66a2f5b12351160b924ac00a8e84e475
Python
LuisArmandoPerez/MasterThesis
/Tensorflow/resources/sinusoidal.py
UTF-8
3,789
3.0625
3
[]
no_license
import numpy as np from itertools import product def sinusoid_data_generation_1D(n_Phi, n_T, omega): """ Creates n_Phi sinusoidal signals with n_T points per signal each with angular frequency of omega. :param n_Phi: number of partitions of phase interval :param n_T: number of partitions of time interval :param omega: angular frequency of sinusoids :return: phase_range::array, time_range:: array, sinusoids::array """ # Discretization of phase interval [0,2pi] phase_range = 2 * np.pi * np.linspace(0, 1, n_Phi) # Time range time_range = np.linspace(0, 1, n_T) # Signals sinusoids = np.sin(np.subtract.outer(phase_range, -(omega * time_range))) return phase_range, time_range, sinusoids def sinusoid_from_phase(phases, n_T, omega): time_range = np.linspace(0, 1, n_T) sinusoids = np.sin(np.subtract.outer(phases, -(omega * time_range))) return time_range, sinusoids def sinusoid_image_phase_combination(phases1, phases2, n_T, omega_values): """ This function produces an array where each row corresponds to a sinusoidal signal with a given phase and angular frequency omega. The columns represent the time sampling from the interval [0,1]. :param phases: Vector with the phases to be used :param n_T: Number of elements in the partition of the interval [0,1] :param omega: Angular frequency :return: np.array with shape (len(phases),n_T) """ # Sampling from phase and space space_linspace = np.linspace(0, 1, n_T) # Create all possible combinations of phi_1, phi_2 phase_combinations = np.array(list(product(phases1, phases2))) sinusoid_images = np.zeros((n_T, n_T, len(phase_combinations))) # Create spatial mesh spatial_mesh = np.meshgrid(space_linspace, space_linspace) # Generate signals for each combination for num_mesh, mesh_dimension in enumerate(spatial_mesh): # Omega*dimension mesh_expanded_dim = omega_values[num_mesh] * mesh_dimension[:, :, np.newaxis] repeated_volume = np.repeat(mesh_expanded_dim, repeats=len(phase_combinations), axis=2) # sine(Omega*dimension+phase) sinusoid_images += np.sin(np.add(repeated_volume, phase_combinations[:, num_mesh])) sinusoid_images = np.swapaxes(sinusoid_images, 2, 0) return phase_combinations, sinusoid_images def sinusoid_image_phase(phases1, phases2, n_T, omega_values): """ This function produces an array where each row corresponds to a sinusoidal signal with a given phase and angular frequency omega. The columns represent the time sampling from the interval [0,1]. :param phases: Vector with the phases to be used :param n_T: Number of elements in the partition of the interval [0,1] :param omega: Angular frequency :return: np.array with shape (len(phases),n_T) """ # Sampling from phase and space space_linspace = np.linspace(0, 1, n_T) # Create all possible combinations of phi_1, phi_2 phases1 = np.expand_dims(phases1, 1) phases2 = np.expand_dims(phases2, 1) phases = np.concatenate((phases1, phases2), axis=1) sinusoid_images = np.zeros((n_T, n_T, len(phases))) # Create spatial mesh spatial_mesh = np.meshgrid(space_linspace, space_linspace) # Generate signals for each combination for num_mesh, mesh_dimension in enumerate(spatial_mesh): # Omega*dimension mesh_expanded_dim = omega_values[num_mesh] * mesh_dimension[:, :, np.newaxis] repeated_volume = np.repeat(mesh_expanded_dim, repeats=len(phases), axis=2) # sine(Omega*dimension+phase) sinusoid_images += np.sin(np.add(repeated_volume, phases[:, num_mesh])) sinusoid_images = np.swapaxes(sinusoid_images, 2, 0) return phases, sinusoid_images
true
8aebf4cb1c911afd6c9552c649f23d3ff673ab18
Python
nhzaci/KattisSolutions
/ADifferentProblem/adifferentproblem.py
UTF-8
194
3.015625
3
[]
no_license
import sys multiline_input = sys.stdin.read().split('\n') for line in multiline_input: if line != '': first, second = map(lambda x: int(x), line.split()) print(abs(first - second))
true
05016fa61004d1af275a9f2cfd54435e9062653d
Python
muchemwal/dataops-infra
/samples/ml-ops-on-aws-img-recognition/source/containers/ml-ops-byo-custom/LambdaScripts/result_analysis.py
UTF-8
6,342
2.9375
3
[ "MIT" ]
permissive
import os import boto3 # Python library for Amazon API import botocore from botocore.exceptions import ClientError import pandas as pd # for taking CSVs of the case description and prediction # this is after there is analysis on thresholds and that the column predicted val in the predictions csv exists # the filenames largely depend on referencing what is available in s3 bucket def get_bucketfilenames(bucket_name): s3 = boto3.resource("s3") s3_client = boto3.client("s3") bucket = s3.Bucket(bucket_name) bucket_datalist = [] for my_bucket_object in bucket.objects.all(): bucket_datalist.append(my_bucket_object.key) cleansed_bucket_datalist = [f for f in bucket_datalist if "full_dataset" in f] bucket_filesdf = pd.DataFrame(cleansed_bucket_datalist, columns=["rawfilenames"]) return bucket_filesdf def parse_bucketfilesdf(bucket_filesdf): bucket_filesdf["folder0"] = bucket_filesdf["rawfilenames"].str.split("/").str[0] bucket_filesdf["folder1"] = bucket_filesdf["rawfilenames"].str.split("/").str[1] bucket_filesdf["folder2"] = bucket_filesdf["rawfilenames"].str.split("/").str[2] bucket_filesdf["filename"] = bucket_filesdf["rawfilenames"].str.split("/").str[3] bucket_filesdf["casenum"] = bucket_filesdf.folder2.str.extract("(\d+)") bucket_filesdf["casenum"] = pd.to_numeric( bucket_filesdf["casenum"], errors="coerce" ) bucket_filesdf = bucket_filesdf.dropna(subset=["casenum"]) bucket_filesdf = bucket_filesdf[bucket_filesdf["folder1"] == "curated_dataset"] return bucket_filesdf def merge_restructure_df(case_desc, preds, bucket_filesdf): preds["imagename"] = preds["filenames"].str.split("/").str[1] filesnames_preds = bucket_filesdf.merge( preds, how="right", left_on="filename", right_on="imagename" ) allmerged = filesnames_preds.merge(case_desc, left_on="casenum", right_on="case_id") return allmerged def collect_most_exemplary_images(num_examples, allmerged_select): # returns the paths for the highest scoring by probability for 0 and 1 most_exemplary_0 = allmerged_select.sort_values("predictions", ascending=True)[ "rawfilenames" ][:num_examples].values most_exemplary_1 = allmerged_select.sort_values("predictions", ascending=False)[ "rawfilenames" ][:num_examples].values return most_exemplary_1, most_exemplary_0 def collect_least_exemplary_1(num_examples, allmerged_select): # takes allmerged_select to filter for those that are barely considered class1 # returns examples that are barely class 1 but should be and also the falsely considered class ones # these types of functions are useful for analyzing false positives and the confusions that the model is having definition_1 = ["benign", "normal"] # those that are suppose to 1 but barely are 1 barely_exemplary_1_truedf = allmerged_select[ (allmerged_select["predicted_val"] == 1) & (allmerged_select["cancer_status"].isin(definition_1)) ].sort_values("predictions", ascending=True) barely_exemplary_1_true = barely_exemplary_1_truedf["rawfilenames"][ :num_examples ].values # the lowest pred vals right above cutoff and near false positive point that are not 1 and should be 0 barely_exemplary_1_falsedf = allmerged_select[ (allmerged_select["predicted_val"] == 1) & (~allmerged_select["cancer_status"].isin(definition_1)) ].sort_values("predictions", ascending=True) barely_exemplary_1_false = barely_exemplary_1_falsedf["rawfilenames"][ :num_examples ].values return barely_exemplary_1_true, barely_exemplary_1_false def collect_least_exemplary_0(num_examples, allmerged_select): definition_0 = ["cancer"] barely_exemplary_0_truedf = allmerged_select[ (allmerged_select["predicted_val"] == 0) & (allmerged_select["cancer_status"].isin(definition_0)) ].sort_values("predictions", ascending=False) barely_exemplary_0_true = barely_exemplary_0_truedf["rawfilenames"][ :num_examples ].values # those that are barely class 0 that should be class 1 barely_exemplary_0_falsedf = allmerged_select[ (allmerged_select["predicted_val"] == 0) & (~allmerged_select["cancer_status"].isin(definition_0)) ].sort_values("predictions", ascending=False) barely_exemplary_0_false = barely_exemplary_0_falsedf["rawfilenames"][ :num_examples ].values return barely_exemplary_0_true, barely_exemplary_0_false def download_fileslist(dl_prefix_pathlocation, download_list, bucket_name): # download_list must have full file path s3 = boto3.resource("s3") s3_client = boto3.client("s3") bucket = s3.Bucket(bucket_name) for dl_file in download_fileslist: bucket.download_file(dl_file, dl_prefix_pathlocation + dl_file.split("/")[-1]) def main(): case_desc = pd.read_csv("case_descriptions(2).csv") preds = pd.read_csv("predictions.csv") dl_prefix_pathlocation = "/breast_cancer_detection/" url = "s3://cornell-mammogram-images/" # => ['s3:', '', 'sagemakerbucketname', 'data', ... url_parts = url.split("/") bucket_name = url_parts[2] bucket_filesdf = get_bucketfilenames(bucket_name) bucket_filesdf = parse_bucketfilesdf(bucket_filesdf) allmerged = merge_restructure_df(case_desc, preds, bucket_filesdf) allmerged_select = allmerged[ [ "rawfilenames", "filename", "casenum", "predictions", "predicted_val", "centered_predictions", "label_val", "label", "case_id", "age", "density", "cancer_status", "left_abnormality", "right_abnormality", ] ].drop_duplicates() num_examples = 20 most_exemplary_1, most_exemplary_0 = collect_most_exemplary_images( num_examples, allmerged ) barely_exemplary_1_true, barely_exemplary_1_false = collect_least_exemplary_1( num_examples, allmerged_select ) barely_exemplary_0_true, barely_exemplary_0_false = collect_least_exemplary_0( num_examples, allmerged_select ) download_fileslist(dl_prefix_pathlocation, barely_exemplary_0_true, bucket_name)
true
5037f4ca29ee8e6ccd7adeddf596325bddcc92d8
Python
YWaller/Sample
/BinpackingHeuristic.py
UTF-8
1,819
3.421875
3
[]
no_license
# -*- coding: utf-8 -*- def binpack(articles,bin_cap): #This is a heuristic to solve the binpacking problem; it found the optimal answer every time in testing while operating many times faster. bin_contents = [] # use this list document the article ids for the contents of # each bin, the contents of each is to be listed in a sub-list #I use the below to control loop flow. If you wrap nested loops in this, you can break into an outer loop without #continuing on in the lower one. You can use break for this as well, but this is a more comprehensive loop. class Continueloop(Exception): pass continue_i = Continueloop() maxBins = len(articles) initialList = [] #make an initial list that's as big as we could possibly need for i in range(maxBins): initialList.append([]) i = 0 sortedArticles = sorted(articles, key=articles.get, reverse=True) #sort the items by their size #print sortedArticles load = 0 for item in sortedArticles: try: for i in initialList: load = sum(list(map(lambda x: articles[x],i))) #uses list and map to find out the value of the current bin if articles[item] + load <= bin_cap: #if the article's weight and the bin's load are less than the bin cap initialList[initialList.index(i)].append(item) #Put it in raise continue_i #exit the loop except Continueloop: continue #puts us on the next item in articles, without doing list copying and such nonsense #remove all the empty lists (bins) in initialList that weren't needed list2 = [x for x in initialList if x != []] bin_contents = list2 return bin_contents
true
42e6ba558bed3582a2d9df6cb3c7a2c8ac201782
Python
ComputationalAstrologer/Optics
/ArrivalTimes.py
UTF-8
1,882
3.40625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 18 15:57:40 2021 @author: Richard Frazin This plots some histograms """ import numpy as np import matplotlib.pyplot as plt #create a histogram corresponding to two exponential decay rates #the probability of waiting a time t given rate r is r*exp(-rt). #r could also be the intensity of photon source r1 = 0.5 # rate of process 1 (proportional to intensity) r2 = 5. # rate of process 2 ttime1 = 1.e5 # time spent at rate 1 ttime2 = 2.e5 # time spent at rate 2 timelist = [] total_time = 0. while total_time < ttime2: dt = np.random.exponential(scale=1/r2, size=1) timelist.append(dt) total_time += dt timelist.pop() # remove last event since it went past ttime2 total_time = 0. while total_time < ttime1: dt = np.random.exponential(scale=1/r1, size=1) timelist.append(dt) total_time += dt timelist.pop() # remove last event since it went past ttime1 timelist = np.array(timelist) #set up histogram bins nbins = 300 tmax = 10./np.min([r1,r2]) # gives a probability of 4.5e-5 for the slow one edges = np.linspace(0, tmax, 1 + nbins) centers = np.linspace(edges[1]/2, (edges[-1] + edges[-2])/2 , nbins) binwidth = edges[1] - edges[0] hist = np.histogram(timelist,bins=edges, density=False) #now, make a theoretical pdf based on the two exponentials #p(t) = p(t|r1)p(r1) + p(t|r2)*p(r2) #note that p(r1) is NOT the fraction of time the system spends at r1. #Rather it is the probability that events occur at a time when the rate #is r1. Since there are more events when rates are higher, p(r1) is #proportional to r1 pr1 = r1*ttime1/(r1*ttime1 + r2*ttime2) pr2 = 1. - pr1 ptr1 = r1*np.exp(-r1*centers) ptr2 = r2*np.exp(-r2*centers) pt = ptr1*pr1 + ptr2*pr2 plt.figure() plt.semilogy(centers, hist[0]/timelist.size, 'bo-', centers, pt*binwidth,'rx:');
true
fafb4c304c3454d7b360fb6b627a09e323272a72
Python
BrendenBe1/Business-Analytics
/createDashboard.py
UTF-8
2,097
3.15625
3
[]
no_license
import requests, json class createDashboard: """ Combines graphs from Plotly API into a single webpage using Dashboardly """ def __init__(self, graph_URLs, date_range): """ Generate needed data and create dashboard :param graph_URLs: list of strings :param date_range: list of two strings :return: string of URL """ self.date_range = date_range self.graph_URLs = graph_URLs # Reformat URLs into a list of dictionaries for the API self.rows_list = [] for URL in graph_URLs: self.rows_list.append([{"plot_url" : URL}]) self.banner_title = "" self.create_banner() self.generate() # Convert "date" to "date (time_type)" def create_banner(self): """ Combine two dates into a single string :return: string """ self.banner_title += self.date_range[0] self.banner_title += " to " self.banner_title += self.date_range[1] def generate(self): """ Calls API to generate a link to the dashboard :return: string """ dashboard_json = { "rows": self.rows_list, "banner": { "visible": True, "backgroundcolor": "#3d4a57", "textcolor": "white", "title": self.banner_title, "links": self.graph_URLs }, "requireauth": False, "auth": { "username": "Business Analytics", "passphrase": "" } } response = requests.post('https://dashboards.ly/publish', data={'dashboard': json.dumps(dashboard_json)}, headers={'content-type': 'application/x-www-form-urlencoded'}) response.raise_for_status() dashboard_url = response.json()['url'] print('Dashboard URL: https://dashboards.ly{}'.format(dashboard_url))
true
2c085436281c06b7b87d419bc8786edc9362333d
Python
VasudhaLalit/Log-Analysis
/loganalysisdb.py
UTF-8
242
2.578125
3
[]
no_license
import psycopg2 DBName = 'news' def db_connect(query): dbconn = psycopg2.connect(database=DBName) cursor = dbconn.cursor() cursor.execute(query) results = cursor.fetchall() dbconn.close() return results
true
365bb3bf6cbe3479ca40f9e8dcbd34c53c169ed3
Python
guidumasperes/MC558
/Prim/prim.py
UTF-8
1,995
3.28125
3
[]
no_license
from collections import defaultdict #Classes to contruct and manipulate Graphs class Graph: def __init__(self): self.graph = defaultdict(list) # function to add an edge to graph and weight dict def addEdge(self,u,v,w,val): self.graph[u].append(v) w[(u,v)] = val class Vertex: def __init__(self): self.name = None self.p = None self.key = None def fake_heapify(G): Q = {} Qaux = G.graph Qaux = [key for key in Qaux.keys()] for key in Qaux: Q[key] = key.key return Q def fake_extract_min(Q): u = min(Q, key=Q.get) #extract-min of heap Q.pop(u) return u def fake_decrease_key(Q,v): Q[v] = v.key def mst_prim(G,w,r): for u in G.graph: u.key = float('inf') u.p = None r.key = 0 A = [] #to return MST Q = fake_heapify(G) while len(Q) != 0: u = fake_extract_min(Q) #extract-min of heap if u.p != None: #insert in A A.append((u.p,u)) for v in G.graph[u]: if v in Q and w[(u,v)] < v.key: v.p = u v.key = w[(u,v)] fake_decrease_key(Q,v) #update heap return A #main a,b,c,d,e,f,g,h,i = Vertex(),Vertex(),Vertex(),Vertex(),Vertex(),Vertex(),Vertex(),Vertex(),Vertex() a.name = 'a' b.name = 'b' c.name = 'c' d.name = 'd' e.name = 'e' f.name = 'f' g.name = 'g' h.name = 'h' i.name = 'i' G = Graph() w = {} G.addEdge(a, b, w, 4) G.addEdge(a, h, w, 8) G.addEdge(b, a, w, 4) G.addEdge(b, h, w, 11) G.addEdge(b, c, w, 8) G.addEdge(c, b, w, 8) G.addEdge(c, i, w, 2) G.addEdge(c, f, w, 4) G.addEdge(c, d, w, 7) G.addEdge(d, c, w, 7) G.addEdge(d, e, w, 9) G.addEdge(e, d, w, 9) G.addEdge(e, f, w, 10) G.addEdge(f, e, w, 10) G.addEdge(f, d, w, 14) G.addEdge(f, c, w, 4) G.addEdge(f, g, w, 2) G.addEdge(g, f, w, 2) G.addEdge(g, i, w, 6) G.addEdge(g, h, w, 1) G.addEdge(h, g, w, 1) G.addEdge(h, b, w, 11) G.addEdge(h, a, w, 8) G.addEdge(i, c, w, 2) G.addEdge(i, g, w, 6) G.addEdge(i, h, w, 7) mst = mst_prim(G,w,g) for e in mst: print('(' + e[0].name + ',' + e[1].name + ')')
true
01bc2e8a65b2a059be25d78d63518d859a725bd6
Python
SHIQIHOU/Training
/ARIMA时间序列预测/log_diff_shift_ARMA.py
UTF-8
2,592
2.625
3
[]
no_license
import pandas as pd import numpy as np from scipy import stats import matplotlib.pyplot as plt import tushare as ts import datetime from statsmodels.graphics.api import qqplot from statsmodels.tsa.stattools import adfuller from statsmodels.graphics.tsaplots import plot_acf, plot_pacf from statsmodels.tsa.arima_model import ARMA import statsmodels.api as sm import statsmodels.tsa.stattools as st from itertools import product data=pd.read_excel('无线市场空间data.xlsx') data=data['亚太整体规模'] data=data[8:] data=pd.Series(data) data.index = pd.Index(pd.date_range(start = '2001-1-1', end = '2019-12-1', freq = 'QS-JAN')) data_log=np.log(data) data_log_diff1=data_log.diff(1) data_log_diff1_new=data_log_diff1.dropna(inplace=True) data_log_diff1_4=data_log_diff1-data_log_diff1.shift(4) data_log_diff1_4_new=data_log_diff1_4.dropna() fig=plt.figure(figsize=(12,8)) ax=fig.add_subplot(111) data_log_diff1_4_new.plot(ax=ax) plot_acf(data_log_diff1_4_new, lags=30) plot_pacf(data_log_diff1_4_new, lags=30) plt.show() p=range(2,7) q=range(0,7) parameters=product(p,q) parameters_list=list(parameters) def optimizeARMA(parameters_list): results = [] best_aic = float("inf") for param in parameters_list: try: model = ARMA(data_log_diff1_4_new, (param[0], param[1])).fit() except: continue aic = model.aic if aic < best_aic: best_model = model best_aic = aic best_param = param results.append([param, model.aic]) result_table = pd.DataFrame(results) result_table.columns = ['parameters', 'aic'] result_table = result_table.sort_values(by='aic', ascending=True).reset_index(drop=True) return result_table result_table = optimizeARMA(parameters_list) p, q = result_table.parameters[0] model20=ARMA(data_log_diff1_4_new, (p,q)).fit() resid = model20.resid fig = plt.figure(figsize=(6,6)) ax = fig.add_subplot(111) fig = qqplot(resid, line='q', ax=ax, fit=True) plt.show() predict_arma = model20.predict(start=0, end=100) data_log_diff1_recover_4 = predict_arma.add(data_log_diff1.shift(4)) data_log_recover_diff1 = data_log_diff1_recover_4.add(data_log.shift(1)) data_log_recover_diff1 = data_log_recover_diff1.dropna() predict_arma = np.power(np.e, data_log_recover_diff1) plt.figure(figsize=(24,8)) orig = plt.plot(data, color = 'blue', label = 'Original') predict = plt.plot(predict_arma, color = 'red', label = 'Predict') plt.legend(loc='best') plt.show()
true
c3fc5d9c5ffe10635bf369869068022b33311fc4
Python
PatPat95/Text-RPG-Sprint2
/progress.py
UTF-8
3,530
3.0625
3
[]
no_license
""" Helpful file to streamline saving and loading players' progress from the database """ import os import models from settings import db from game.player import Player, deconstruct_player # for this funciton work a list of users with most recent ones at the end must be sent def save_progress(userlist): """ Saves the user's progress to the database """ FLAG = "INSERT" USER = userlist[-1] all_character = [ character.character_name for character in db.session.query(models.character).all() ] all_userid = [ user_id.user_id for user_id in db.session.query(models.character).all() ] dict = {} for i in range(len(all_character)): dict[all_userid[i]] = all_character[i] USER = userlist[-1] email = db.session.query(models.username).filter_by(id=USER).first() key = email.id characterList = db.session.query(models.character).filter_by(user_id=key) player = Player() # needs to pick character by user choice for char in characterList: if char.character_name == "popo": player = char statslist = deconstruct_player(player) for x, y in dict.items(): if USER == x and statslist[0] == y: FLAG = "UPDATE" break else: FLAG = "INSERT" if FLAG == "INSERT": chara = models.character( user_id=USER, character_name=statslist[0], strength=statslist[1], dex=statslist[2], con=statslist[3], intel=statslist[4], cha=statslist[5], luck=statslist[6], max_health=statslist[7], health=statslist[8], max_mana=statslist[9], mana=statslist[10], money=statslist[11], checkpoint=statslist[12], gender=statslist[13], character_class=statslist[14], ) db.session.add(chara) db.session.commit() elif FLAG == "UPDATE": chara = ( db.session.query(models.character) .filter_by(user_id=USER, character_name=statslist[0]) .first() ) chara.strength = statslist[1] chara.dex = statslist[2] chara.con = statslist[3] chara.intel = statslist[4] chara.cha = statslist[5] chara.luck = statslist[6] chara.max_health = statslist[7] chara.health = statslist[8] chara.max_mana = statslist[9] chara.mana = statslist[10] chara.money = statslist[11] chara.checkpoint = statslist[12] chara.gender = statslist[13] chara.character_class = statslist[14] db.session.commit() else: print("weird error") # need to send list of users to use function, also this is currnetly incomplete def load_progress(userlist, char_name): """ Loads all characters from DB -> userlist is the list of most recent users -> Tries to match char_name with user from DB <- Returns a Player obj if found, otherwise returns None """ USER = userlist[-1] email = db.session.query(models.username).filter_by(id=USER).first() key = email.id characterList = db.session.query(models.character).filter_by(user_id=key) # gets all the character names tied to userID. Need to display all names and allowed use to select or create new player = None for char in characterList: if char.characterName == char_name: player = char return player
true
99ed95cf5ff91f5aa625fc920ef5e12159bbaf28
Python
andreserb/python
/ejercicio10.py
UTF-8
326
3.96875
4
[]
no_license
# -*- coding: utf-8 -*- #Escribir un programa que pida al usuario un número entero y #muestre por pantalla un triángulo rectángulo como el de más abajo. lista=[] a=int(input("Ingrese la altura del triángulo (entero positivo): ")) for i in range(1,a+1,2): lista.append(i) print(' '.join(map(str, lista[::-1])))
true
bc3a8dba5a754aeb411195ed0f07ea7163757746
Python
martinhoeller/wrdlr
/wrdlr.py
UTF-8
3,240
3.40625
3
[ "MIT" ]
permissive
#!/usr/bin/python import sys, getopt, os.path import fnmatch # SEQUENCE MATCHING # All words containing 'clo': "clo" # All words starting with 'clo': "clo*"" # All words ending with 'clo': "*clo" # All words starting with 'clo' and ending with 'rm': "clo*rm" # All words starting with 'clo', followed by any character and ending with 'h': "clo?h" def load_dictionary(file): file = open(file, "r") lines = file.readlines() return [line.strip() for line in lines] def matching_words(words, pattern, min_len = -1, max_len = -1, match_case = False): if (match_case == True): matches = [word for word in words if fnmatch.fnmatchcase(word, pattern)] else: lower_pattern = pattern.lower() matches = [word for word in words if fnmatch.fnmatch(word.lower(), lower_pattern)] if (max_len > -1): matches = [word for word in matches if len(word) <= max_len] if (min_len > -1): matches = [word for word in matches if len(word) >= min_len] return matches def print_words(words): for word in words: print word def test(): words = load_dictionary("dict_en.txt") print len(words), "words" print print "STARTING TESTS" print print "Words containing 'clor'" print_words(matching_words(words, "*clor*")) print "Words starting with 'clor'" print_words(matching_words(words, "clor*")) print "Words ending with 'clo'" print_words(matching_words(words, "*clo")) print "Words starting with 'clo' and ending with 'ing'" print_words(matching_words(words, "clo*ing")) print "All words starting with 'clo', followed by any character and ending with 'h'" print_words(matching_words(words, "clo?h")) print "All words with exactly 20 characters" print_words(matching_words(words, "*", 20, 20)) print "All words starting with 'u' and at least 20 characters" print_words(matching_words(words, "u*", 20)) print "All words ending with 'alt' and max 5 characters" print_words(matching_words(words, "*alt", -1, 5)) def print_help(): print "Usage:" print " wrdlr.py --dict <dictfile> --pattern <pattern> [--minlen <minlen>] [--maxlen <maxlen>] [--matchcase]" print print "Example:" print " ./wrdlr.py --dict /usr/share/dict/words --pattern col* --minlen 5 --maxlen 7" ################ # Main Program # ################ ERROR_WRONG_ARGUMENTS = 1 ERROR_DICTIONARY_FILE = 2 def main(argv): dictfile = "" pattern = "" minlen = -1 maxlen = -1 matchcase = False try: opts, args = getopt.getopt(argv,"",["dict=","pattern=", "minlen=", "maxlen=", "matchcase"]) except getopt.GetoptError: print_help() sys.exit(ERROR_WRONG_ARGUMENTS) for opt, arg in opts: if opt in ("--dict"): dictfile = arg elif opt in ("--pattern"): pattern = arg elif opt in ("--minlen"): minlen = int(arg) elif opt in ("--maxlen"): maxlen = int(arg) elif opt in ("--matchcase"): matchcase = True if len(dictfile) == 0 or len(pattern) == 0: print_help() sys.exit(ERROR_WRONG_ARGUMENTS) if not os.path.isfile(dictfile): print "ERROR: invalid dictionary file" sys.exit(ERROR_DICTIONARY_FILE) words = load_dictionary(dictfile) matches = matching_words(words, pattern, minlen, maxlen, matchcase) print_words(matches) sys.exit(0) if __name__ == "__main__": main(sys.argv[1:]) #test()
true
2dae79a0d2cf6d2399924b53861a35b2b0644be9
Python
ArturtheQA/classRepo
/day5/hw1.py
UTF-8
3,810
2.703125
3
[]
no_license
states = { "California": 39557045, "Texas": 28701845, "Florida": 21299325, "New York": 19542209, "Pennsylvania": 12807060, "Illinois": 12741080, "Ohio": 11689442, "Georgia": 10519475, "North Carolina": 10383620, "Michigan": 9998915, "New Jersey": 9032873, "Virginia": 8517685, "Washington": 7535591, "Arizona": 7171646, "Massachusetts": 6902149, "Tennessee": 6770010, "Indiana": 6691878, "Missouri": 6126452, "Maryland": 6042718, "Wisconsin": 5813568, "Colorado": 5695564, "Minnesota": 5611179, "South Carolina": 5084127, "Alabama": 4887871, "Louisiana": 4659978, "Kentucky": 4468402, "Oregon": 4190713, "Oklahoma": 3943079, "Connecticut": 3572665, "Puerto Rico": 3195153, "Utah": 3161105, "Iowa": 3156145, "Nevada": 3034392, "Arkansas": 3013825, "Mississippi": 2986530, "Kansas": 2911505, "New Mexico": 2095428, "Nebraska": 1929268, "West Virginia": 1805832, "Idaho": 1754208, "Hawaii": 1420491, "New Hampshire": 1356458, "Maine": 1338404, "Montana": 1062305, "Rhode Island": 1057315, "Delaware": 967171, "South Dakota": 882235, " North Dakota": 760077, "Alaska": 737438, "District of Columbia": 702455, "Vermont": 626299, "Wyoming": 577737, "Guam": 165718, "U.S. Virgin Islands": 104914, "American Samoa": 55641, "Northern Mariana Islands": 55194, "Wake Island": 100, "Palmyra Atoll": 20, "Midway Atoll": 40, "Johnston Atoll": 0, "Baker Island": 0, "Howland Island": 0, "Jarvis Island": 0, "Kingman Reef": 0, "Navassa Island": 0 } def hw1_1(): i = 0 while i != 20+1: print(i+1) i = i+1 def hw1_2(): i = 0 while i in range(0, 20): print(i+1) i = i+1 def hw2_1(): i = 0 a = int(input("put number")) while i != a: print(a-i) i = i+1 def hw3(): i = 0 a = int(input("put number")) while i < (a+1): print(i*i) i = i+1 def hw4(): i = 2 dinamicvalue = 2 result = 0 while result < 65536+1: result = i**dinamicvalue print(result) i = i+1 def hw5_1(): a = input("please eneter some word") print(len(a)) def hw5_2(): i = 0 a = input("please enter some word") while i != len(a)+1: i = i+1 print(i) def hw6_1(): i = 0 acount = 0 a = input("please enter some word") while i != len(a)+1: i = i+1 for letter in a: if letter == "a": acount = acount+1 break print(i-1, acount-1) # def hw7_1(): # i = {1: "one", 2: 'two', 3: 'three'} # u = int(input("please place the #")) # print(i[u]) def hw9(states): # counter=0 bigOneName='' bigOnePopulation=0 top5=[] time=0 times=5 while time != times: # while counter <len(states): for state in states: if states[state] > bigOnePopulation: bigOnePopulation=states[state] bigOneName=state # counter=counter+1 states.pop(bigOneName) top5.append(bigOneName) bigOneName='' bigOnePopulation=0 time=time+1 print(top5) # def hw5_2(): # i = 0 # a = input("please enter some word") # while i != len(a)+1: # i = i+1 # print(i-1) # # hw5_2() # hw9(states) # def is_leap(year): # leap = False # # Write your logic here # if (year % 4 == 0 and year % 100 != 0)or (year % 100 == 0 and year % 400 == 0): # leap = True # elif year % 100 == 0: # leap = False # print(leap) # is_leap(2100) hw9(states)
true
3646585194f198668b6b8bafc014ebe1e5425b52
Python
HarishKolla533/Example
/Daa_Project-master/Source/pyhton code/practise1.py
UTF-8
2,414
3.09375
3
[]
no_license
import sys import heapq from graph import Graph from vertex import Vertex class emergency_vehcile(object): dict={} lst=[] lst1=[] dict1={} def __init__(self,type,zipcode,availability): self.type=type self.zipcode=zipcode self.availability=availability def get_vehcile__details(self): return self.availability +"no of vehciles of "+ self.type + "type is available at" + self.zipcode for num in range(self.availability): dict[zipcode]=lst.append(self.type) for num in range(self.availability): dict[zipcode]=lst1.append(self.availability) class request(object): def __init__(self,type,zipcode): self.type=type self.zipcode=zipcode """creating dictionary to store emergency vechiles using zipcode""" def dijkstra(aGraph, start, target): print '''Dijkstra's shortest path''' start.set_distance(0) unvisited_queue = [(v.get_distance(), v) for v in aGraph] heapq.heapify(unvisited_queue) while len(unvisited_queue): uv = heapq.heappop(unvisited_queue) current = uv[1] current.set_visited() for next in current.adjacent: if next.visited: continue new_dist = current.get_distance() + current.get_weight(next) if new_dist < next.get_distance(): next.set_distance(new_dist) next.set_previous(current) print 'updated : current = %s next = %s new_dist = %s' \ % (current.get_id(), next.get_id(), next.get_distance()) else: print 'not updated : current = %s next = %s new_dist = %s' \ % (current.get_id(), next.get_id(), next.get_distance()) while len(unvisited_queue): heapq.heappop(unvisited_queue) unvisited_queue = [(v.get_distance(), v) for v in aGraph if not v.visited] heapq.heapify(unvisited_queue) if __name__ == '__main__': g = Graph() g.add_vertex('a') g.add_vertex('b') g.add_vertex('c') g.add_vertex('d') g.add_vertex('e') g.add_vertex('f') g.add_edge('a', 'b', 7) g.add_edge('a', 'c', 9) g.add_edge('a', 'f', 14) g.add_edge('b', 'c', 10) g.add_edge('b', 'd', 15) g.add_edge('c', 'd', 11) g.add_edge('c', 'f', 2) g.add_edge('d', 'e', 6) g.add_edge('e', 'f', 9)
true
714d4114b45d451958bc8ef8f8d645499cd5906d
Python
thesprockee/mitmproxy
/mitmproxy/utils.py
UTF-8
2,493
2.828125
3
[ "MIT" ]
permissive
from __future__ import absolute_import, print_function, division import datetime import json import time import netlib.utils def timestamp(): """ Returns a serializable UTC timestamp. """ return time.time() def format_timestamp(s): s = time.localtime(s) d = datetime.datetime.fromtimestamp(time.mktime(s)) return d.strftime("%Y-%m-%d %H:%M:%S") def format_timestamp_with_milli(s): d = datetime.datetime.fromtimestamp(s) return d.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] def isBin(s): """ Does this string have any non-ASCII characters? """ for i in s: i = ord(i) if i < 9 or 13 < i < 32 or 126 < i: return True return False def isMostlyBin(s): s = s[:100] return sum(isBin(ch) for ch in s) / len(s) > 0.3 def isXML(s): for i in s: if i in "\n \t": continue elif i == "<": return True else: return False def pretty_json(s): try: p = json.loads(s) except ValueError: return None return json.dumps(p, sort_keys=True, indent=4) pkg_data = netlib.utils.Data(__name__) class LRUCache: """ A simple LRU cache for generated values. """ def __init__(self, size=100): self.size = size self.cache = {} self.cacheList = [] def get(self, gen, *args): """ gen: A (presumably expensive) generator function. The identity of gen is NOT taken into account by the cache. *args: A list of immutable arguments, used to establish identiy by *the cache, and passed to gen to generate values. """ if args in self.cache: self.cacheList.remove(args) self.cacheList.insert(0, args) return self.cache[args] else: ret = gen(*args) self.cacheList.insert(0, args) self.cache[args] = ret if len(self.cacheList) > self.size: d = self.cacheList.pop() self.cache.pop(d) return ret def clean_hanging_newline(t): """ Many editors will silently add a newline to the final line of a document (I'm looking at you, Vim). This function fixes this common problem at the risk of removing a hanging newline in the rare cases where the user actually intends it. """ if t and t[-1] == "\n": return t[:-1] return t
true
3f525de556ccb0725a70ddc01cd41fb6832daf88
Python
LucasSoftware12/EjerciciosPy
/ejercicio2.py
UTF-8
194
3
3
[]
no_license
# Alumno Lucas Medina # Contraseña incorrecta intentos = 0 while intentos < 5: print("Intento fallido:", intentos, "Contraseña incorrecta") intentos = intentos+1 print("Cuenta Bloqueada")
true
fe74a2d1d555d3727d210d2bfe4521f7da5e9b7a
Python
fisherab/r-gma
/server/src/scripts/libexec/rgma-fetch-vdbs.py
UTF-8
4,204
2.671875
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
#!/usr/bin/env python # This utility will fetch vdb xml files from given URLs. # The URLs are extracted from all vdb_url files found in # "$RGMA_HOME/etc/rgma-server/vdb and the downloaded xml # "files are placed in the directory $RGMA_HOME/etc/rgma-server/vdb. # "The prefix of the vdb_url file name must match the prefix of the # "xml file name, these prefixes are the name of the vdb import os, sys, re, socket, urlparse, httplib, getopt, stat, glob, time def get_xml_file(url, http_proxy): data = "" returnCode = 0 conn = None socket.setdefaulttimeout(60) try: if http_proxy: hostPortUrl = http_proxy else: hostPortUrl = url hostPort = urlparse.urlparse(hostPortUrl)[1] conn = httplib.HTTPConnection(hostPort) headers = {"Accept": "*/*"} conn.request("GET", url, None, headers) response = conn.getresponse() if response.status != 200: returnCode = response.status data = "ERROR: " + response.reason else: data = response.read() except: data = "ERROR: " + url + " " + str(sys.exc_info()[0]) if http_proxy: data = data + " proxy was " + http_proxy returnCode = 1 if conn: conn.close() return returnCode, data; def now(): return time.strftime("%Y-%m-%d %H:%M:%S") def main(): rgma_home = sys.argv[1] try: http_proxy = os.environ['http_proxy'] except KeyError: http_proxy = None xml_file_path = os.path.join(rgma_home, 'var', 'rgma-server', 'vdb') for filename in glob.glob(os.path.join(rgma_home, 'etc', 'rgma-server', 'vdb', "*")): if filename.endswith("~"): continue if not filename.endswith(".vdb_url"): print >> sys.stderr, now(), "Unexpected file found", filename continue url_file = open(filename, "r") lines = url_file.readlines() url_file.close() found = False for line in lines: line = line.strip() if (re.search("^http", line) != None) & (re.search("\.xml", line) != None): if found: print >> sys.stderr, now(), filename, "has bad contents - only one line per file is expected" continue found = True head, tail = os.path.split(filename) vdb_name = tail[:-8] url = line path = urlparse.urlparse(url)[2] head, tail = os.path.split(path) vdb_name2 = tail[:-4] if vdb_name != vdb_name2: print >>sys.stderr, now(), "Name of VDB '" + vdb_name + "' extracted from the file name " + filename \ + " does not match the name of VDB '" + vdb_name2 + "' extracted from the URL " + url continue returncode, xml_data = get_xml_file(url, http_proxy) filename = os.path.join(xml_file_path, vdb_name + ".xml") if returncode == 0: # See if anything has changed changed = not os.path.isfile(filename) if not changed: f = open(filename) old_data = f.read() f.close() changed = old_data != xml_data if changed: xml_file = open(filename, "w") xml_file.write(xml_data) xml_file.close() os.chmod(filename, 0644) print now(), filename, "has been written" elif returncode == 404: os.remove(filename) print >>sys.stderr, now(), filename, "has been removed" else: print >>sys.stderr, now(), "problem getting xml file", xml_data if not found: print >> sys.stderr, now(), filename, "has no recognised content" main()
true
ce1bddddcc385e74a9d8220b99142d1dd663950f
Python
eggplantbren/CVTModes
/spectra.py
UTF-8
895
2.609375
3
[]
no_license
import matplotlib.pyplot as plt import numpy as np spectrum = np.loadtxt("overdrive-eh.txt", skiprows=1) plt.plot(spectrum[:,0], spectrum[:,1]+100, label="Overdrive EH") spectrum = np.loadtxt("edge-eh.txt", skiprows=1) plt.plot(spectrum[:,0], spectrum[:,1], label="Edge EH") spectrum = np.loadtxt("edge-a.txt", skiprows=1) plt.plot(spectrum[:,0], spectrum[:,1], label="Edge A") spectrum = np.loadtxt("curbing-uh.txt", skiprows=1) plt.plot(spectrum[:,0], spectrum[:,1]-100, label="Curbing UH") spectrum = np.loadtxt("curbing-oo.txt", skiprows=1) plt.plot(spectrum[:,0], spectrum[:,1]-100, label="Curbing OO") spectrum = np.loadtxt("neutral-ee.txt", skiprows=1) plt.plot(spectrum[:,0], spectrum[:,1]-200, label="Neutral EE") spectrum = np.loadtxt("neutral-oo.txt", skiprows=1) plt.plot(spectrum[:,0], spectrum[:,1]-200, label="Neutral OO") plt.legend() plt.xlim([0.0, 5000.0]) plt.show()
true
3027ad7d4e78e6d7813542312300367dbeffdb7f
Python
renjieliu/leetcode
/1500_1999/1582.py
UTF-8
642
2.796875
3
[]
no_license
class Solution: def numSpecial(self, mat: 'List[List[int]]') -> int: r_1 = {} c_1 = {} for r in range(len(mat)): for c in range(len(mat[0])): if mat[r][c] == 1: if r not in r_1: r_1[r] = 0 r_1[r] += 1 if c not in c_1: c_1[c] = 0 c_1[c] += 1 output = 0 for r in range(len(mat)): for c in range(len(mat[0])): if mat[r][c] == 1 and r_1[r] == 1 and c_1[c] == 1: output += 1 return output
true
7fcbae0318d10be6d5e8a8db900b4df393a11b13
Python
asitP9/50-Plots-To-Practice
/countsPlot.py
UTF-8
2,103
3.71875
4
[]
no_license
import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns import warnings; warnings.filterwarnings(action="once") # PLOT 5: Counts Plot # Useful for: # Draw a scatterplot where one variable is categorical. # In this plot we calculate the size of overlapping points in each category and for each y. # This way, the bigger the bubble the more concentration we have in that region. # More info: # https://seaborn.pydata.org/generated/seaborn.stripplot.html class countsPlot: def countsPlot(self): path="datasets/mpg_ggplot2.csv" df=pd.read_csv(path) # we need to make a groupby by variables of interest gb_df=df.groupby(["cty", "hwy"]).size().reset_index(name="counts") # sort the values gb_df.sort_values(["cty", "hwy", "counts"], ascending=True, inplace=True) # create a color for each group. # there are several way os doing, you can also use this line: # colors = [plt.cm.gist_earth(i/float(len(gb_df["cty"].unique()))) for i in range(len(gb_df["cty"].unique()))] colors={i:np.random.random(3,) for i in sorted(list(gb_df["cty"].unique()))} # instanciate the figure fig = plt.figure(figsize=(10, 5)) ax = fig.add_subplot() # iterate over each category and plot the data. This way, every group has it's own color and sizwe. # instantiate the figure for i in sorted(list(gb_df["cty"].unique())): # get x and y values for each group x_values = gb_df[gb_df['cty'] == i]["cty"] y_values = gb_df[gb_df['cty'] == i]["hwy"] print("my y values ", gb_df[gb_df['cty'] == i]["hwy"]) # extract the size of each group to plot size = gb_df[gb_df["cty"] == i]["counts"] # extract the color for each group and covert it from rgb to hex color = mpl.colors.to_hex(colors[i]) ax.scatter(x_values, y_values, s=size * 10, c=color) # prettify the plot ax.set_title("count_plot") plt.show()
true
78a7cd6a23d638f0b2f0e5e593108570c8c1735f
Python
Python3pkg/Caesar-Cipher
/tests/test_caesarcipher.py
UTF-8
11,915
2.84375
3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
import unittest from caesarcipher import CaesarCipher from caesarcipher import CaesarCipherError class CaesarCipherEncodeTest(unittest.TestCase): def test_encode_with_known_offset(self): message = "Twilio" test_cipher = CaesarCipher(message, encode=True, offset=1) self.assertEquals(test_cipher.encoded, "Uxjmjp") def test_encode_long_phrase_with_known_offset(self): message = "The quick brown fox jumps over the lazy dog." test_cipher = CaesarCipher(message, encode=True, offset=7) self.assertEquals(test_cipher.encoded, "Aol xbpjr iyvdu mve qbtwz vcly aol shgf kvn.") def test_encode_with_mirror_offset(self): message = "The quick brown fox jumps over the lazy dog." test_cipher = CaesarCipher(message, encode=True, offset=26) self.assertEquals(test_cipher.encoded, "The quick brown fox jumps over the lazy dog.") def test_encode_with_offset_greater_than_alphabet_length(self): message = "The quick brown fox jumps over the lazy dog." test_cipher = CaesarCipher(message, encode=True, offset=28) self.assertEquals(test_cipher.encoded, "Vjg swkem dtqyp hqz lworu qxgt vjg ncba fqi.") def test_encode_with_very_large_offset(self): message = "The quick brown fox jumps over the lazy dog." test_cipher = CaesarCipher(message, encode=True, offset=10008) self.assertEquals(test_cipher.encoded, "Rfc osgai zpmul dmv hsknq mtcp rfc jyxw bme.") def test_encode_decode_consistent(self): message = "The quick brown fox jumps over the lazy dog." setup_cipher = CaesarCipher(message, encode=True, offset=14) encoded_message = setup_cipher.encoded test_cipher = CaesarCipher(encoded_message, decode=True, offset=14) self.assertEquals(message, test_cipher.decoded) def test_encode_with_arbitrary_alphabet(self): message = "The quick brown fox jumps over the lazy dog." alphabet = 'ueyplkizjgncdbqshoaxmrwftv' test_cipher = CaesarCipher(message, offset=7, alphabet=alphabet) self.assertEquals('Kfj rzbad mytpo ltu szenw tijy kfj cvqg xth.', test_cipher.encoded) class CaesarCipherDecodeTest(unittest.TestCase): def test_decode_with_known_offset(self): message = "UXJMJP" test_cipher = CaesarCipher(message, encode=True, offset=1) self.assertEquals(test_cipher.decoded, "TWILIO") def test_decode_long_phrase_with_known_offset(self): message = "AOL XBPJR IYVDU MVE QBTWZ VCLY AOL SHGF KVN." test_cipher = CaesarCipher(message, decode=True, offset=7) self.assertEquals(test_cipher.decoded, "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.") def test_decode_with_offset_greater_than_alphabet_length(self): message = "VJG SWKEM DTQYP HQZ LWORU QXGT VJG NCBA FQI." test_cipher = CaesarCipher(message, decode=True, offset=28) self.assertEquals(test_cipher.decoded, "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.") def test_decode_with_very_large_offset(self): message = "RFC OSGAI ZPMUL DMV HSKNQ MTCP RFC JYXW BME." test_cipher = CaesarCipher(message, decode=True, offset=10008) self.assertEquals(test_cipher.decoded, "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.") def test_encode_decode_persistence(self): message = "The quick brown fox jumps over the lazy dog." test_cipher = CaesarCipher(message, encode=True, offset=14) test_cipher.encoded self.assertEquals(message, test_cipher.decoded) def test_decode_with_arbitrary_alphabet(self): message = "Kfj rzbad mytpo ltu szenw tijy kfj cvqg xth." alphabet = 'ueyplkizjgncdbqshoaxmrwftv' test_cipher = CaesarCipher(message, offset=7, alphabet=alphabet) self.assertEquals('The quick brown fox jumps over the lazy dog.', test_cipher.decoded) class CaesarCipherRegressionTest(unittest.TestCase): def test_all_offsets(self): message = "The quick brown fox jumps over the lazy dog." for i in range(0, 100): test_cipher = CaesarCipher(message, encode=True, offset=i) test_cipher.encoded self.assertEquals(message, test_cipher.decoded) class CaesarCipherErrorTest(unittest.TestCase): def test_caesar_cipher_error(self): def raiseCaesarCipherError(): raise CaesarCipherError("This test is bullshit to hit 100%" " coverage.") self.assertRaises(CaesarCipherError, raiseCaesarCipherError) class CaesarCipherCrackTest(unittest.TestCase): def test_calculate_entropy_zero_offset(self): message = "The quick brown fox jumps over the lazy dog." test_cipher = CaesarCipher(message, crack=True) confirmed_entropy_value = 179.14217305030957 test_entropy_value = test_cipher.calculate_entropy(message) self.assertEquals(confirmed_entropy_value, test_entropy_value) def test_crack(self): ciphertext = "Rfc osgai zpmul dmv hsknq mtcp rfc jyxw bme." plaintext = "The quick brown fox jumps over the lazy dog." test_crack = CaesarCipher(ciphertext, crack=True) self.assertEquals(plaintext, test_crack.cracked) def test_crack_one_word(self): ciphertext = "Yxo" plaintext = "One" test_crack = CaesarCipher(ciphertext, crack=True) self.assertEquals(plaintext, test_crack.cracked) def test_crack_difficult_word(self): message = "A quixotic issue to test." test_cipher = CaesarCipher(message).encoded cracked_text = CaesarCipher(test_cipher).cracked self.assertEquals(message, cracked_text) class CaesarCipherCrackRegressionTest(unittest.TestCase): def test_lots_of_cracks(self): plaintexts = [ "London calling to the faraway towns", "Now war is declared and battle come down", "London calling to the underworld", "Come out of the cupboard, you boys and girls", "London calling, now don't look to us", "Phony Beatlemania has bitten the dust", "London calling, see we ain't got no swing", "'Cept for the ring of that truncheon thing", "The ice age is coming, the sun is zooming in", "Meltdown expected, the wheat is growin' thin", "Engines stop running, but I have no fear", "Cause London is drowning, and I, I live by the river", "London calling to the imitation zone", "Forget it, brother, you can go it alone", "London calling to the zombies of death", "Quit holding out and draw another breath", "London calling and I don't want to shout", "But when we were talking I saw you nodding out", "London calling, see we ain't got no high", "Except for that one with the yellowy eye", "Now get this", "London calling, yes, I was there, too", "An' you know what they said? Well, some of it was true!", "London calling at the top of the dial", "And after all this, won't you give me a smile?", "I never felt so much a' like a'like a'like", "When they kick at your front door", "How you gonna come?", "With your hands on your head", "Or on the trigger of your gun", "When the law break in", "How you gonna go?", "Shot down on the pavement", "Or waiting on death row", "You can crush us", "You can bruise us", "But you'll have to answer to", "Oh, the guns of Brixton", "The money feels good", "And your life you like it well", "But surely your time will come", "As in heaven, as in hell", "You see, he feels like Ivan", "Born under the Brixton sun", "His game is called survivin'", "At the end of the harder they come", "You know it means no mercy", "They caught him with a gun", "No need for the Black Maria", "Goodbye to the Brixton sun", "You can crush us", "You can bruise us", "Yes, even shoot us", "But oh-the guns of Brixton", "Shot down on the pavement", "Waiting in death row", "His game is called survivin'", "As in heaven as in hell", "Anybody who makes speeches written ", "by someone else is just a robot."] ciphertexts = [ "Cfeufe trcczex kf kyv wrirnrp kfnej", "Tuc cgx oy jkirgxkj gtj hgzzrk iusk juct", "Twvlwv kittqvo bw bpm cvlmzewztl", "Lxvn xdc xo cqn ldykxjam, hxd kxhb jwm praub", "Bedted sqbbydw, dem ted'j beea je ki", "Yqxwh Knjcunvjwrj qjb krccnw cqn mdbc", "Hkjzkj ywhhejc, oaa sa wej'p ckp jk osejc", "'Lnyc oxa cqn arwp xo cqjc cadwlqnxw cqrwp", "Lzw auw syw ak ugeafy, lzw kmf ak rggeafy af", "Rjqyitbs jcujhyji, ymj bmjfy nx lwtbns' ymns", "Oxqsxoc cdyz bexxsxq, led S rkfo xy pokb", "Usmkw Dgfvgf ak vjgofafy, sfv A, A danw tq lzw janwj", "Cfeufe trcczex kf kyv zdzkrkzfe qfev", "Oxapnc rc, kaxcqna, hxd ljw px rc juxwn", "Twvlwv kittqvo bw bpm hwujqma wn lmibp", "Mqep dkhzejc kqp wjz znws wjkpdan xnawpd", "Gjiyji xvggdib viy D yji'o rvio oj ncjpo", "Mfe hspy hp hpcp elwvtyr T dlh jzf yzootyr zfe", "Jmlbml ayjjgle, qcc uc ygl'r emr lm fgef", "Votvgk wfi kyrk fev nzky kyv pvccfnp vpv", "Stb ljy ymnx", "Ehgwhg vteebgz, rxl, B ptl maxkx, mhh", "Iv' gwc svwe epib bpmg aiql? Emtt, awum wn qb eia bzcm!", "Svukvu jhsspun ha aol avw vm aol kphs", "Reu rwkvi rcc kyzj, nfe'k pfl xzmv dv r jdzcv?", "E jaran bahp ok iqyd w' hega w'hega w'hega", "Lwtc iwtn zxrz pi ndjg ugdci sddg", "Yfn pfl xfeer tfdv?", "Lxiw ndjg wpcsh dc ndjg wtps", "Il ih nby nlcaayl iz siol aoh", "Bmjs ymj qfb gwjfp ns", "Mtb dtz ltssf lt?", "Hwdi sdlc dc iwt epktbtci", "Tw bfnynsl ts ijfym wtb", "Qgm usf ujmkz mk", "Gwc kiv jzcqam ca", "Jcb gwc'tt pidm bw ivaemz bw", "Mf, rfc eslq md Zpgvrml", "Kyv dfevp wvvcj xffu", "Wjz ukqn heba ukq hega ep sahh", "Rkj ikhubo oekh jycu mybb secu", "Xp fk ebxsbk, xp fk ebii", "Hxd bnn, qn onnub urtn Rejw", "Uhkg ngwxk max Ukbqmhg lng", "Opz nhtl pz jhsslk zbycpcpu'", "Fy ymj jsi tk ymj mfwijw ymjd htrj", "Fvb ruvd pa tlhuz uv tlyjf", "Znke igamnz nos cozn g mat", "Yz yppo qzc esp Mwlnv Xlctl", "Zhhwurx mh max Ukbqmhg lng", "Vlr zxk zorpe rp", "Oek sqd rhkyiu ki", "Lrf, rira fubbg hf", "Kdc xq-cqn pdwb xo Kargcxw", "Dsze ozhy zy esp algpxpye", "Osalafy af vwslz jgo", "Efp dxjb fp zxiiba prosfsfk'", "Rj ze yvrmve rj ze yvcc", "Ylwzmbw ufm kyicq qnccafcq upgrrcl ", "ur lhfxhgx xelx bl cnlm t khuhm."] for i, ciphertext in enumerate(ciphertexts): test_cipher = CaesarCipher(ciphertext, crack=True) self.assertEquals(plaintexts[i], test_cipher.cracked)
true
1bccb7d663b5aa6a2db1147089061697a6524bf4
Python
jumpjumpdog/OpreatingSystemProjects
/TenpLayer.py
UTF-8
199
2.671875
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -* class TempLayer(object): def __init__(self,direction = 'wait',cur_layer = 1): self.direction = direction self.cur_layer = cur_layer
true
c793bca36318b4d1d3a8e80bda24d4c000e76767
Python
PerFilip/Advent-of-Code
/Day5/solution.py
UTF-8
1,393
3.765625
4
[]
no_license
import string def solve_1(): with open('data.txt', 'r') as data: message = data.read() return reactions(message) def reactions(message: str): while True: #Until all reactions have happened prev_len = len(message) for n in range(len(message) - 1): if message[n].lower() == message[n + 1].lower(): if message[n]!= message[n + 1]: message = message[:n] + message[n + 2:] break if prev_len == len(message): #If no new elements have been removed to problem is solved and the current length is returned. return len(message) def solve_2(): lengths = [] lowercase_alphabet = string.ascii_lowercase for letter in lowercase_alphabet: with open('data.txt', 'r') as data: message = data.read() new_message = remove_letter(message, letter) cur_len = reactions(new_message) print(cur_len) lengths.append(cur_len) return max(lengths) def remove_letter(message: str, letter: str): while True: cur_len = len(message) for n in range(len(message)): if message[n].lower() == letter: message = message[:n] + message[n + 1:] break if cur_len == len(message): return message
true
3fe4e88644e6a18811ff9d9f064f558303c81123
Python
BraedenBurgard/Sunhacks-2020
/data_tools.py
UTF-8
1,328
2.890625
3
[]
no_license
import pandas as pd import requests def get_api_key() -> str: try: with open('api.key') as file: return file.read().strip() except FileNotFoundError: raise FileNotFoundError(f"Missing omdbapi key. Store it in file 'api.key'.") def parse_float(n: str) -> float: try: return float(n) except ValueError as e: return float('nan') def load(show: str) -> pd.DataFrame: try: return pd.read_csv(f'{show}_data.csv') except FileNotFoundError: return default(show, get_api_key()) def save(data: pd.DataFrame, show: str): data.to_csv(f'{show}_data.csv', index=False) def default(show: str, api_key: str) -> pd.DataFrame: show_info = requests.get(f'http://www.omdbapi.com/?t={show}&apikey={api_key}').json() if show_info['Response'] == "False": raise Exception(f"OMDb does not list {show}.") id = show_info['imdbID'] total_seasons = int(show_info['totalSeasons']) # title = show_info['Title'] data = [] for i in range(1, total_seasons+1): season_info = requests.get(f'http://www.omdbapi.com/?i={id}&Season={i}&apikey={api_key}').json() for episode in season_info['Episodes']: data.append([ i, int(episode['Episode']), episode['Title'], parse_float(episode['imdbRating']), float('nan'), ]) return pd.DataFrame(data, columns=['season', 'episode', 'title', 'rating', 'date'])
true
94a7b6dcd60fd22551b117579c6d9fd27d996925
Python
chandeeland/exercism.io
/python/run-length-encoding/run_length.py
UTF-8
434
2.828125
3
[]
no_license
def encode(msg): count = 1 curr = msg[0] code = '' for i in range(1, len(msg)): global count, curr if msg[i] == curr: count += 1 else: if count > 1: code += str(count) code += curr curr = msg[i] count = 1 if count > 1: code += str(count) code += curr return code def decode(code): return
true
5cd96bb4a0b9742bbbe80b7e7caddeaea3958cea
Python
syntheticprotocol/Python
/practice/technique/test_data/test.py
UTF-8
1,645
3.265625
3
[]
no_license
""" !/usr/bin/env python3.6 -*- coding: utf-8 -*- -------------------------------- Description : -------------------------------- @Time : 2019/8/4 17:04 @File : test.py @Software: PyCharm -------------------------------- @Author : lixj @contact : lixj_zj@163.com """ # -*- coding:utf-8 -*- import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from pandas import DataFrame, Series # from sklearn.cross_validation import train_test_split from sklearn.linear_model import LinearRegression # 读取文件 datafile = 'test_excel.xlsx' # 文件所在位置,u为防止路径中有中文名称,此处没有,可以省略 data = pd.read_excel(datafile) # datafile是excel文件,所以用read_excel,如果是csv文件则用read_csv examDf = DataFrame(data) # 数据清洗,比如第一列有可能是日期,这样的话我们就只需要从第二列开始的数据, # 这个情况下,把下面中括号中的0改为1就好,要哪些列取哪些列 new_examDf = examDf.ix[:, 1:] # 检验数据 print(new_examDf.describe()) # 数据描述,会显示最值,平均数等信息,可以简单判断数据中是否有异常值 print(new_examDf[new_examDf.isnull() == True].count()) # 检验缺失值,若输出为0,说明该列没有缺失值 # 输出相关系数,判断是否值得做线性回归模型 print(new_examDf.corr()) # 0-0.3弱相关;0.3-0.6中相关;0.6-1强相关; # 通过seaborn添加一条最佳拟合直线和95%的置信带,直观判断相关关系 # sns.pairplot(data, x_vars=['visitor_id'], y_vars='created_time', height=7, aspect=0.8, kind='reg')
true
0d7b73e490edd28413667ce9854dd4d6b6425d3e
Python
qyk1480/py3
/12_tcpserver.py
UTF-8
505
2.828125
3
[]
no_license
from socket import socket, AF_INET, SOCK_STREAM # tcp服务端2个套接字,一个等待,一个交互 tcpServerSocket = socket(AF_INET, SOCK_STREAM) tcpServerSocket.bind(('', 9696)) tcpServerSocket.listen(6) # 新套接字,新套接字的ip和port # py 运行,等待对方连接 clientSocket, clientInfo = tcpServerSocket.accept() # 连接后,等待对方发数据 recvData = clientSocket.recv(1024) print('%s: %s' % (str(clientInfo), recvData)) clientSocket.close() tcpServerSocket.close()
true
e26f6c021bd3c1234075fff7d8c0ab4d9dd61817
Python
HG1227/ML
/数据预处理Fearture Scaling/最大最小值归一化 Normalization.py
UTF-8
4,247
3.453125
3
[]
no_license
#!/usr/bin/python #coding:utf-8 """ @software: PyCharm @file: 最大最小值归一化.py """ ''' Xscl=(X-Xmin)/(Xmax-Xmin) 实际处理的过程中针对同一列的数据 最大最小归一化不适合极端数据分布 ''' import numpy as np x=np.array([1,1,2,2,3,3,100]).reshape(-1,1) x2=(x-x.min())/(x.max()-x.min()) np.set_printoptions(suppress=True) x=np.hstack([x,x2]) # x=np.concatenate((x,x2),axis = 1) # print(x) ''' [[ 1. 0. ] [ 1. 0. ] [ 2. 0.01010101] [ 2. 0.01010101] [ 3. 0.02020202] [ 3. 0.02020202] [100. 1. ]] ''' #Sklearn 最值归一化 from sklearn import datasets from sklearn.model_selection import train_test_split wine=datasets.load_wine() # print(wine.DESCR) X=wine.data y=wine.target X_train,X_test,y_train,y_test=train_test_split(X,y, test_size=0.3, random_state=321) ''' 现在,将全部特征映射到 0-1 的范围后建模,预测模型得分效果如何,分三个步骤。 第一步,将数据归一化。加载和划分数据集已经练习过很多遍了不用多说。Sklearn 中的最 值归一化方法是 MinMaxScaler 类,fit 拟合之后调用 fit_transform 方法归一化训练集。 ''' #导入归一化方法并fit from sklearn.preprocessing import MinMaxScaler minmaxscaler=MinMaxScaler() #MinMaxScaler(feature_range=(0, 1), copy=True) minmaxscaler.fit(X_train) #fit之后才可以transform 归一化 X_train_minmax=minmaxscaler.fit_transform(X_train) ''' 解释一下 fit 、 fit_transform 和 transform 的作用和关系。 在执行归一化操作时,一定要先 fit 然后才能调用 fit_transform。因为 fit 的作用是计 算出训练集的基本参数,比如最大最小值等。只有当最大最小值有确定的数值时,才能通 过 fit_tranform 方法的断言,进而才能运行并进行归一化操作。否则不先运行 fit 那么 最大最小值的值是空值,就通不过 fit_transform 的断言,接着程序就会报过 fit_tranform 方法的断言,进而才能运行并进行归一化操作。否则不先运行 fit 那么错。 虽然计算最大最小值和归一化这两个步骤不相关,但 Sklearn 的接口就是这样设计的。 所以,要先 fit 然后 fit_transform。至于 transform,它的作用和 fit_transform 差不 多,只是在不同的方法中应用。比如 MinMaxScaler 中是 fit_transform,等下要讲的 均值方差归一化 StandardScaler 中则是 transform。 ''' #第二步,建立 kNN 模型。这一步也做过很多遍了。 #建立KNN模型 from sklearn.neighbors import KNeighborsClassifier KNN_clf=KNeighborsClassifier(n_neighbors=3) KNN_clf.fit(X_train_minmax,y_train) #第三步,测试集归一化并预测模型。 #这里一定要注意测试集归一化的方法:是在训练集的最大最小值基础归一化,而非测试集的最大最小值。 ''' 为什么是在训练集上呢?其实很好理解,虽然我们划分出的测试集能很容易求出最大最小值,但是别忘了我们划分测试集的目的:来模拟实际中的情况。而在实际中,通常很难获得数据的最大最小值,因为我们得不到全部的测试集。比如早先说的案例:酒吧猜新倒的一杯红酒属于哪一类。凭这一杯葡萄酒它是没有最大最小值的,你可能说加多样本,多几杯红酒不就行了?但这也只是有限的样本,有限样本中求出的最大最小值是不准确的,因为如果再多加几杯酒,那参数很可能又变了。 所以,测试集的归一化要利用训练集得到的参数,包括下面要说的均值方差归一化。 ''' #注意两点 1 在预测前也必须对测试集归一化 # 2 归一化采用的训练集的最大最小值,而不是测试集 X_test_minmax=minmaxscaler.fit_transform(X_test) #计算测试集得分 sc=KNN_clf.score(X_test_minmax,y_test) print(sc) #0.9074074074074074 #作为对比 求出未归一化的得分 KNN_clf=KNeighborsClassifier(n_neighbors=3) KNN_clf.fit(X_train,y_train) sc=KNN_clf.score(X_test,y_test) print(sc)
true
b8899800c7e91d79d3dfe1252c43ce43861fe601
Python
Temaaaal/informatika
/continenti.py
UTF-8
300
3.515625
4
[]
no_license
countries = ["USA","China","Japan","Germany","Spanis"] print(countries) print(sorted(countries)) print(sorted(countries, reverse=True)) countries.reverse() print(countries) countries.reverse() print(countries) countries.sort() print(countries) countries.sort(reverse=True) print(countries)
true
42182d19036c35bd5e4fc5629e134c31d8c38403
Python
kuroshum/signate_lesson2020
/tajika/exercise3.py
UTF-8
178
2.875
3
[]
no_license
import numpy as np values = np.array([10, 3, 1, 5, 8, 6]) print(values) convert_values = [-1 if values[ind] < 5 else 1 for ind in np.arange(len(values))] print(convert_values)
true
c5a02b81cc7c1c7596de4216b5ab1857695a9b2e
Python
Doug1983/MRI_GUI
/_Archived/DT_GUI/NeuroportDBS-master/NeuroportDBS-master/PlotDBSTrack/utilities.py
UTF-8
3,807
3.1875
3
[]
no_license
import numpy as np def rms(x): """ The root mean square of a signal. Parameters ---------- x: array_like An array of input sequence. Returns ------- out: float A root mean square of the signal. """ return np.sqrt(np.mean(x**2)) def rmse(x1, x2): """ The root mean square error between two signals. Parameters ---------- x1: array_like An array of input sequence. x2: array_like Another array of input sequence. Returns ------- out: float The root mean square error between the two input sequences. """ return rms(x1-x2) def nrmse(x1, x2): """ The normalized root mean square error between two signals. Parameters ---------- x1: array_like An array of input sequence. x2: array_like Another array of input sequence. Returns ------- out: float The normalized root mean square error between the two input sequences. """ return rms(x1-x2) / rms(x1) def group_by(x, n=10): """ Group a sequence by a number of iteration. """ l = x.shape[0] remain = np.mod(l, n) if remain != 0: padding = np.zeros((n-remain)) x = np.hstack([x, padding]) w = x.shape[0] / n return [x[i*w:(i+1)*w] for i in xrange(n)] # ==================================================== # ========== Pre-Process for Finding Artefact ======== # ==================================================== def segment_consecutive(data, stepsize=100): """ Group data that has consecutive segments with increment < stepsize together. Parameters ---------- signal: a single channel numpy array stepsize: the threshold specifying the difference between each increment Returns ------- sub-arrays: list of ndarrays A list of sub-arrays grouped with consecutive signal, where the difference in the increment is specified by the stepsize. Examples -------- >>> x = np.arange(100) >>> x[50:60] = np.arange(10) * 5 >>> new_x = util.segment_consecutive(x, stepsize=10) >>> print new_x [array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), array([ 0, 5, 10, 15, 20, 25, 30, 35, 40, 45]), array([60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99])] """ return np.split(data, np.where(np.abs(np.diff(data)) >= stepsize)[0]+1) def artifact_flat(signal, replace_by_value=None, minGap=1, thres=1e-8): """ Locate where the samples in the signal that are flat. Parameters ---------- signal: Single channel numpy array replace_by_value: The value for replacing the flat samples Default - None returns the labels only Returns ------- signal: The new signal replacing the original one or label: An array of boolean representing where the signal is flat """ # label True for the flat samples #TODO: fix the minGap property such that it captures all the points. sig = signal.copy() label = (np.abs(sig - np.roll(sig, -minGap)) < thres) & (np.abs(signal - np.roll(signal, minGap)) < thres) labelTransition = np.roll(label, -minGap) & -np.roll(label, minGap) | np.roll(label, minGap) & -np.roll(label, -minGap) label[labelTransition] = True # mark all transitioning point as True if replace_by_value or replace_by_value == 0: sig[label] = replace_by_value return sig else: return label
true
4f104f20e3bd00e6e318bb0c2b7b2efceb84ad4e
Python
BCM-HGSC/ngsi-pm
/ngsi_pm/vcf_worklist.py
UTF-8
5,883
2.609375
3
[]
no_license
#!/usr/bin/env python3 """Read a master workbook and output an XLSX workbook annotated with absolute paths read from the filesystem.""" # First come standard libraries, in alphabetical order. import argparse import csv import logging import os import pprint import sys import warnings # After a blank line, import third-party libraries. import openpyxl # After another blank line, import local libraries. # When your code is something you would use cautiously in production, # delete the "-unstable" suffix. That suffix is saying that this script # could change behaviour without the version number changing. In other # words, a later version of this script will be 1.0.0, but you aren't # there just yet. from .version import __version__ logger = logging.getLogger(__name__) REQUIRED_INPUT_COLUMN_NAMES = ''' sample_id/nwd_id lane_barcode vcf_batch result_path '''.split() # The order of the columns in the output REQUIRED_INPUT_COLUMN_NAMES_SET = set(REQUIRED_INPUT_COLUMN_NAMES) ADDITIONAL_OUTPUT_COLUMN_NAMES = ''' snp_file snp_path indel_file indel_path '''.split() # The order of the columns in the output def main(): args = parse_args() config_logging(args) run(args) logging.shutdown() def parse_args(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( 'input_file', help='an XLSX workbook containing a master worklist ' 'in the first worksheet' ) parser.add_argument('-o', '--output_file', help='will default to MASTER_annotated.xlsx') parser.add_argument('-v', '--verbose', action='store_true') parser.add_argument('--version', action='version', version='%(prog)s {}'.format(__version__)) args = parser.parse_args() if args.output_file is None: args.output_file = munge_input_file_name(args.input_file) return args def munge_input_file_name(input_file_name): """X.xlsx -> X_vcfs.xlsx""" assert input_file_name.endswith('.xlsx') return input_file_name[:-5] + '_vcfs.xlsx' def config_logging(args): global logger level = logging.DEBUG if args.verbose else logging.INFO logging.basicConfig(level=level) logger = logging.getLogger('vcfs_worklist') def run(args): logger.debug('args: %r', args) input_file = args.input_file output_file = args.output_file process_input(input_file, output_file) logger.debug('finished') def process_input(input_file, output_file): """A docstring should say something about the inputs, operation, and any return values. In this case there are no return values, since results are printed to the specified file.""" logger.debug('process_input %s -> %s', input_file, output_file) data = read_input(input_file) logger.info('found %s records', len(data)) for record in data: add_file_paths(record) pprint.pprint(vars(data[0])) write_annotated_workbook(output_file, data) def read_input(input_file): """Return representation of reading master XLSX.""" warnings.simplefilter("ignore") wb = openpyxl.load_workbook(filename=input_file) master_worksheet = find_master_worksheet(wb) logger.debug('master worksheet name: %s', master_worksheet.title) row_iter = iter(master_worksheet.rows) header_row = next(row_iter) column_names = [c.value for c in header_row] logger.debug('columns: %s', column_names) missing = set(REQUIRED_INPUT_COLUMN_NAMES) - set(column_names) assert not missing, 'missing: {}'.format(sorted(missing)) data = [] for row in row_iter: record = Generic() for column_name, cell in zip(column_names, row): if column_name in REQUIRED_INPUT_COLUMN_NAMES_SET: value = cell.value setattr(record, column_name, value) if record.result_path and record.result_path[0] != '#': data.append(record) return data def find_master_worksheet(wb): master_worksheet = None for ws in wb: logger.debug('found: %s', ws.title) if ws.title.endswith('_smpls') or ws.title == 'smpls': assert master_worksheet is None, 'ambiguous worksheets: {}, {}'.format( master_worksheet.title, ws.title ) master_worksheet = ws assert master_worksheet, 'no worksheet with correct name' return master_worksheet def add_file_paths(record): """Add the file paths found under result_path.""" result_path = record.result_path logger.debug('searching: %s', result_path) for file_name in os.listdir(result_path): if file_name.endswith('.hgv.bam'): record.current_bam_name = file_name record.bam_path = os.path.join(result_path, file_name) variants_path = os.path.join(result_path, 'variants') for file_name in os.listdir(variants_path): if file_name.endswith('_snp_Annotated.vcf'): record.snp_file = file_name record.snp_path = os.path.join(variants_path, file_name) elif file_name.endswith('_indel_Annotated.vcf'): record.indel_file = file_name record.indel_path = os.path.join(variants_path, file_name) def write_annotated_workbook(output_file, data): wb = openpyxl.Workbook() ws = wb.active ws.title = "smpls" header = REQUIRED_INPUT_COLUMN_NAMES + ADDITIONAL_OUTPUT_COLUMN_NAMES ws.append(header) for record in data: row = [getattr(record, name) for name in header] ws.append(row) # bold = openpyxl.styles.Font(bold=True) # for c in ws.rows[0]: # c.font = bold # TODO: Investigate setting column widths. wb.save(output_file) class Generic: """Nothing special. Just a class to create objects with __dict__.""" pass if __name__ == '__main__': main()
true
b0bd9507ed47f9c73d7f88ee5b7bec62545a0199
Python
divanshu79/hackerearth-solution
/Marut and Girls.py
UTF-8
356
2.984375
3
[]
no_license
n = int(input()) a = list(map(int,input().split())) count = 0 for j in range(int(input())): arr = list(map(int,input().split())) d = {} flag = 0 for i in range(len(arr)): d[arr[i]] = 1 for i in range(len(a)): if(a[i] not in d): flag = 1 break else: flag = 0 if(flag == 0): count += 1 #print(d) print(count)
true
bb33bdaa1206bfd2e1ead1bc0f4c085296f58ec7
Python
lanlanabcd/atis
/interaction.py
UTF-8
5,109
2.84375
3
[]
no_license
""" Contains the class for an interaction in ATIS. """ import anonymization as anon import sql_util from snippets import expand_snippets from utterance import Utterance, OUTPUT_KEY, ANON_INPUT_KEY class Interaction: """ ATIS interaction class. Attributes: utterances (list of Utterance): The utterances in the interaction. snippets (list of Snippet): The snippets that appear through the interaction. anon_tok_to_ent: identifier (str): Unique identifier for the interaction in the dataset. """ def __init__(self, utterances, snippets, anon_tok_to_ent, identifier, params): self.utterances = utterances self.snippets = snippets self.anon_tok_to_ent = anon_tok_to_ent self.identifier = identifier # Ensure that each utterance's input and output sequences, when remapped # without anonymization or snippets, are the same as the original # version. for i, utterance in enumerate(self.utterances): deanon_input = self.deanonymize(utterance.input_seq_to_use, ANON_INPUT_KEY) assert deanon_input == utterance.original_input_seq, "Anonymized sequence [" \ + " ".join(utterance.input_seq_to_use) + "] is not the same as [" \ + " ".join(utterance.original_input_seq) + "] when deanonymized (is [" \ + " ".join(deanon_input) + "] instead)" desnippet_gold = self.expand_snippets(utterance.gold_query_to_use) deanon_gold = self.deanonymize(desnippet_gold, OUTPUT_KEY) assert deanon_gold == utterance.original_gold_query, \ "Anonymized and/or snippet'd query " \ + " ".join(utterance.gold_query_to_use) + " is not the same as " \ + " ".join(utterance.original_gold_query) def __str__(self): string = "Utterances:\n" for utterance in self.utterances: string += str(utterance) + "\n" string += "Anonymization dictionary:\n" for ent_tok, deanon in self.anon_tok_to_ent.items(): string += ent_tok + "\t" + str(deanon) + "\n" return string def __len__(self): return len(self.utterances) def deanonymize(self, sequence, key): """ Deanonymizes a predicted query or an input utterance. Inputs: sequence (list of str): The sequence to deanonymize. key (str): The key in the anonymization table, e.g. NL or SQL. """ return anon.deanonymize(sequence, self.anon_tok_to_ent, key) def expand_snippets(self, sequence): """ Expands snippets for a sequence. Inputs: sequence (list of str): A SQL query. """ return expand_snippets(sequence, self.snippets) def input_seqs(self): in_seqs = [] for utterance in self.utterances: in_seqs.append(utterance.input_seq_to_use) return in_seqs def output_seqs(self): out_seqs = [] for utterance in self.utterances: out_seqs.append(utterance.gold_query_to_use) return out_seqs # raw_load_function def load_function(parameters, nl_to_sql_dict, anonymizer): def fn(interaction_example): keep = False raw_utterances = interaction_example["interaction"] identifier = interaction_example["id"] snippet_bank = [] utterance_examples = [] anon_tok_to_ent = {} for utterance in raw_utterances: available_snippets = [ snippet for snippet in snippet_bank if snippet.index <= 1] proc_utterance = Utterance(utterance, available_snippets, nl_to_sql_dict, parameters, anon_tok_to_ent, anonymizer) keep_utterance = proc_utterance.keep if keep_utterance: keep = True utterance_examples.append(proc_utterance) # Update the snippet bank, and age each snippet in it. if parameters.use_snippets: snippets = sql_util.get_subtrees( proc_utterance.anonymized_gold_query, proc_utterance.available_snippets) for snippet in snippets: snippet.assign_id(len(snippet_bank)) snippet_bank.append(snippet) for snippet in snippet_bank: snippet.increase_age() interaction = Interaction(utterance_examples, snippet_bank, anon_tok_to_ent, identifier, parameters) return interaction, keep return fn
true
846a2f6b7c37cf18129594aad786860867c5176b
Python
TKuzola/pgsandbox
/try_sqlalchemy.py
UTF-8
1,038
3.015625
3
[]
no_license
import psycopg2 import sqlalchemy as db from sqlalchemy.orm import sessionmaker def connect(): try: engine = db.create_engine("postgresql://postgres:777999Pg@localhost:5432/postgres") # engine.echo = True # We want to see the SQL we're creating # connection = engine.connect() metadata = db.MetaData() log2 = db.Table('test_log2', metadata, autoload=True, autoload_with=engine, schema='test') # Print the column names # print(log2.columns.keys()) # Print full table metadata # print(repr(metadata.tables['log2'])) Session = sessionmaker(bind=engine) # Equivalent to 'SELECT * FROM log2' work_session = Session() for instance in work_session.query(log2): print(instance.message_id, instance.message1, instance.message2) except Exception as e: # handle exception "e", or re-raise appropriately. print(e) finally: print('goodbye.') if __name__ == '__main__': connect()
true
0bf88e4b779ac1d0e11980f792dafda7a2b2f28b
Python
AndreXi/clock-sync
/main.py
UTF-8
4,941
3.1875
3
[ "MIT" ]
permissive
#! /usr/bin/python3 # -*- coding utf-8 -*- # @AndreXi (Author) """ CLOCK-SYNC Este programa se encarga de ajustar la hora de un sistema Windows automaticamente realizado con el objetivo de brindar una solucion rapida a problemas comunes que causan cambios indeseados en la hora del sistema (Ej: BIOS sin batería, arranque dual). """ main_msg = '''Modificar la hora del sistema necesita permisos de Administrador. Para agilizar puedes pasar como argumento la zona horaria. Para no entrar en taskmenu use "-n" como argumento Ej: "main.py -4:00 -n" , "main.py +4:00 -n"''' print(main_msg) import os import sys import time import ntplib # Requiere instalacion import admin # Para solicitar privilegios de administrador. import win32api from taskmenu import TaskEditor def main(): try: # Comunicación con NTP. client = ntplib.NTPClient() response = client.request('pool.ntp.org') # Variables user_tz = user_TimeZoneHandler() user_timezone = user_tz[0] * 60 * 60 + user_tz[1] * 60 local_timezone = time.timezone offset = local_timezone * 2 - user_timezone # Genera la tupla con la hora actualizada f_time = time.localtime(response.tx_time + offset) # Ajusta la hora del sistema fix_clock(f_time) # Sale sin errores. return 0 except ntplib.NTPException: print('Ocurrio un error de comunicacion con el servidor\nRevise su conexion a internet, firewalls, etc') return 1 def fix_clock(f_time): """Aqui se realiza el cambio de hora""" win32api.SetSystemTime(f_time[0], # Año %Y f_time[1], # Mes %m f_time[6], # dayOfWeek ?? f_time[2], # Dia %d f_time[3], # Hora %H f_time[4], # Minutos %M f_time[5], # Segundos %S 0) # Milisegundos def reset_clock(): """Ajusta el reloj al origen de los tiempos (?)""" f_time = time.localtime(0) fix_clock(f_time) def new_TimeZone(): """Le pide al usuario su zona horaria.""" print('\n' * 16) instruccions = ''' A continuación se debe introducir la zona horaria... Debe seguir obligatoriamente el siguiente formato: -HH:MM o +HH:MM\n ''' r = input(instruccions) return r def user_TimeZoneHandler(): """ Retorna una tupla con la zona horaria guardados como enteros """ # Si se pasa la zona horaria como argumento se usará primero. if len(sys.argv) > 1: use_argv = True else: use_argv = False while True: try: if use_argv: # Si el usuario pasa un argumento time_zone = sys.argv[1] # este se usara primero. else: time_zone = new_TimeZone() # Pide la la zona horaria # La agrega a los argumentos sys.argv.append(time_zone) # Evita un error por colocar el '+' time_zone = time_zone.replace('+', '') time_zone = time_zone.rsplit(':') # Separa horas y minutos fix_h = -int(time_zone[0]) fix_m = -int(time_zone[1]) return (fix_h, fix_m) # Todo esta correcto except Exception: if use_argv: print('ERROR: El argumento no sigue el formato -HH:MM o +HH:MM') print('El programa ignorará el argumento') use_argv = False # Ignorar el argumento erroneo else: print('ERROR: La información introducida no sigue el formato dado') if __name__ == '__main__' and os.name == 'nt': user_TimeZoneHandler() # Primero le pide al usuario la zona horaria task = TaskEditor(sys.argv[1]) # Y se agrega a los argumentos if not admin.isUserAdmin(): admin.runAsAdmin() # Se ejecuta en una consola de administrador sys.argv.insert(2, '-n') # Evita que se abra la UI Tareas 2 veces admin.runAsAdmin() # Si, por alguna razon necesito ejecutarlo 2 veces else: reset_clock() # Evita errores por reloj muy adelantado i = 0 while main() and i <= 10: # Ajusta el reloj i += 1 print('Intento (%s / 10)' % (i)) if len(sys.argv) > 2: if sys.argv[2] == '-n': pass else: print('Para no entrar en taskmenu use "-n" como argumento') else: task.taskMenu() # Inicia la UI para tratar la tarea task.xmlDelete() # Elimina el archivo auxiliar sys.exit(0) # Cierra sin errores
true
a36ffe27c0738d16eb926cb07357569436703c41
Python
PaviVasudev/DistracNot
/Other Files/trial.py
UTF-8
2,913
3.25
3
[ "MIT" ]
permissive
import speech_recognition as SpeechRecog import pyaudio from random_word import RandomWords import random import time import threading init_rec = SpeechRecog.Recognizer() score = 0 num_ques = 0 lang = { 1: 'en-US', 2: 'hi-IN', 3: 'ta-IN', 4: 'te-IN', 5: 'kn-IN', 6: 'zh-CN', 7: 'ja-JP', 8: 'it-IT', 9: 'fr-FR', 10: 'de-DE' } def quiz(string): global score global num_ques ran_word = random_words() # taking a random word from the correct answer random_correct = [] minimize = [words for words in string if len(words) >= 5] len_str = len(minimize) x = random.randint(0, len_str) for i in range(3): random_correct.append(minimize[(x+i)%len_str]) random_correct = ' '.join(random_correct) # print(random_correct) # appending random word from the wrong answer and correct answer options = [] for i in ran_word: options.append(i) options.append(random_correct) # shuffling all the options random.shuffle(options) # print(options) op1 = options[0] op2 = options[1] op3 = options[2] op4 = options[3] print("Choose the word which was mentioned by the professor:") print("1.", options[0], "2.", options[1], "3.", options[2], "4.", options[3]) user_choice = input("Enter option:") if user_choice == "1": ans = op1 elif user_choice == "2": ans = op2 elif user_choice == "3": ans = op3 elif user_choice == "4": ans = op4 else: print("Inavlid option") if ans == random_correct: print("Correct option") score += 1 num_ques += 1 else: print("Wrong option") num_ques += 1 def random_words(): r = RandomWords() words = r.get_random_words() word_final = [] words1 = words[:3] words1 = ' '.join(words1) word_final.append(words1) words2 = words[3:6] words2 = ' '.join(words2) word_final.append(words2) words3 = words[6:9] words3 = ' '.join(words3) word_final.append(words3) return word_final def main(num): while True: words = [] for i in range(1): with SpeechRecog.Microphone() as source: audio_data = init_rec.record(source, duration=10) try: text = init_rec.recognize_google(audio_data, language = lang[num]) except: text = '' #text = 'Note that we may get different output because this program generates random number in range 0 and 9.' text_filtered = text.split(' ') for j in text_filtered: words.append(j) quiz(words) ''' thread_quiz = threading.Thread(target=quiz, args=(words, )) thread_quiz.start() thread_quiz.join() ''' print(score) if __name__ == '__main__': main(3)
true
535b2cefb7afe59f53acd31d8c04ed0920296a12
Python
velzepooz/exercises
/csv.py
UTF-8
436
3.09375
3
[]
no_license
import csv rows = [] with open("m5-buckwheat.csv") as fp: reader = csv.reader(fp) for row in reader: rows.append(row) fields = rows[0] rows = rows[1:] print(fields) print(rows) # максимальная цена манки # m = 0 # for r in rows: # val = float(r[1]) # if val > m: # m = val # print(m) m = 40.71 for r in rows: val = float(r[1]) if val < m: m = val print(m * 0.250)
true
c4bbf8fca947a14906a21dfc4b892d12d8ba55ee
Python
piperpi/python_book_code
/Python编程锦囊/Code(实例源码及使用说明)/10/1~14/flask/12/run.py
UTF-8
1,706
2.59375
3
[]
no_license
from flask import Flask, request,render_template,redirect from flask_mail import Mail, Message from threading import Thread from forms import RegistrationForm app = Flask(__name__) # 配置邮件服务 app.config['MAIL_SERVER'] = 'smtp.qq.com' app.config['MAIL_PORT'] = 25 app.config['MAIL_USE_TLS'] = True app.config['MAIL_USERNAME'] = '#####' # 邮箱 app.config['MAIL_PASSWORD'] = '******' # 验证密保 mail = Mail(app) def send_async_email(app, msg): '''异步发送邮件''' with app.app_context(): mail.send(msg) @app.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm(request.form) # 实例化RegistrationForm类 if request.method == 'POST' and form.validate(): # 判断是否提交表单,并且表单字段验证通过 username = request.form.get('username','尊敬的用户') # 获取用户名 email = request.form.get('email') # 获取邮箱 recipients = list() # 收件人邮件列表 recipients.append(email) # 加入收件人邮件列表 msg = Message('[明日学院]网站用户激活邮件', sender='694798056@qq.com', recipients=recipients) msg.body = '您好'+username+',明日学院管理员想邀请您激活您的用户,点击链接激活。https://www.mingrisoft.com' # 使用线程 thread = Thread(target=send_async_email, args=[app, msg]) # 创建线程实例 thread.start() # 开启线程 return redirect('/mail_success') # 跳转路由 return render_template('register.html', form=form) # 渲染模板 @app.route("/mail_success") def mail_success(): return "邮件发送成功" if __name__ == '__main__': app.run(debug=True)
true
5a93e5dd250ea97d9f915ebcd6e340989c97abe5
Python
inkrypto/crypt0pa15
/five.py
UTF-8
1,120
4.03125
4
[]
no_license
#!/usr/bin/python ''' Implement repeating-key XOR Here is the opening stanza of an important work of the English language: Burning 'em, if you ain't quick and nimble I go crazy when I hear a cymbal Encrypt it, under the key "ICE", using repeating-key XOR. In repeating-key XOR, you'll sequentially apply each byte of the key; the first byte of plaintext will be XOR'd against I, the next C, the next E, then I again for the 4th byte, and so on. It should come out to: 0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272 a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f Encrypt a bunch of stuff using your repeating-key XOR function. Encrypt your mail. Encrypt your password file. Your .sig file. Get a feel for it. I promise, we aren't wasting your time with this. ''' def encrypt(text, key): x = '' for i in range(0, len(phrase)): x += chr(ord(phrase[i]) ^ ord(key[i % 3])).encode('hex') return(x) if __name__ == '__main__': phrase = "Burning 'em, if you ain't quick and nimble I go crazy when I hear a cymbal" k = "ICE" print(encrypt(phrase, k))
true
87f485bfa62ee25563789fd41debf8dfe1c7ef13
Python
Vishal7515/Image-Encryption-Decryption-using-Cyphers
/encryption(final).py
UTF-8
904
2.6875
3
[]
no_license
from PIL import Image, ImageDraw, ImageFilter, ImageOps #imported the required objects from the Python Image Library import sys #imported sys so zas to view the entire numpy array import numpy as np from random import randint np.seterr(divide='ignore', invalid='ignore') def random_with_N_digits(n): range_start = 10**(n-1) range_end = (10**n)-1 return randint(range_start, range_end) data_image = Image.open('thanos.jpg') ar1 = np.array(data_image) print(ar1) size_dat = min(data_image.size) print(size_dat) key = random_with_N_digits(size_dat) key = str(key) key_image = Image.open('test_3.jpg') ar2 = np.array(key_image) maink = np.sum(ar2,axis=0)#/size_dat maink = maink.astype('uint8') print(maink) print(ar2) ar3 = ar1 - maink print(ar3) im1 = Image.fromarray(ar3) im1.save('inotded.jpg')
true
a0dfba244504b1d0c518dca51d58ef18b24d0577
Python
Selidex/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/1-search_replace.py
UTF-8
221
3.453125
3
[]
no_license
#!/usr/bin/python3 def search_replace(my_list, search, replace): new_list = my_list.copy() for x in range(0, len(new_list)): if new_list[x] == search: new_list[x] = replace return new_list
true
51f5e60f1c48d6fe50a1cf796e28b3f38e9c2f2f
Python
1va/caravan
/get_data/UTM_GPS.py
UTF-8
2,605
2.53125
3
[]
no_license
""" Description: Get list of GPS coordinates of caravan parks from other peoples' lists Author: Iva Date: 07/12/2015 Python version: 2.7 """ #from utm import to_latlon, from_latlon from pyproj import transform, Proj import numpy as np # forst define the conversion from the stupid british eastling and northling bng = Proj(init= 'epsg:27700') wgs84 = Proj(init= 'epsg:4326') #transform(bng, wgs84, 458528,99293) neals_data = np.genfromtxt('coord_lists/Neals_List1_final.csv', delimiter=',', skip_header= True, dtype='float')[:,0:2] x=np.array(transform(bng, wgs84, neals_data[:,0], neals_data[:,1])) np.savetxt('coord_lists/Neals_List1_final_gps.csv',x.transpose(), fmt='%.6f', delimiter=', ') neals_coord = np.vstack({tuple(row) for row in np.transpose([x[1],x[0]])}) m77_data = np.genfromtxt('coord_lists/77m_Sample_list.csv', delimiter=',', skip_header= True, dtype='float')[:,0:2] x=np.array(transform(bng, wgs84, m77_data[:,0], m77_data[:,1])) np.savetxt('coord_lists/77m_Sample_list_gps.csv',x.transpose(), fmt='%.6f', delimiter=', ') zoopla_data = np.genfromtxt('get_data/park_homes_zoopla_3col.csv', delimiter=',', skip_header= True, dtype='float') zoopla_caravans = np.vstack({tuple(row) for row in zoopla_data[zoopla_data[:,2]==1,0:2]}) zoopla_controls = np.vstack({tuple(row) for row in zoopla_data[zoopla_data[:,2]==0,0:2]}) zoopla_controls_subset = zoopla_controls[[5*i for i in range(200*9)],:] np.savetxt('get_data/GPS_5000caravans.csv', neals_coord[0:5000,:], fmt='%.6f', delimiter=', ') np.savetxt('get_data/GPS_5000controls.csv', zoopla_controls[0:5000,:], fmt='%.6f', delimiter=', ') caravan_parks = [[50.6259796,-2.2706743], #durdle door [50.689801,-2.3341522], #warmwell [50.7523135,-2.0617302], #huntnick [50.7041072,-1.1035238], #nodes point [50.700116,-1.1138009], #st. helens [50.7963016,-0.9838095], #hayling island [50.7988633,-0.9804728], #oven campsite [50.7826322,-0.9472032], #eliots estate [50.7831533,-0.9574026], #fishery creek [50.9058588,-1.1627122], #rookesbury [51.0093301,-1.5739032], #hillfarm [50.9622607,-1.6225851], #greenhill [50.8515685,-1.2839778], # dybles SUSPICIOS [50.7358116,-1.5499394], # hurst view [50.8218972,-0.3123287] # beach park ] #random.seed(1234) #random_areas = [[random.uniform(50.8484,52.0527), random.uniform(-2.75874, 0.4485376)]for i in range(20)]
true
311901216a8f1007e8c1e6ddc4976ede2c7564c5
Python
SaipraveenB/projection-networks
/environments/project2d.py
UTF-8
1,120
3.03125
3
[]
no_license
import numpy as np import math # Returns a 1D image of the 2D scene as seen from position 'pos' and direction 'dir' # Uses ray tracing to find the target points. # Use FOV=90deg for now. def project( pos, dirs, shapelist, fov=90, resolution=100): # calculate max deviation as the lateral distance on a filmstrip placed a unit distance away. # RGBA space. col_img = np.zeros((resolution,4)) depth_img = np.zeros((resolution,1)) max_r = math.tan(((fov/2.0)*math.pi)/180.0); f_dir, r_dir = dirs; # Shoot rays. for k in zip(np.linspace( -max_r, max_r, resolution ), range(0, resolution)): direction = (f_dir + k[0] * r_dir) direction = direction / np.linalg.norm(direction) ray = (pos, direction ) min_depth = 1000; this_color = np.zeros((4,)) for shape in shapelist: hit, color, depth, _ = shape.intersect( ray ) if hit and depth < min_depth: min_depth = depth this_color = color col_img[k[1]] = this_color depth_img[k[1]] = min_depth return (col_img, depth_img)
true
b880680518fd25693861d6f93017ddb6b22cabb3
Python
somsomdah/Algorithm
/Algorithm-python/_section8/MaximumScore.py
UTF-8
186
2.609375
3
[]
no_license
n,m=map(int,input().split()) q=[(0,0)] D=[0]*(m+1) for i in range(n): s,t=map(int,input().split()) for j in range(m,t-1,-1): D[j]=max(D[j],D[j-t]+s) print(D[m])
true
bad2cc013d14a3e9dff034c934250bfa934dfebe
Python
swaathe/py
/min.py
UTF-8
121
3.6875
4
[]
no_license
n = [int(x) for x in input("enter the array elements:").split()] print(min(n),("is the min element in the given array"))
true
93586a525757831747444f547bd8042dae85c27d
Python
vmms16/MonitoriaIP
/Arquivos/slide_28.py
UTF-8
251
2.515625
3
[]
no_license
import os os.chdir('C:\\Users\\Vinicius\\Desktop\\Vinicius\\UFRPE\\Projetos - Eclipse') arqe=open('exercicios2.txt','r') dic={} x=arqe.readlines() arqe.close() for i in x: y=i.strip('\n').split(' ') dic[y[0]]=y[1] print(dic)
true
fee600b1cde72228a8251e98f81120294915a5cf
Python
gitdxb/learning-python
/free-python/guessinggame.py
UTF-8
602
4.4375
4
[]
no_license
## Guessing Game print("Think of a number between 1 and 100") def guess(): max = 100 min = 0 count = 0 finish = False while finish == False: middle = int((max + min)/2) answer = input("Is your number [H]igher, [L]ower or the [S]ame as {} ".format(middle)).upper() count += 1 for guess in answer: if answer == "H": min = middle elif answer == "L": max = middle else: print("Your number is {}, it took me".format(middle),count," guess") finish = True guess()
true
701b4430a1ddbc0ea5239af533891fb47edceccc
Python
Homnis/hyx
/former/Method.py
UTF-8
5,002
3.5625
4
[]
no_license
# # 1. # def printList(list1=[]): # print(list1) # # # list1 = [1, 2, 3, 4] # printList(list1) # # 2. # def sumList(list1=[]): # Sum = 0 # for i in range(len(list1)): # Sum = Sum + list1[i] # return Sum # # # list1 = [1, 2, 3, 4] # print(sumList(list1)) # #3. # def sumList(list1=[]): # Sum = 0 # for i in range(len(list1)): # if i%2==1: # Sum = Sum + list1[i] # return Sum # # list1 = [1, 2, 3, 4] # print(sumList(list1)) # 4. # def sumList(list1=[]): # Sum = 0 # for i in range(len(list1)): # if i%2==0: # Sum = Sum + list1[i] # return Sum # # list1 = [1, 2, 3, 4] # print(sumList(list1)) # 5. # def Sum(a=0,b=0): # return a+b # # print(Sum(10,20)) # # 6. # def Divide(a=0, b=1): # if b == 0: # print("something wrong happened") # return a / b # # # print(Divide(10, 20)) # 7. # def add1s(day=0, hour=0, minute=0, second=0): # seconds = day * 3600 * 60 + hour * 3600 + minute * 60 + second # return seconds # # # print(add1s(1, 1, 1, 1)) # 8. # def exchange(list1=[], pos1=0, pos2=1): # x = list1[pos1] # list1[pos1] = list1[pos2] # list1[pos2] = x # # # listA = [1, 2, 3, 4] # exchange(listA, 1, 3) # print(listA) # 9. # def divide3(list1=[]): # count = 0 # for i in range(len(list1)): # if list1[i] % 3 == 0: # count += 1 # return count # # # list1 = [1, 2, 3, 4, 5, 6] # print(divide3(list1)) # 10. # def change(num=0, char="*", length=1): # str1 = str(num) # if len(str1) > length: # return str1[:length] # elif len(str1) < length: # return str1.rjust(length, char) # # # print(change(27, '0', 8)) # 11. # def maxMin(list1=[], isMax=True): # if isMax == True: # return max(list1) # elif isMax == False: # return min(list1) # # # list1 = [1, 2, 3, 4, 5] # print(maxMin(list1, True)) 12. # def primeNum(num=0): # for i in range(2,num): # if i < num - 1: # if num % i == 0: # return False # break # elif num % i != 0: # continue # elif i == num - 1: # return True # # # print(primeNum(12)) # 13. # def seconds(seconds=0): # days,hours,minutes=0,0,0 # while seconds >= 0: # if seconds >= 216000: # days = seconds // 216000 # seconds = seconds % 216000 # elif 3600 <= seconds < 216000: # hours = seconds // 3600 # seconds = seconds % 3600 # elif 60 <= seconds < 3600: # minutes = seconds // 60 # seconds = seconds % 60 # elif seconds < 60: # break # print("%i天,%i小时,%i分钟,%i秒" %(days,hours,minutes,seconds)) # # # seconds(7894624) # 14. # import random # # # def r(list1=[],num=1): # i = 0 # while i < num: # x = random.randint(0, num) # if x not in list1: # list1.append(x) # i += 1 # else: # continue # # list1=[] # r(list1,5) # print(list1) # 15. # def duiChen(list1=[]): # for i in range(len(list1)): # if list1[i] == list1[len(list1) - i - 1]: # if i >= len(list1) / 2: # return True # continue # else: # return False # # # list1 = [3, 1, 2, 1,] # print(duiChen(list1)) # 16. # def printTuple(tuple1=()): # for i in range(len(tuple1)): # print(tuple1[i], end=" ") # # # tuple1 = (1, 2, 3, 4, 5) # printTuple(tuple1) # # 17. # def inTuple(tuple1=(), a=0): # for i in range(len(tuple1)): # if a == tuple1[i]: # return i # else: # if i == len(tuple1) - 1: # return -1 # # # tuple1 = (1, 2, 3, 4, 5) # print(inTuple(tuple1, 3)) # 18. # def Unti(list1=[]): # for i in range(len(list1)): # if i >= len(list1) / 2: # break # x = list1[i] # list1[i] = list1[len(list1) - 1 - i] # list1[len(list1) - 1 - i] = x # # # list1 = [1, 2, 3, 4,5] # Unti(list1) # print(list1) # 19. # list1 = [1, 2, 3, 4, 5] # print(max(list1)) # 20. # list1 = [1, 2, 3, 4, 5] # print(min(list1)) # 21. # def inSert(list1=[], pos=0, str1=" "): # list1.insert(pos - 1, str1) # # # list1 = [1, 2, 3] # inSert(list1, 1, "a") # print(list1) # 22. # def delete(list1=[], pos=0): # del list1[pos] # # # list1 = [1, 2, 3] # delete(list1, 1) # print(list1) # 23. # import random # # # def guess(ans=0, a=0): # num = int(input("请输入你的答案:")) # for i in range(a): # if num == ans: # print("您的答案正确") # print("你一共猜了%i次" % (i + 1)) # break # elif num > ans: # num = int(input("大了,继续猜:")) # elif num < ans: # num = int(input("小了,继续猜:")) # # # ans = random.randint(0, 100) # guess(ans, 5) # print("答案为:", ans)
true
7dda4f6c093332f6191bd0bb9769983169f6af2d
Python
cuihantao/OpalApiControl
/OpalApiControl/signals/signalcontrol.py
UTF-8
10,021
2.59375
3
[]
no_license
#*************************************************************************************** #Description # Access Simulink signal control for changing values in Real-Time # Model must be compiled and connected before signal control is granted #*************************************************************************************** #*************************************************************************************** # Modules #*************************************************************************************** from OpalApiControl.config import * import OpalApiControl.system # from OpalApiControl.system import acquire import collections #*************************************************************************************** # Globals #*************************************************************************************** #*************************************************************************************** # Main #******* def setControlSignals(signalIDS,newSignalValues): """Change signal values by signal subsystem names signalNames can by a tuple (name1,name2....,nameN) or a single name newSignalValues can also by a tuple (newValue1,newValue2,....newValueN), or a single value. Item indexes in the signal tuple correspond to respective numeric values in the value tuple """ # controlChange = 1 # signalID = 1 OpalApiPy.SetSignalsById(signalIDS,newSignalValues) # controlSignalValues = list(OpalApiPy.GetControlSignals(1)) ###REMOVE??? # newSignalValues = list(newSignalValues) # # # print"signalChange: %s" %signalChange # print"newsignalvalues %s" %newSignalValues # num = 0 # for newVals in signalIDS: # controlSignalValues[newVals-1] = newSignalValues[num] # num+=1 # # newSignalValuesList = tuple(controlSignalValues) # print("SignalChange: " , controlSignalValues) # # OpalApiPy.SetControlSignals(controlChange, newSignalValuesList) # print("Signal:{} New Signal Value:{}".format(signalIDS, newSignalValues)) #Release All Control Signals # controlChange = 0 # OpalApiPy.GetSignalControl(controlChange, 0) def showControlSignals(): """Displays available subSystems along with their ID and value. Read-Write Control Signals # Returns a Dictionary of key-value (ID,VALUE) for each signal""" subSystemSignals = OpalApiPy.GetControlSignalsDescription() systemList = [subSystemSignals] print("****************Available Signals******************") sigcount = 1 iDList = [] for systems in systemList: sigcount =+1 systemInfo = systems for signal in systemInfo: signalType, subSystemId, path, signalName, reserved, readonly, value = signal iDList.append(subSystemId) print("SubSystem Name:{} SubSystemID:{} SignalName:{} Value:{}".format(path, subSystemId, signalName, value)) # num = 1 # signalDict = dict.fromkeys(iDList) # for item in list(OpalApiPy.GetControlSignals(1)): # signalDict[num] = item # num+=1 # # return signalDict def getControlSignalsDict(): """"# Returns a Dictionary of key-value (ID,VALUE) for each control signal. Model must be loaded Read-Write Control Signals""" # subSystemSignals = OpalApiPy.GetControlSignalsDescription() # systemList = [subSystemSignals] iDList = [] num = 1 signalDict = dict.fromkeys(iDList) for item in list(OpalApiPy.GetControlSignals(1)): signalDict[num] = item num += 1 return signalDict def numControlSignals(): """Returns number of controllable signals in model.Model must be loaded""" count = 0 for num in OpalApiPy.GetControlSignals(1): count +=1 return count def getSignalsDict(): """Returns a dictionary of key-value(ID,VALUE) for signals(NOT control signals) Read-Only Dynamic Signals""" allSignals = list(OpalApiPy.GetSignalsDescription()) # print("signal list before cut: ", allSignals) # Remove control signals from list numControl = numControlSignals() del allSignals[:numControl] dynValueList = [] for signalList in allSignals: signal = [signalList] for spec in signal: signalType, signalId, path, signalName, reserved, readonly, value = spec if (signalType == 1): dynValueList.append(value) iDList = [] num = 1 signalDict = dict.fromkeys(iDList) for item in list(dynValueList): signalDict[numControl+num] = item # start at ID, but can start at 1 if needed. num += 1 return signalDict def showSignals(): """Displays a list of signals(non-control signals) by Name, ID and Value Read-Only Dynamic Signals""" allSignals = list(OpalApiPy.GetSignalsDescription()) # print("signal list before cut: ", allSignals) #Remove control signals from list numControl = numControlSignals() del allSignals[:numControl] dynSignalList = [] for signalList in allSignals: signal = [signalList] for spec in signal: signalType, signalId, path, signalName, reserved, readonly, value = spec if(signalType == 1): dynSignalList.append(signal) print("Signal Name:{} SignalID:{} Value:{}".format(path, signalId, value)) def accessAllSignals(): ######Might not be needed since set signal overrides signalControl """"Gives user access to models's control signals. One client API granted signal control at a time""" subsystemId = 0 # 0 takes control of all subsystems signalControl = 0 # requests signal control when value == 1 # Connect to model if connection is not already made acquire.connectToModel() modelState,realTimeMode = OpalApiPy.GetModelState() try: if(modelState == OpalApiPy.MODEL_RUNNING): # Access signal control signalControl = 1 OpalApiPy.GetSignalControl(subsystemId,signalControl) print "Signal control accessed" else: print "Model state not ready for signal access" finally: print "Release signal control after changing values" def releaseAllSignals(): """Releases all signal controls""" OpalApiPy.GetSignalControl(0,0) print "All signal controls released" def releaseSignal(): #### Might not be needed """Release subsystem by subsystem Id (one value at a time for now)""" subSystemList = OpalApiPy.GetSubsystemList() for subSystemInfo in subSystemList: print ("Subsystems:", subSystemInfo) subSystemName, subSystemId, nodeName = subSystemInfo print ("Subsystem Name:{} Subsystem ID:{} NodeName:{}".format(subSystemName, subSystemId, nodeName)) chooseId = (int(raw_input("Choose subsystem Id to be released: "))) OpalApiPy.GetSignalControl(int(chooseId),0) print "Subsystem %s control released." % chooseId def accessSignal(): ######Might not be needed. setSignal accesses signal control """Access subsystem by subsystem Id (one value at a time for now)""" acquire.connectToModel() subSystemList = OpalApiPy.GetSubsystemList() # Displays available subSystems along with their ID and value. subSystemSignals = OpalApiPy.GetControlSignalsDescription() systemList = [subSystemSignals] print("****************Available Signals******************") for systems in systemList: systemInfo = systems for signal in systemInfo: signalType, subSystemId, path, signalName, reserved, readonly, value = signal print("SubSystem Name:{} SubSystemID:{} SignalName:{} Value:{}".format(path,subSystemId,signalName,value)) chooseId = (int(raw_input("Choose subsystem Id to be accessed: "))) OpalApiPy.GetSignalControl(chooseId, 1) print "Subsystem %s control accessed." %chooseId signalType, subSystemId, path, label, reserved, readonly, value = subSystemSignals[chooseId-1] print("Subsystem Name:{} Signal Name:{} SignalID:{} ReadOnly:{} Value:{}".format(path,label,chooseId,readonly,value)) # def setControlSignal(signalId,newSignalValue): ###REMOVE??? # """Change signal values by signal subsystem ID, # newSignal values takes tuple of values mapped to each signal of the chosen subsystem # in consecutive order as specified by the sc_user_interface list""" # controlChange = 1 # # # accessSignal() # # OpalApiPy.SetSignalsByName(signalNames,newSignalValues) ###REMOVE # print" SignalID:%s" %signalId # controlSignalValues = list(OpalApiPy.GetControlSignals(1)) # print"Control Sig Values:%s" %controlSignalValues # controlSignalValues[signalId-1] = newSignalValue # # OpalApiPy.SetSignalsById(signalId,tuple(controlSignalValues)) # print("Signal:{} New Signal Value:{}".format(signalId,newSignalValue)) # # #Release Signal Controls # controlChange = 0 # OpalApiPy.GetSignalControl(controlChange,signalId) # # def setSignals(): ##CANT SET THESE!!! ADD ARGUMENTS ###NOT NEEDED,CAN USE TO RETURN OTHER SIGNAL VALUES (NONCONTROL SIGNALS) # """ # """ # # # # signalInfo = OpalApiPy.GetSignalsDescription() # # for signalList in signalInfo: # signal = [signalList] # for spec in signal: # signalType,signalId,path,signalName,reserved,readonly,value = spec # print("Signal Name:{} SignalID:{} Value:{}".format(path,signalId,value)) # # OpalApiPy.GetSignalControl(1,0) # controlSignalValues = OpalApiPy.GetControlSignals(1) # # OpalApiPy.SetSignalsById((1,4),(300,100)) # print("**************Values Changed****************") # # for signalList in signalInfo: # signal = [signalList] # for spec in signal: # signalType,signalId,path,signalName,reserved,readonly,value = spec # print("Signal Name:{} SignalID:{} Value:{}".format(path,signalId,value))
true
6205837a751fa9b19e2a25abe1648a634c54d708
Python
NelsonGomesNeto/Competitive-Programming
/Competitions/IEEExtreme/MiniXtremeR9 2020/Number Mind/debugger.py
UTF-8
380
2.84375
3
[]
no_license
import os import time from random import randint from filecmp import cmp os.system("g++ code.cpp -o test -std=c++17") while True: f = open("big", "w") a = [randint(0, 9) for i in range(12)] f.close() start_time = time.time() os.system("./test < big") total_time = time.time() - start_time if total_time > 0.5: break print("Passou")
true
8cf9e952b9c42f6bd8d456f0dd6b16210b572e12
Python
cataluna84/hpp-book
/high_performance_python_2e/06_matrix/diffusion_2d/diffusion_scipy.py
UTF-8
817
2.828125
3
[]
no_license
#!/usr/bin/env python3 import time from numpy import add, multiply, zeros from scipy.ndimage.filters import laplace try: profile except NameError: profile = lambda x: x grid_shape = (640, 640) def laplacian(grid, out): laplace(grid, out, mode="wrap") @profile def evolve(grid, dt, out, D=1): laplacian(grid, out) multiply(out, D * dt, out) add(out, grid, grid) def run_experiment(num_iterations): scratch = zeros(grid_shape) grid = zeros(grid_shape) block_low = int(grid_shape[0] * 0.4) block_high = int(grid_shape[0] * 0.5) grid[block_low:block_high, block_low:block_high] = 0.005 start = time.time() for i in range(num_iterations): evolve(grid, 0.1, scratch) return time.time() - start if __name__ == "__main__": run_experiment(500)
true
a3d27d7004e68c752bfe33e325cb9880ce671406
Python
salvadorhm/java_sintaxis
/rule_00.py
UTF-8
1,031
3.640625
4
[]
no_license
import string class OpenClose: def n__init__(self): pass def validate(self,file): open=('{','[','(') close=('}',']',')') signs=[] for line in file: for letter in line: if letter in open: signs.append(letter) elif letter in close: try: char = signs.pop() except : print "Error en sintaxis 001: se cerro {} sin abrirse previamente".format(letter) print line exit() if char == chr(ord(letter) - 1) or char == chr(ord(letter) - 2): char else: print "Error en sintaxis 002: se debe cerrar {}".format(char) print line exit() if len(signs) > 0: print "Error de sintaxis 003: falta cerrar {}".format(signs[0]) exit()
true
d6ea5223097016ff4b0f76736e637472c373fb51
Python
UmutOrman/hackerrank
/python/numpy/mean_var_std.py
UTF-8
277
2.75
3
[]
no_license
import numpy numpy.set_printoptions(sign=' ') n,m = map(int, raw_input().strip().split()) a = [] for i in range(n): a.append(map(int, raw_input().strip().split())) arrA = numpy.array(a) print numpy.mean(arrA, 1) print numpy.var(arrA, 0) print numpy.std(arrA, None)
true
5e7bc880a40b761246dfb4f270c1b9836038b772
Python
ghomasHudson/graphVisualiser
/MainProgram.py
UTF-8
93,268
2.671875
3
[]
no_license
# -*- coding: cp1252 -*- #============================================================================== # Graph Algorirthm Program #============================================================================== #------------------------------------------------------------------------------ # Import required modules # math: provides link to the OS # random: provides file handling # Tkinter: provides UI framework # tkk: provides more UI widgets # pickle: provides file packing / unpacking #------------------------------------------------------------------------------ import math import random import sys import os from tkinter import filedialog as tkFileDialog from tkinter import messagebox as tkMessageBox from tkinter import * from tkinter import ttk import pickle import operator import copy #Import the parts of the program from arcViewObj import * from matrixViewObj import * from graphObj import * from kruskalObj import * from primObj import * from djikstraObj import * from chinesePostmanObj import * from nearestNObj import * from lowerBoundObj import * from dfsObj import * #------------------------------------------------------------------------------ # Constants #------------------------------------------------------------------------------ VERSION = "1.0.1" PROGRAM_NAME = "GraphAlgori" FILE_EXTENSION = ".grph" RECENT_FILES_NAME = "recent.dat" HELP_FILE = "help.pdf" CONFIG_NAME = "config.dat" #------------------------------------------------------------------------------ # Global variable declarations #------------------------------------------------------------------------------ def globalVars(): global coordClicked global newNode global shift global tempArcs global connected global myKruskal global myPrim global myDj global myNearestN global myLowerB global myCPostman coordClicked = None #variable holding index position of clicked node newNode = True shift = False tempArcs = [None,None,None] connected = None myKruskal=None myPrim=None myDj = None myNearestN = None myLowerB = None myCPostman = None globalVars() #------------------------------------------------------------------------------ # Class definitions (UI elements) # (other classes are defined in seperate files #------------------------------------------------------------------------------ #Undo Redo class UndoRedo(object): def __init__(self): self.undoStack = [] self.redoStack = [] self.stackLength = 5 def lengthCheck(self): if len(self.undoStack) > self.stackLength: del self.undoStack[0] if len(self.redoStack) > self.stackLength: del self.redoStack[0] def undo(self,event=None): """Undoes actions""" #gets graph object from undo stack global myGraph if self.undoStack != []: theFile = pickle.dumps(myGraph) graph = pickle.loads(theFile) self.redoStack.append(graph) clear() myGraph = self.undoStack.pop() #redraw graph: for i in range(0,myGraph.getNumNodes()): drawNode(i) for j in myGraph.neighbors(i): drawArc(i,j) #update other UI elements: myMatrixView.update(myGraph) myArcView.update(myGraph) self.lengthCheck() def redo(self,event=None): """redoes actions""" #gets graph object from redo stack global myGraph if self.redoStack != []: theFile = pickle.dumps(myGraph) graph = pickle.loads(theFile) self.undoStack.append(graph) clear() myGraph = self.redoStack.pop() #redraw graph: for i in range(0,myGraph.getNumNodes()): drawNode(i) for j in myGraph.neighbors(i): drawArc(i,j) #update other UI elements: myMatrixView.update(myGraph) myArcView.update(myGraph) self.lengthCheck() def add(self): """adds a snapshot of the graph to undo stack""" theFile = pickle.dumps(myGraph) graph = pickle.loads(theFile) self.undoStack.append(graph) self.redoStack = [] self.lengthCheck() def clear(self): self.undoStack = [] self.redoStack = [] #Menus object class Menus(Frame): """ Creates menu bar and events """ def __init__(self, parent): global myMatrixView,unRedo self.recentFiles = [] self.parent = parent self.filePath = "Untitled"+FILE_EXTENSION parent.title(os.path.split(self.filePath)[-1][0:-len(FILE_EXTENSION)] + " - " + PROGRAM_NAME) Frame.__init__(self, parent) self.parent = parent menubar = Menu(self.parent) self.parent.config(menu=menubar) #FILE MENU fileMenu = Menu(menubar,tearoff=0) fileMenu.add_command(label="New",underline=0, command=self.newDoc, accelerator="Ctrl+N") fileMenu.add_command(label="Open",underline=0, command=self.openFileDialog, accelerator="Ctrl+O") self.recentMenu = Menu(fileMenu,tearoff=0) fileMenu.add_cascade(label="Recent Files",underline=0, menu=self.recentMenu) fileMenu.add_separator() fileMenu.add_command(label="Save",underline=0, command=self.saveFile, accelerator="Ctrl+S") fileMenu.add_command(label="Save As..",underline=5, command=self.saveAsFile, accelerator="Ctrl+Shift+S") fileMenu.add_separator() exportMenu = Menu(fileMenu,tearoff=0) exportMenu.add_command(label="Export Current Graph",underline=7, command=self.exportAs) exportMenu.add_command(label="Export Algorithm Sequence",underline=7, command=self.exportSequence) fileMenu.add_cascade(label="Export",underline=0, menu=exportMenu) fileMenu.add_separator() fileMenu.add_command(label="Exit",underline=1, command=self.onExit, accelerator="Ctrl+Q") menubar.add_cascade(label="File", menu=fileMenu,underline=0) #EDIT MENU editMenu = Menu(menubar,tearoff=0) editMenu.add_command(label="Undo",underline=0,command=unRedo.undo, accelerator="Ctrl+Z") editMenu.add_command(label="Redo",underline=0,command=unRedo.redo, accelerator="Ctrl+Shift+Z") editMenu.add_separator() editMenu.add_command(label="Preferences",underline=0,command=self.preferences, accelerator="Ctrl+Shift+P") menubar.add_cascade(label="Edit", menu=editMenu,underline=0) #VIEW MENU viewMenu = Menu(menubar,tearoff=0) viewMenu.add_checkbutton(label="Matrix",underline=0,command=togMatrix,var=myMatrixView.visible,accelerator="Ctrl+M") viewMenu.add_checkbutton(label="Arcs",underline=0,command=togArcView,var=myArcView.visible, accelerator="Ctrl+A") self.orders = BooleanVar() viewMenu.add_checkbutton(label="Orders",underline=1,command=self.togOrders,var=self.orders, accelerator="Ctrl+R") viewMenu.add_separator() viewMenu.add_command(label="Graph Stats",underline=6,command=self.graphStats, accelerator="Ctrl+T") menubar.add_cascade(label="View", menu=viewMenu,underline=0) #HELP MENU helpMenu = Menu(menubar,tearoff=0) helpMenu.add_command(label="Help",underline=0,command=self.openHelp, accelerator="F1") helpMenu.add_separator() helpMenu.add_command(label="About",underline=0,command=self.about) menubar.add_cascade(label="Help", menu=helpMenu,underline=0) #KEYBOARD SHORTCUTS # file menu self.bind_all("<Control-n>",self.newDoc) self.bind_all("<Control-o>",self.openFile) self.bind_all("<Control-s>",self.saveFile) self.bind_all("<Control-Shift-s>",self.saveAsFile) self.bind_all("<Control-q>",self.onExit) # edit menu self.bind_all("<Control-z>",unRedo.undo) self.bind_all("<Control-Z>",unRedo.redo) self.bind_all("<Control-P>",self.preferences) # view menu self.bind_all("<Control-m>",togMatrix) self.bind_all("<Control-a>",togArcView) self.bind_all("<Control-r>",self.togOrders) self.bind_all("<Control-t>",self.graphStats) # help menu self.bind_all("<F1>",self.openHelp) root.protocol("WM_DELETE_WINDOW", self.onExit) self.updateRecents() def exportSequence(self,event=None): options = {} options['parent'] = self options['defaultextension'] = ".jpg" options['filetypes'] = [("Bitmap",(".bmp")), ("GIF",(".gif")), ("JPEG",(".jpg",".jpe",".jpeg")), ("PDF",(".pdf")), ("TIFF",(".tif",".tiff")), ("PNG",(".png")) ] filePath = tkFileDialog.asksaveasfilename(**options) #creates file browseR if filePath != "": filePath = str(filePath) path = filePath[:filePath.index(".")]+"/" name = filePath.split("/")[-1] name = name[:name.index(".")] os.mkdir(path) global control finished = False i = 0 while not finished: i+=1 control.nextStep() self.exportImage(path+name+str(i)+filePath[filePath.index("."):]) if control.algorithmVar.get() == "Kruskal's": if myKruskal == None: finished = True elif control.algorithmVar.get() == "Prim's": if myPrim == None: finished = True elif control.algorithmVar.get() == "Djikstra's": if myDj == None: finished = True elif control.algorithmVar.get() == "Chinese Postman": if myCPostman == None: finished = True elif control.algorithmVar.get() == "TSP- Nearest Neighbor": if myNearestN == None: finished = True elif control.algorithmVar.get() == "TSP - Lower Bound": if myLowerB == None: finished = True else: finished = True def exportAs(self,event=None): #Set standard diologe options: options = {} options['parent'] = self options['defaultextension'] = ".jpg" options['filetypes'] = [("Bitmap",(".bmp")), ("GIF",(".gif")), ("JPEG",(".jpg",".jpe",".jpeg")), ("PDF",(".pdf")), ("TIFF",(".tif","tiff")), ("PNG",(".png")) ] filename = tkFileDialog.asksaveasfilename(**options) #creates file browseR if filename != "": self.exportImage(filename) def exportImage(self,filename): if myGraph.getNumNodes() == 0: return global canvas from PIL import Image, ImageDraw,ImageFont #define color constants colors = {} colors["white"] = (255, 255, 255) colors["black"] = (0, 0, 0) colors["grey"] = (150, 150, 150) colors["green"] = (0, 255, 0) colors["red"] = (255, 0, 0) colors["#28D13B"] = (40, 209, 59) colors["orange"] = (255,165,0) #setup image rootWidth = int(self.parent.geometry().split('+')[0].split('x')[0])*2 rootHeight = int(self.parent.geometry().split('+')[0].split('x')[1])*2 size = (rootWidth,rootHeight) image = Image.new("RGB",size, colors["white"]) draw = ImageDraw.Draw(image) #Draw the arcs for i in range(0,myGraph.getNumNodes()): for j in myGraph.neighbors(i): iC = list(myGraph.getCoords(i)) iC[0] = iC[0]*2 iC[1] = iC[1]*2 jC = list(myGraph.getCoords(j)) jC[0] = jC[0]*2 jC[1] = jC[1]*2 arcCol = canvas.itemcget("a"+"%02d" % (i)+"%02d" % (j), "fill") if arcCol != "": if arcCol == "black": draw.line((iC[0], iC[1], jC[0], jC[1]), fill=colors[arcCol]) else: for w in range(0,5): draw.line((iC[0]-w, iC[1], jC[0]-w, jC[1]), fill=colors[arcCol]) draw.line((iC[0], iC[1]-w, jC[0], jC[1]-w), fill=colors[arcCol]) rX = (iC[0]+jC[0])/2 rY = (iC[1]+jC[1])/2 draw.rectangle((rX-40,rY-20,rX+40,rY+20),fill=colors["black"]) weight = str(myGraph.getArc(i,j)) try: tFont = ImageFont.load("timR18.pil") draw.text((rX-len(weight)*6,rY-12),weight,fill=colors["white"],font=tFont) except: draw.text((rX-len(weight)*6,rY-12),weight,fill=colors["white"]) minX = 9999999 minY = 9999999 maxX = 0 maxY = 0 #Draw the nodes for i in range(0,myGraph.getNumNodes()): iC = list(myGraph.getCoords(i)) iC[0] = iC[0]*2 iC[1] = iC[1]*2 #Find top-left and bottom-right nodes if minX > iC[0]: minX = iC[0] if minY > iC[1]: minY = iC[1] if maxX < iC[0]: maxX = iC[0] if maxY < iC[1]: maxY = iC[1] nodeCol = canvas.itemcget("n"+"%02d" % (i), "outline") draw.ellipse((iC[0]-30,iC[1]-30,iC[0]+30,iC[1]+30),fill=colors[nodeCol]) nodeCol = canvas.itemcget("n"+"%02d" % (i), "fill") draw.ellipse((iC[0]-27,iC[1]-27,iC[0]+27,iC[1]+27),fill=colors[nodeCol]) try: draw.text((iC[0]+25,iC[1]+25),myGraph.getLetter(i),fill=colors["black"],font=tFont) except: draw.text((iC[0]+25,iC[1]+25),myGraph.getLetter(i),fill=colors["black"]) if menu.orders.get(): try: draw.text((iC[0]+25,iC[1]-50),str(myGraph.getOrder(i)),fill=colors["black"],font=tFont) except: draw.text((iC[0]+25,iC[1]-50),str(myGraph.getOrder(i)),fill=colors["black"]) for d in canvas.find_withtag("dj"): i = int(canvas.gettags(d)[1][-2:]) iC = list(myGraph.getCoords(i)) iC[0] = iC[0]*2 iC[1] = iC[1]*2 if canvas.gettags(d)[1][2] == "B": draw.rectangle((iC[0]+50,iC[1]+50,iC[0]+200,iC[1]+125),fill=colors["white"],outline=colors["black"]) draw.line((iC[0]+125,iC[1]+50,iC[0]+125,iC[1]+90),fill=colors["black"]) draw.line((iC[0]+50,iC[1]+90,iC[0]+200,iC[1]+90),fill=colors["black"]) elif canvas.gettags(d)[1][2] == "O": draw.text((iC[0]+85,iC[1]+57),str(myDj.getNode(i).getOrderOfLbl()),fill=colors["black"],font=tFont) elif canvas.gettags(d)[1][2] == "P": draw.text((iC[0]+157,iC[1]+57),str(myDj.getNode(i).getPerminantLbl()),fill=colors["black"],font=tFont) elif canvas.gettags(d)[1][2] == "T": x = iC[0]+120-(len(myDj.getNode(i).getTempLbls())*9) #tempLbls tempLbls = myDj.getNode(i).getTempLbls() tempLbls = list(map(str,tempLbls)) tempLbls = " ".join(tempLbls) draw.text((x,iC[1]+93),str( tempLbls),fill=colors["black"],font=tFont) desc = control.myDescBox.canvas.itemcget(control.myDescBox.desc,"text") step = control.myDescBox.canvas.itemcget(control.myDescBox.step,"text") if desc != "Choose an algorithm to begin": draw.text((minX-90,minY-200),step,fill=colors["black"],font=tFont) draw.text((minX,minY-180),desc.split("\n")[0],fill=colors["black"],font=tFont) if len(desc.split("\n")) == 2: draw.text((minX,minY-150),desc.split("\n")[1],fill=colors["black"],font=tFont) #Crop and save image image = image.crop((minX-100,minY-200,maxX+300,maxY+200)) image.save(filename) def togOrders(self,event=None): global myGraph if event != None: self.orders.set(not self.orders.get()) for i in range(0,myGraph.getNumNodes()): drawNode(i) def new(self,event=None): """Creates new graph""" clear() unRedo.clear() self.filePath = "Untitled"+FILE_EXTENSION root.title(os.path.split(self.filePath)[-1][0:-len(FILE_EXTENSION)] + " - " + PROGRAM_NAME) def onExit(self,event=None): """ Handles 'Do you want to save?' alert when window is closed """ if "*" in root.title(): #If the graph has been changed #Create alert: answer = tkMessageBox.askyesnocancel("Save Changes", "Do you want to save your changes to "+os.path.split(self.filePath)[-1][0:-len(FILE_EXTENSION)]+"?") if answer == None: #"Cancel" return if answer: #"Yes" self.saveFile() #Close window: root.destroy() def openFileDialog(self,event=None): """Creates an 'open file dialoge'""" global FILE_EXTENSION options = {} options['parent'] = self try: global CONFIG_NAME theFile = open(CONFIG_NAME,'rb') #open connection options['initialdir'] = pickle.load(theFile)[0] if options['initialdir'] == "/examples": options['initialdir'] = "examples" theFile.close() except: options['initialdir'] = "examples" options['defaultextension'] = FILE_EXTENSION options['filetypes'] = [("graph files",FILE_EXTENSION)] self.filePath = tkFileDialog.askopenfilename(**options) self.openFile(self.filePath) def openFile(self,fileToOpen): """Opens the file: fileToOpen""" global myGraph,myMatrixView,myArcView,FILE_EXTENSION if fileToOpen != "": #if cancel not pressed if "*" in root.title(): #If the graph has been changed #Create alert: answer = tkMessageBox.askyesnocancel("Save Changes", "Do you want to save your changes to "+root.title()[1:-14]+"?") if answer: #"Yes" self.saveFile() try: #attempt to open file theFile = open(fileToOpen,'rb') #open connection clear() #clear canvas myGraph = pickle.load(theFile) #redraw graph: for i in range(0,myGraph.getNumNodes()): drawNode(i) for j in myGraph.neighbors(i): drawArc(i,j) #update other UI elements: myMatrixView.update(myGraph) myArcView.update(myGraph) control.algorithmVar.set(myGraph.AlgorithmUsed) #set algorithm to last used #change file path,title and close file self.filePath = fileToOpen root.title(os.path.split(fileToOpen)[-1][0:-len(FILE_EXTENSION)] + " - " + PROGRAM_NAME) theFile.close() self.addRecentFile(self.filePath) except: tkMessageBox.showwarning("Open file", "Cannot open this file:\n%s" % os.path.split(fileToOpen)[-1]) self.newDoc() def saveAsFile(self,event=None): """Creates a 'save file' dialoge'""" global myGraph #Set standard diologe options: options = {} options['parent'] = self options['defaultextension'] = FILE_EXTENSION options['filetypes'] = [("graph files",FILE_EXTENSION)] options['initialfile'] = os.path.split(self.filePath)[-1][0:-len(FILE_EXTENSION)] #if not an existing file, go to it's location if self.filePath != "Untitled"+FILE_EXTENSION: options['initialdir'] = self.filePath self.filePath = tkFileDialog.asksaveasfilename(**options) #creates file browser self.save() def saveFile(self,event=None): """For 'Save' option""" #if file is not prev saved, open file brower if os.path.split(self.filePath)[-1][0:-len(FILE_EXTENSION)] == "Untitled": self.saveAsFile() else: self.save() def save(self): """uses pickle to save the graph""" if self.filePath != "": theFile = open(self.filePath,"wb") pickle.dump(myGraph,theFile) root.title(os.path.split(self.filePath)[-1][0:-len(FILE_EXTENSION)] + " - " + PROGRAM_NAME) theFile.close() self.addRecentFile(self.filePath) def onEdit(self): """Adds '*' when graph is changed""" root.title("*" + os.path.split(self.filePath)[-1][0:-len(FILE_EXTENSION)] + " - " + PROGRAM_NAME) unRedo.add() def graphStats(self,event=None): """Opens graph stats dialog by creating an aboutDialog object instance""" graphStatsDialog(self.parent) def about(self): """Opens about dialog by creating an aboutDialog object instance""" aboutDialog(self.parent) def preferences(self,event=None): """Opens about dialog by creating an prefDialog object instance""" prefDialog(self.parent) def newDoc(self,event=None): if "*" in root.title(): #If the graph has been changed #Create alert: answer = tkMessageBox.askyesnocancel("Save Changes", "Do you want to save your changes to "+os.path.split(self.filePath)[-1][0:-len(FILE_EXTENSION)]+"?") if answer == None: #"Cancel" return if answer: #"Yes" self.saveFile() clear() unRedo.clear() self.filePath = "Untitled"+FILE_EXTENSION root.title(os.path.split(self.filePath)[-1][0:-len(FILE_EXTENSION)] + " - " + PROGRAM_NAME) def addRecentFile(self,fileToAdd): """ Adds a opened/saved file to the recent files list. This is stored using pickle """ global RECENT_FILES_NAME theFile = open(RECENT_FILES_NAME,"wb") #opens conection if self.recentFiles == []: # if blank creates default blank strings self.recentFiles = ["","",""] if fileToAdd in self.recentFiles: #if already in list, delete existing del self.recentFiles[self.recentFiles.index(fileToAdd)] else: #else delete oldest item del self.recentFiles[0] self.recentFiles.append(fileToAdd)#appends new file #Save to file and update pickle.dump(self.recentFiles,theFile) theFile.close() self.updateRecents() def updateRecents(self): """ Updates recent files menu""" try: theFile = open(RECENT_FILES_NAME,"rb") if theFile != None: self.recentFiles = pickle.load(theFile) theFile.close() for i in range(0,3): self.recentMenu.delete(i) if self.recentFiles[2] != "": self.recentMenu.add_command(label=self.recentFiles[2],command=lambda:self.openFile(self.recentFiles[2])) if self.recentFiles[1] != "": self.recentMenu.add_command(label=self.recentFiles[1],command=lambda:self.openFile(self.recentFiles[1])) if self.recentFiles[0] != "": self.recentMenu.add_command(label=self.recentFiles[0],command=lambda:self.openFile(self.recentFiles[0])) except IOError: pass def openHelp(self,event=None): try: global CONFIG_NAME theFile = open(CONFIG_NAME,'rb') #open connection helpPath = pickle.load(theFile)[1] theFile.close() except: helpPath = "help.pdf" if os.path.isfile(helpPath): import webbrowser webbrowser.open(helpPath) else: tkMessageBox.showwarning("No Help File","The help file: "+helpPath+" cannot be found.") class aboutDialog(Toplevel): """creates the 'about' popup""" def __init__(self, parent): global PROGRAM_NAME,VERSION #Creates a box with the following properties: Toplevel.__init__(self, parent) self.resizable(0,0) #not resizable self.transient(parent) #minimizes with parent self.grab_set() #sets focus on self self.title("About") x = parent.winfo_rootx() y = parent.winfo_rooty()-40 height = parent.winfo_height() width = parent.winfo_width() self.geometry("120x120+%d+%d" % (x+width/2-60,y+height/2-60)) #Content: l1 = Label(self,text=PROGRAM_NAME,font=("Helvetica", 16)) l1.pack() l2 = Label(self,text=chr(169)+" 2014 T. Hudson") l2.pack() l3 = Label(self,text="V"+VERSION) l3.pack() b1 = ttk.Button(self,text="Close",command=self.close) b1.focus_set() b1.pack(pady=10) #adds event bindings self.bind("<Return>",self.close) self.wait_window(self) def close(self,event=None): """destroy popup when closed button pressed""" self.destroy() class graphStatsDialog(Toplevel): """creates the 'graph stats' popup""" def __init__(self, parent): global myGraph #Creates a box with the following properties: Toplevel.__init__(self, parent) self.resizable(0,0) #not resizable self.transient(parent) #minimizes with parent self.grab_set() #sets focus on self self.title("Stats") x = parent.winfo_rootx() y = parent.winfo_rooty()-40 height = parent.winfo_height() width = parent.winfo_width() self.geometry("180x200+%d+%d" % (x+width/2-90,y+height/2-100)) #Get Stats: if myGraph.isEulerian(): l1 = Label(self,text="Eulerian") elif myGraph.isSemiEulerian(): l1 = Label(self,text="Semi-Eulerian") else: l1 = Label(self,text="Non-Eulerian") myDfs = dfs(myGraph) if myDfs.connected(): l2 = Label(self,text="Connected") else: l2 = Label(self,text="Non-Connected") l3 = Label(self,text=str(myGraph.getNumNodes())) arcsOrig = myGraph.arcs() arcs = [] #remove duplicates (for non-directed arcs) for i in range(0,len(arcsOrig)): if (arcsOrig[i][0],(arcsOrig[i][1][1],arcsOrig[i][1][0])) not in arcs: arcs.append(arcsOrig[i]) A = len(arcs) l4 = Label(self,text=str(A)) R = A+2-myGraph.getNumNodes() l5 = Label(self,text=str(R)) l6 = Label(self,text=str(myDfs.numConnectedComponants())) #Draw the layout headingFont = ("Arial",9,"bold") self.rowconfigure(0, weight=1) Label(self,text="Type:",font=headingFont).grid(column=0, row=1, sticky=(N,E)) l1.grid(column=1, row=1, sticky=(N,W), pady=2) l2.grid(column=1, row=2, sticky=(N,W), pady=2) Label(self,text="Nodes:",font=headingFont).grid(column=0, row=3, sticky=(N,E)) l3.grid(column=1, row=3, sticky=(N,W), pady=2) Label(self,text="Arcs:",font=headingFont).grid(column=0, row=4, sticky=(N,E)) l4.grid(column=1, row=4, sticky=(N,W), pady=2) if myDfs.connected(): Label(self,text="Regions:",font=headingFont).grid(column=0, row=5, sticky=(N,E)) l5.grid(column=1, row=5, sticky=(N,W), pady=2) Label(self,text=" Connected\n Componants:",font=headingFont).grid(column=0, row=6, sticky=(N,E)) #Label(self,text="Componants:",font=headingFont).grid(column=0, row=7, sticky=(N, W,E,S)) l6.grid(column=1, row=6, sticky=(N,S,W),rowspan=2) b1 = ttk.Button(self,text="Close",command=self.close) b1.focus_set() b1.grid(column=0, row=8,columnspan=3, sticky=(N,W,E,S), padx=20, pady=10) #adds event bindings self.bind("<Return>",self.close) self.wait_window(self) def close(self,event=None): """destroy popup when closed button pressed""" self.destroy() class prefDialog(Toplevel): """creates the 'preferences' popup""" def __init__(self, parent): #Creates a box with the following properties: Toplevel.__init__(self, parent) self.resizable(0,0) #not resizable self.transient(parent) #minimizes with parent self.grab_set() #sets focus on self self.title("Preferences") x = parent.winfo_rootx() y = parent.winfo_rooty()-40 height = parent.winfo_height() width = parent.winfo_width() self.geometry("400x150+%d+%d" % (x+width/2-200,y+height/2-75)) #Content: self.examplesPath = StringVar() self.helpPath = StringVar() try: global CONFIG_NAME theFile = open(CONFIG_NAME,'rb') #open connection paths = pickle.load(theFile) self.examplesPath.set(paths[0]) self.helpPath.set(paths[1]) theFile.close() except: self.helpPath.set("help.pdf") self.examplesPath.set("/examples") #Examples folder l2 = Label(self,text="Examples folder:") l2.grid(row=1, column=0,sticky="W") e2 = ttk.Entry(self,textvariable=self.examplesPath,width=50) e2.grid(row=2, column=0,columnspan=1,sticky="W") b2 = ttk.Button(self,text="Browse",command=self.browseExamples) b2.grid(row=2, column=1,columnspan=1,sticky="W",padx=10) #Help File l3 = Label(self,text="Help File:") l3.grid(row=3, column=0,columnspan=1,sticky="W",pady=(10,0)) e3 = ttk.Entry(self,textvariable=self.helpPath,width=50) e3.grid(row=4, column=0,columnspan=1,sticky="W") b3 = ttk.Button(self,text="Browse",command=self.browseHelp) b3.grid(row=4, column=1,columnspan=1,sticky="W",padx=10) b1 = ttk.Button(self,text="Apply",command=self.close) b1.grid(row=5, column=0,columnspan=3,pady=20) b1.focus_set() #adds event bindings self.bind("<Return>",self.close) self.wait_window(self) def browseExamples(self): options = {} options['parent'] = self options['title'] = 'Choose examples directory' if self.examplesPath.get() != "": options['initialdir'] = self.examplesPath.get() path = tkFileDialog.askdirectory (**options) if path != "": self.examplesPath.set(path) def browseHelp(self): options = {} options['parent'] = self options['defaultextension'] = ".pdf" options['initialfile'] = self.helpPath.get() options['filetypes'] = [("Help Files",(".pdf",".html",".chm"))] path = tkFileDialog.askopenfilename(**options) if path != "": self.helpPath.set(path) def close(self,event=None): """destroy popup when closed button pressed""" global CONFIG_NAME theFile = open(CONFIG_NAME,"wb") #opens conection #Save to file data = [self.examplesPath.get(),self.helpPath.get()] if data[0] == "": data[0] = "/examples" if data[1] == "": data[1] = "help.pdf" pickle.dump(data,theFile) theFile.close() self.destroy() #Controls Class class controls: """Creates toolbar""" def __init__(self,parent): self.parent=parent self.controlsContainer = Frame(parent) self.playbackContainer = Frame(self.controlsContainer) #SCALE #setup style self.scaleVar = IntVar() w = ttk.Scale(self.playbackContainer, from_=0, to=5, orient=HORIZONTAL, variable=self.scaleVar, command=self.slideSnap) w.pack() lblFrame = Frame(self.playbackContainer) slow = Label(lblFrame,text="Slow") fast = Label(lblFrame,text="Fast") slow.pack(side=LEFT,expand=TRUE,padx=20) fast.pack(side=RIGHT,expand=TRUE,padx=20) lblFrame.pack(expand=TRUE) MainButton = ttk.Button(self.playbackContainer,text="Start",command=self.buttonPressed) MainButton.pack() self.algorithmVar = StringVar() self.algorithmVar.set("--Select Algorithm--") self.algorithm = ttk.Combobox(self.controlsContainer, textvariable=self.algorithmVar,state="readonly",takefocus=0) self.algorithm['values'] = ("--Select Algorithm--", "Prim's", "Kruskal's", "Djikstra's", "Chinese Postman", "TSP- Nearest Neighbor", "TSP - Lower Bound" #,"TSP - Tour Improvement", ) self.algorithm.pack(side=LEFT) canvas.bind_all("<<ComboboxSelected>>", self.selectChange) self.playbackContainer.pack(side=LEFT,padx=100,pady=1) self.controlsContainer.grid(column=0, row=0, sticky=(N, W,E,S)) self.myDescBox = descBox(self.controlsContainer) self.myDescBox.pack() self.timer = None def slideSnap(self,x=None): self.scaleVar.set(round(self.scaleVar.get())) def stepDone(self): if self.scaleVar.get() != 0: self.timer = canvas.after((5-self.scaleVar.get())*1000,self.nextStep) def buttonPressed(self): global canvas if self.algorithmVar.get() != "TSP - Tour Improvement" and self.scaleVar.get() != 0: reset() if self.timer != None: canvas.after_cancel(self.timer) self.nextStep() def nextStep(self): """Runs next step of selected algorithm""" global myGraph,control myDfs = dfs(myGraph) labelDeselected() if (myDfs.connected() and not myGraph.isDigraph()) or self.algorithmVar.get() == "--Select Algorithm--": if self.algorithmVar.get() == "--Select Algorithm--": reset() elif self.algorithmVar.get() == "Kruskal's": doKruskal() if myKruskal != None: self.stepDone() elif self.algorithmVar.get() == "Prim's": doPrim() if myPrim != None: self.stepDone() elif self.algorithmVar.get() == "Djikstra's": doDj() if myDj != None: self.stepDone() elif self.algorithmVar.get() == "Chinese Postman": doCPostman() if myCPostman != None: self.stepDone() elif self.algorithmVar.get() == "TSP- Nearest Neighbor": doNearestN() if myNearestN != None: self.stepDone() elif self.algorithmVar.get() == "TSP - Lower Bound": doLowerB() if myLowerB != None: self.stepDone() """elif self.algorithmVar.get() == "TSP - Tour Improvement": doTourImprov() if myTImprov != None: self.stepDone()""" else: control.myDescBox.setText("WARNING",self.algorithmVar.get()+" can only be run on connected non-directed graphs") def selectChange(self,event=None): global myGraph myGraph.AlgorithmUsed = self.algorithmVar.get() myDfs = dfs(myGraph) if self.algorithmVar.get() == "--Select Algorithm--": self.myDescBox.setText("","Choose an algorithm to begin") elif self.algorithmVar.get() != "Djikstra's" and not myDfs.connected(): self.myDescBox.setText(" WARNING","This algorithm only runs on connected graphs") elif myGraph.isDigraph(): self.myDescBox.setText(" WARNING","This algorithm only runs on undirected graphs") else: self.myDescBox.setText("","Press Run to begin the Algorithm") class StatusBar(Frame): def __init__(self, master): Frame.__init__(self, master,border=1, relief=RAISED) self.label = Label(self, anchor=W) self.label2 = Label(self, anchor=W) self.label.pack(side=LEFT) self.label2.pack(side=RIGHT) def setText(self, string): self.label.config(text=string) def setOrder(self,string): self.label2.config(text=string) class descBox(Frame): def __init__(self, master): Frame.__init__(self, master) self.canvas = Canvas(self, border=1, relief=SUNKEN, width=600,height=50,bg="#CCC") self.canvas.pack() self.step = self.canvas.create_text(5,5,font=("Arial",9,"bold"),text="STEP 1",anchor="nw") self.desc = self.canvas.create_text(300,25,text="") self.setText("","Choose an algorithm to begin") def setText(self,step,desc): self.canvas.itemconfig(self.step,text=step) if step == "ERROR" or step == " WARNING": self.canvas.itemconfig(self.step,fill="red") else: self.canvas.itemconfig(self.step,fill="black") self.canvas.itemconfig(self.desc,text=desc) #------------------------------------------------------------------------------ # Canvas Functions #------------------------------------------------------------------------------ def mouseClick(event): """ Handles mouse clicks -Decides whether a node has been clicked on """ global myGraph, mousedown,coordClicked if textOver()!=None: #If clicked on arc weight #select weight: labelDeselected() canvas.focus(textOver()) canvas.select_from(textOver(), 0) canvas.select_to(textOver(), len(canvas.itemcget(textOver(),"text"))-1) coordClicked = None else: #deselect weight: labelDeselected() theNode = nodeOver(myGraph,event.x,event.y) #test if clicked on node if theNode == None: #if clicked on canvas, create a node addCoords(event) else: #else setup for arc drawing labelDeselected() coordClicked = theNode #Updates UI elements: menu.onEdit() myMatrixView.update() myArcView.update() def nodeOver(graph,x,y): """ Gets index of the node at pos (x,y). Returns None if no node is found. """ found = False for i in range(0,graph.getNumNodes()): #interate through nodes coord = graph.getCoords(i) if (abs(x-coord[0]) <30) and (abs(y-coord[1]) <30): #compares mouse click to coords #if click within 30px of node center found = True return i #return node else: if i == (graph.getNumNodes()) and not found: #if didn't click on node return None def textOver(): """ Gets index of the arc weight at pos (x,y). Returns None if no weight is found. """ under = canvas.find_withtag("current") for i in under: tags = canvas.gettags(i) if "b" in tags or "w" in tags: return "w"+tags[1][1:] if "l" in tags: return "l"+tags[1][1:] return None def updateStatus(event): global myGraph if nodeOver(myGraph,event.x,event.y) != None: bar.setText("Node "+myGraph.getLetter(nodeOver(myGraph,event.x,event.y))+": Shift-click to move") bar.setOrder("Order: "+str(myGraph.getOrder(nodeOver(myGraph,event.x,event.y)))) else: bar.setText("For help, press F1") bar.setOrder("") def addCoords(event,y=None): """adds new nodes to the list""" global myGraph,coordClicked if y!=None: x = event coordClicked = None else: x = event.x y = event.y if myGraph.getNumNodes() == 0: global menu menu.onEdit() if coordClicked != None: node1 = myGraph.getCoords(coordClicked) if shift or abs(x-node1[0])<20 or abs(y-node1[1])<20: if abs(x-node1[0]) < abs(y-node1[1]): myGraph.addNode(node1[0],y) else: myGraph.addNode(x,node1[1]) else: myGraph.addNode(x,y) #adds to graph object else: myGraph.addNode(x,y) #adds to graph object reset() #Clears all algorithms drawNode(myGraph.getNumNodes()-1) #draws the node coordClicked = myGraph.getNumNodes()-1 #sets node as clicked def nodeMove(event): """moves node if selected""" global coordClicked,myGraph,newNode,shift if coordClicked != None: #if a node is selected if newNode == False: snapX = event.x snapY = event.y for n in myGraph.neighbors(coordClicked)+myGraph.revNeighbors(coordClicked): nCord = myGraph.getCoords(n) if abs(event.x-nCord[0])<20 or abs(event.y-nCord[1])<20: if abs(event.x-nCord[0]) < abs(event.y-nCord[1]): snapX = nCord[0] else: snapY = nCord[1] else: myGraph.setCoords(coordClicked,snapX,snapY)#update coords in graph obj drawNode(coordClicked) #redraw the node at new pos #redraws the arcs connected to the node: neigh = myGraph.neighbors(coordClicked) revNeighbors = myGraph.revNeighbors(coordClicked) for i in neigh: drawArc(coordClicked,i) for i in revNeighbors: drawArc(i,coordClicked) def addArc(event): """Creates a new arc""" global coordClicked,myGraph,tempArcs,connected,newNode,shift if coordClicked != None and newNode: #if a node is selected #print shift node1 = myGraph.getCoords(coordClicked) if tempArcs == []: #if there is no temp arc, create one tempArcs[0] = canvas.create_line(node1[0],node1[1],event.x,event.y) else: #if there is then update it for i in tempArcs: canvas.delete(i) #deletes existing arcs theNode = nodeOver(myGraph,event.x,event.y) if theNode == None or theNode == coordClicked: #Stops self-loops TEMP if shift or abs(event.x-node1[0])<20 or abs(event.y-node1[1])<20: #Snaps if close to vert/horz or if shift key pressed for i in tempArcs: canvas.delete(i) #deletes existing arcs if abs(event.x-node1[0]) < abs(event.y-node1[1]): tempArcs[0] = canvas.create_line(node1[0],node1[1],node1[0],event.y) else: tempArcs[0] = canvas.create_line(node1[0],node1[1],event.x,node1[1]) else: tempArcs[0] = canvas.create_line(node1[0],node1[1],event.x,event.y) connected = None else: #if between 2 different nodes... for i in tempArcs: canvas.delete(i) #deletes existing arcs node2 = myGraph.getCoords(theNode) connected = theNode if myGraph.getArc(coordClicked,theNode) == None and myGraph.getArc(theNode,coordClicked) == None: #straight arc tempArcs[0] = canvas.create_line(node1[0],node1[1],node2[0],node2[1]) else: #For curved arcs #draw the arc tempArcs[0] = drawCurve(node1[0],node1[1],node2[0],node2[1],True) #repeat for second arc tempArcs[1] = drawCurve(node2[0],node2[1],node1[0],node1[1],False) #cover existing line tempArcs[2] = canvas.create_line(node1[0],node1[1],node2[0],node2[1],fill="white",width=4) canvas.tag_raise("l") canvas.tag_raise("b") canvas.tag_raise("w") canvas.tag_raise("n") def mouseUp(event): """ Handles the event when the mouse button is relesed """ global tempArcs,connected,coordClicked,myGraph,myMatrixView,myArcView,newNode newNode = True #Removes the tempArcs for i in tempArcs: canvas.delete(i) tempArcs = [None,None,None] if textOver()==None: randomW = random.randint(1,10) if connected != None: if myGraph.getArc(connected,coordClicked) == None and myGraph.getArc(coordClicked,connected) == None: #simple arc myGraph.setArc(coordClicked,connected,random.randint(1,10)) else: #multiple arc randWeight = myGraph.getArc(connected,coordClicked) while randWeight == myGraph.getArc(connected,coordClicked ): randWeight = random.randint(1,10) myGraph.setArc(coordClicked,connected,randWeight,True) drawArc(coordClicked,connected) textBox = "w" + "%02d" % (coordClicked) + "%02d" % (connected) canvas.focus(textBox) canvas.select_from(textBox, 0) canvas.select_to(textBox, len(canvas.itemcget(textBox,"text"))-1) elif nodeOver(myGraph,event.x,event.y) == None: #if not connecting 2 nodes, make a new node prev = coordClicked if coordClicked!=None: addCoords(event) myGraph.setArc(prev,myGraph.getNumNodes()-1,randomW) drawArc(prev,myGraph.getNumNodes()-1) textBox = "w" + "%02d" % (prev) + "%02d" % (myGraph.getNumNodes()-1) canvas.focus(textBox) canvas.select_from(textBox, 0) canvas.select_to(textBox, len(canvas.itemcget(textBox,"text"))-1) connected = None coordClicked = None myMatrixView.update() myArcView.update() control.selectChange() def drawNode(pos): """ Draws the graphical represantation of the node pos, in the graph object """ global myGraph,canvas nOpt = {"fill":"grey", "activefill":"black", "disabledoutline":"grey", "state":myGraph.getNodeState(pos) } lOpt = {"disabledfill":"grey", "state":myGraph.getNodeState(pos)} strPos = "%02d" % (pos) coord = myGraph.getCoords(pos) letter = myGraph.getLetter(pos) #letter = pos #TEMP if canvas.find_withtag("n"+strPos) == (): t = canvas.create_oval(coord[0]+15, coord[1]+15, coord[0]-15, coord[1]-15,width=2,tags=("n","n"+strPos),**nOpt) canvas.create_text(coord[0]+20,coord[1]+20,text=letter,tags=("l","l"+strPos),**lOpt) o = canvas.create_text(coord[0]+20,coord[1]-20,text=str(myGraph.getOrder(pos)),tags=("o","o"+strPos),**lOpt) if not menu.orders.get(): canvas.itemconfig(o,state=HIDDEN) if myGraph.isPosUserNode(pos): canvas.itemconfig("l"+strPos,font="Times 10 underline bold") else: canvas.itemconfig("l"+strPos,font="Times 10 normal") else: drawDj(pos) canvas.coords("n"+strPos, coord[0]+15, coord[1]+15, coord[0]-15, coord[1]-15) canvas.coords("l"+strPos,coord[0]+20, coord[1]+20) if myGraph.isPosUserNode(pos): canvas.itemconfig("l"+strPos,font="Times 10 underline bold") else: canvas.itemconfig("l"+strPos,font="Times 10 normal") canvas.coords("o"+strPos,coord[0]+20, coord[1]-20) canvas.itemconfig("o"+strPos,text=str(myGraph.getOrder(pos))) canvas.lift("o"+strPos) if not menu.orders.get(): canvas.itemconfig("o"+strPos,state=HIDDEN) else: canvas.itemconfig("o"+strPos,state=NORMAL) canvas.itemconfig("l"+strPos,text=letter) #Change colour for start and end nodes if myGraph.getStart() == pos: canvas.itemconfig("n"+strPos,outline="#28D13B",state=myGraph.getNodeState(pos)) elif myGraph.getEnd() == pos: canvas.itemconfig("n"+strPos,outline="red",state=myGraph.getNodeState(pos)) else: canvas.itemconfig("n"+strPos,outline="black",state=myGraph.getNodeState(pos)) #update labels for pos in range(0,myGraph.getNumNodes()): strPos = "%02d" % (pos) letter = myGraph.getLetter(pos) #letter = pos # temp canvas.itemconfig("l"+strPos,text=letter,state=myGraph.getNodeState(pos)) def drawArc(n1,n2): """ Draws the graphical represantation of the arc between n1 and n2, in the graph object """ global myGraph aOpt = {"disabledfill":"grey", "state":myGraph.getArcState(n1,n2)} bOpt = {"fill":"black", "disabledfill":"grey", "disabledoutline":"grey", "state":myGraph.getArcState(n1,n2) } wOpt = {"fill":"white"} strN1 = "%02d" % (n1) strN2 = "%02d" % (n2) #draws line representing edge node1 = myGraph.getCoords(n1) node2 = myGraph.getCoords(n2) midx = (node1[0]+node2[0])/2 midy = (node1[1]+node2[1])/2 if myGraph.getArc(n1,n2) == None: return if myGraph.getArc(n2,n1)==myGraph.getArc(n1,n2): #if -----NORMAL ARC----- """if canvas.find_withtag("a"+strN1+strN2) == (): # creates line if line doesn't already exist""" #delete existing arcs canvas.delete("a"+strN2+strN1) canvas.delete("w"+strN2+strN1) canvas.delete("b"+strN2+strN1) canvas.delete("a"+strN1+strN2) canvas.delete("w"+strN1+strN2) canvas.delete("b"+strN1+strN2) weight = myGraph.getArc(n1,n2) #gets weight canvas.create_line(node1[0],node1[1],node2[0],node2[1],tags=("a",("a"+strN1+strN2)),**aOpt) canvas.create_rectangle(midx-20,midy,midx+20,midy+20, tags=("b","b"+strN1+strN2),**bOpt) canvas.create_text(midx, midy+10, text=str(weight),tags=("w","w"+strN1+strN2),**wOpt) canvas.tag_lower("w"+strN1+strN2) canvas.tag_lower("b"+strN1+strN2) canvas.tag_lower("a"+strN1+strN2) """else: #adjust coords of existing arc canvas.itemconfig("a"+strN1+strN2,state=myGraph.getArcState(n1,n2)) canvas.itemconfig("b"+strN1+strN2,state=myGraph.getArcState(n1,n2)) canvas.itemconfig("w"+strN1+strN2,state=myGraph.getArcState(n1,n2)) canvas.coords("a"+strN1+strN2,node1[0],node1[1],node2[0],node2[1]) canvas.coords("b"+strN1+strN2,midx-20, midy+20,midx+20,midy+40) canvas.coords("w"+strN1+strN2,midx, midy+30)""" elif myGraph.getArc(n2,n1)!= None and myGraph.getArc(n1,n2) != None: #if ------MULTIPLE ARC------ #delete existing arcs canvas.delete("a"+strN2+strN1) canvas.delete("w"+strN2+strN1) canvas.delete("b"+strN2+strN1) canvas.delete("a"+strN1+strN2) canvas.delete("w"+strN1+strN2) canvas.delete("b"+strN1+strN2) #draw and tag a new curve midX,midY,height,width = calcNormal(node1[0],node1[1],node2[0],node2[1]) curve = drawCurve(node1[0],node1[1],node2[0],node2[1],True,aOpt) canvas.addtag_withtag("a",curve) canvas.addtag_withtag("a"+strN1+strN2,curve) #add a weight weight = myGraph.getArc(n1,n2) #gets weight x,y = calArcMid(node1[0],node1[1],node2[0],node2[1],True) w,h = point2(node1[0],node1[1],node2[0],node2[1]) if node1[0]>= node2[0]: canvas.create_line(x,y,x+w,y+h,arrow=LAST,arrowshape=(10,10,10),width=0,tags=("a",("a"+strN2+strN1))) else: canvas.create_line(x,y,x+w,y+h,arrow=FIRST,arrowshape=(10,10,10),width=0,tags=("a",("a"+strN2+strN1))) canvas.create_rectangle(midX+width-20,midY+height+20,midX+width+20,midY+height+40, tags=("b","b"+strN1+strN2),**bOpt) canvas.create_text(midX+width, midY+height+30, text=str(weight),tags=("w","w"+strN1+strN2),**wOpt) #draw and tag second curve curve = drawCurve(node2[0],node2[1],node1[0],node1[1],False,aOpt) canvas.addtag_withtag("a",curve) canvas.addtag_withtag("a"+strN2+strN1,curve) #add a weight midX,midY,height,width = calcNormal(node1[0],node1[1],node2[0],node2[1]) weight = myGraph.getArc(n2,n1) #gets weight x,y = calArcMid(node1[0],node1[1],node2[0],node2[1],False) w,h = point2(node1[0],node1[1],node2[0],node2[1]) if node1[0]>= node2[0]: canvas.create_line(x,y,x+w,y+h,arrow=FIRST,arrowshape=(10,10,10),width=0,tags=("a",("a"+strN2+strN1))) else: canvas.create_line(x,y,x+w,y+h,arrow=LAST,arrowshape=(10,10,10),width=0,tags=("a",("a"+strN2+strN1))) canvas.create_rectangle(midX-width+20, midY-height-20,midX-width-20,midY-height-40,tags=("b","b"+strN2+strN1),**bOpt) canvas.create_text(midX-width, midY-height-30, text=str(weight),tags=("w","w"+strN2+strN1),**wOpt) canvas.tag_lower("w"+strN2+strN1) canvas.tag_lower("b"+strN2+strN1) canvas.tag_lower("a"+strN2+strN1) canvas.tag_lower("w"+strN1+strN2) canvas.tag_lower("b"+strN1+strN2) canvas.tag_lower("a"+strN1+strN2) elif myGraph.getArc(n2,n1)== None and myGraph.getArc(n1,n2) != None: #directed arc #delete existing arcs canvas.delete("a"+strN2+strN1) canvas.delete("w"+strN2+strN1) canvas.delete("b"+strN2+strN1) canvas.delete("a"+strN1+strN2) canvas.delete("w"+strN1+strN2) canvas.delete("b"+strN1+strN2) weight = myGraph.getArc(n1,n2) #gets weight canvas.create_line(midx,midy,node1[0],node1[1],tags=("a",("a"+strN1+strN2)),**aOpt) canvas.create_line(midx,midy,node2[0],node2[1],arrow=FIRST,arrowshape=(10,10,10),width=0,tags=("a",("a"+strN1+strN2)),**aOpt) canvas.create_rectangle(midx-20, midy+20,midx+20,midy+40,tags=("b","b"+strN1+strN2),**bOpt) canvas.create_text(midx, midy+30, text=str(weight),tags=("w","w"+strN1+strN2),**wOpt) #send to back canvas.tag_lower("w"+strN1+strN2) canvas.tag_lower("b"+strN1+strN2) canvas.tag_lower("a"+strN1+strN2) else: tkMessageBox.showwarning("Drawing","Arc drawing error") if menu.orders.get(): drawNode(n1) drawNode(n2) def calArcMid(x1,y1,x2,y2,up): L=25 if y1==y2: y1+=10 if x1==x2: x1+=5 #Calculate midpoint between the nodes midX=(x1+x2)/float(2) midY=(y1+y2)/float(2) #Calculate gradient #if dy is 0, solve by setting gradient to 1 m = 0-(x2-x1)/float(y2-y1) #calculate x and y of arc midpoint angle = math.atan(m) height = L*math.sin(angle) try: width = height/m except: width = height if up: return midX+width,midY+height else: return midX-width,midY-height def point2(x1,y1,x2,y2): L=25 if y1==y2: y1+=1 if x1==x2: x1+=1 m = calcGrad(x1,y1,x2,y2) angle = math.atan(m) height = L*math.sin(angle) try: width = height/m except: width = height return width/9,height/9 def calcGrad(x1,y1,x2,y2): try: return (y2-y1)/float(x2-x1) except: return 1 def calcNormal(x1,y1,x2,y2): L=50 if y1==y2: y1+=10 if x1==x2: x1+=5 #Calculate midpoint between the nodes midX=(x1+x2)/float(2) midY=(y1+y2)/float(2) #Calculate gradient #if dy is 0, solve by setting gradient to 1 m = 0-(x2-x1)/float(y2-y1) #calculate x and y of arc midpoint angle = math.atan(m) height = L*math.sin(angle) try: width = height/m except: width = height return midX,midY,height,width def drawCurve(x1,y1,x2,y2,up,options={}): """ Draws a curve between the 2 coords. Returns curve ID """ if x1 == x2: x1+=1 if y1 == y2: if up: up = False midX,midY,height,width = calcNormal(x1,y1,x2,y2) if up: #make array of points # start mid points = [(x1, y1),(midX+width, midY+height)] # end p = (x2,y2) else: points = [(x2, y2),(midX-width, midY-height)] p = (x1,y1) #draw the arc return canvas.create_line(points, p, smooth = True,**options) def delNode(n1=None): """ Deletes node in GUI and graph object. Also updates arc labels to accomadate """ global myGraph,unRedo if n1 == None: global coordClicked else: coordClicked = n1 reset() neigh = myGraph.neighbors(coordClicked) #deletes any arc lines connected to the deleted node strCoordClicked = "%02d" % (coordClicked) for n in neigh: strN = "%02d" % (n) canvas.delete("a"+strCoordClicked+strN) canvas.delete("b"+strCoordClicked+strN) canvas.delete("w"+strCoordClicked+strN) neigh = myGraph.revNeighbors(coordClicked) for n in neigh: strN = "%02d" % (n) canvas.delete("a"+strN+strCoordClicked) canvas.delete("b"+strN+strCoordClicked) canvas.delete("w"+strN+strCoordClicked) #deletes the node shape canvas.delete("n"+strCoordClicked) canvas.delete("l"+strCoordClicked) canvas.delete("o"+strCoordClicked) myGraph.delNode(coordClicked) #removes entry in graph obj #Adjusts node numbers to match array: # All arcs connecting to a node with a higher index than the # deleted node have their label decresed by one to match # the array in the graph object for node in canvas.find_withtag("n"): if int(canvas.gettags(node)[1][1:]) > coordClicked: new = "%02d" % (int(canvas.gettags(node)[1][1:])-1) canvas.addtag_withtag("n"+new, node) canvas.addtag_withtag("l"+new, "l"+canvas.gettags(node)[1][1:]) canvas.addtag_withtag("o"+new, "o"+canvas.gettags(node)[1][1:]) canvas.dtag("l"+new, "l"+canvas.gettags(node)[1][1:]) canvas.dtag("o"+new, "o"+canvas.gettags(node)[1][1:]) canvas.dtag(node,canvas.gettags(node)[1]) #adjusts arc numbers #Fixed for arc in canvas.find_withtag("a"): theArc = canvas.gettags(arc)[1] new = theArc[1:] if int(new[0:2]) > coordClicked: new = ("%02d" % (int(new[0:2])-1))+new[2:4] if int(new[2:4]) > coordClicked: new = new[0:2]+("%02d" % (int(new[2:4])-1)) if new != theArc[1:]: a = min(canvas.find_withtag(theArc)) b = min(canvas.find_withtag("b"+theArc[1:])) w = min(canvas.find_withtag("w"+theArc[1:])) canvas.addtag_withtag("a"+new,a) canvas.addtag_withtag("b"+new,b) canvas.addtag_withtag("w"+new,w) canvas.dtag(b,"b"+theArc[1:]) canvas.dtag(w,"w"+theArc[1:]) canvas.dtag(a,theArc) #adjusts start/end nodes if myGraph.getStart() >= coordClicked: myGraph.setStart(myGraph.getStart()-1) if myGraph.getEnd() >= coordClicked: myGraph.setEnd(myGraph.getEnd()-1) myMatrixView.update() myArcView.update() def delArc(n1,n2,both=False): """ Deletes arc between n1 and n2 if var both is set to true, arcs in both directiond are deleted """ srtN1 = "%02d" % (n1) srtN2 = "%02d" % (n2) myGraph.delArc(n1,n2)#change matrix #remove GUI elements canvas.delete("a"+srtN1+srtN2) canvas.delete("b"+srtN1+srtN2) canvas.delete("w"+srtN1+srtN2) if both: myGraph.delArc(n2,n1)#change matrix #remove GUI elements canvas.delete("a"+srtN2+srtN1) canvas.delete("b"+srtN2+srtN1) canvas.delete("w"+srtN2+srtN1) else: drawArc(n2,n1) myMatrixView.update() myArcView.update() def popup(event): """Creates context menu at mouse position""" global myGraph,coordClicked if nodeOver(myGraph,event.x,event.y) != None: #popup node menu coordClicked = nodeOver(myGraph,event.x,event.y) isStart = BooleanVar() isStart.set(myGraph.getStart() == coordClicked) isEnd = BooleanVar() isEnd.set(myGraph.getEnd() == coordClicked) isDisabled = BooleanVar() isDisabled.set(myGraph.getNodeState(coordClicked) == "disabled") popNodeMenu = Menu(root, tearoff=0) popNodeMenu.add_command(label="Delete", command=delNode) popNodeMenu.add_separator() popNodeMenu.add_checkbutton(label="Start", command=setStart,var=isStart)#PROBLEM: Need to change to checkbutton popNodeMenu.add_checkbutton(label="End", command=setEnd,var=isEnd) popNodeMenu.add_separator() popNodeMenu.add_checkbutton(label="Disabled",command=disabledClicked,var=isDisabled) popNodeMenu.post(event.x_root, event.y_root) elif canvas.find_overlapping(event.x-5,event.y-5,event.x+5,event.y+5) != (): tag = canvas.gettags(canvas.find_overlapping(event.x-5,event.y-5,event.x+5,event.y+5)[0])[1] if tag[0] in ["w","b","a"]: tag = [int(tag[1:3]),int(tag[3:5])] popArcMenu = Menu(root, tearoff=0) popArcMenu.add_command(label="Delete", command=lambda:delArc(tag[0],tag[1],myGraph.getArc(tag[0],tag[1]) == myGraph.getArc(tag[1],tag[0]))) popArcMenu.post(event.x_root,event.y_root) else: popCanvasMenu = Menu(root, tearoff=0) popCanvasMenu.add_command(label="Clear Algorithm", command=reset) popCanvasMenu.add_command(label="Clear Screen", command=clear) popCanvasMenu.post(event.x_root,event.y_root) def keypress(event): """handles typing""" global myGraph,canvas, shift shift = (event.keysym[:5] == "Shift") textBox = canvas.focus() if textBox: if canvas.gettags(textBox)[0] == "l": #If a node label labelKeypress(event,textBox) else: weightKeypress(event,textBox) def weightKeypress(event,textBox): nodes = (int(canvas.gettags(textBox)[1][1:3]), int(canvas.gettags(textBox)[1][3:5])) insert = canvas.index(textBox, INSERT) #gets cursor index if event.char.isdigit() or event.char== ".": #accept digits only if canvas.tk.call(canvas._w, 'select', 'item'): #if selected replace contents canvas.dchars(textBox, SEL_FIRST, SEL_LAST) canvas.select_clear() canvas.insert(textBox, "insert", event.char) current = myGraph.getArc(nodes[0],nodes[1]) elif len(canvas.itemcget(textBox,"text").split(".")[0])<3 and len(canvas.itemcget(textBox,"text").split(".")[-1])<3: #append a digit (limited to 2 digit numbers) if event.char != "." or (event.char == "." and "." not in canvas.itemcget(textBox,"text")): canvas.insert(textBox, "insert", event.char) current = myGraph.getArc(nodes[0],nodes[1]) labelDeselected(False) elif event.keysym == "BackSpace": if canvas.tk.call(canvas._w, 'select', 'item'): #if label selected, clear it canvas.dchars(textBox, SEL_FIRST, SEL_LAST) canvas.select_clear() current = myGraph.getArc(nodes[0],nodes[1]) else: if insert > 0: #if not already blank canvas.dchars(textBox, insert-1, insert) current = myGraph.getArc(nodes[0],nodes[1]) def labelKeypress(event,textBox): node = int(canvas.gettags(textBox)[1][1:]) insert = canvas.index(textBox, INSERT) #gets cursor index if event.char.isalpha() and not myGraph.isUserNode(event.char): #accept letters only if canvas.tk.call(canvas._w, 'select', 'item'): #if selected replace contents canvas.dchars(textBox, SEL_FIRST, SEL_LAST) canvas.select_clear() canvas.insert(textBox, "insert", event.char.upper()) myGraph.setUserNode(node,canvas.itemcget(textBox,"text")) #current = myGraph.getArc(nodes[0],nodes[1]) elif len(canvas.itemcget(textBox,"text"))<1: #append a digit (limited to 1 letter) labelDeselected(False) elif event.keysym == "BackSpace": canvas.itemconfig(textBox,font="Times 10 normal") myGraph.delUserNode(node) canvas.dchars(textBox, SEL_FIRST, SEL_LAST) canvas.select_clear() for i in range(0,myGraph.getNumNodes()): drawNode(i) def labelDeselected(clear=True): """ Deselects text box and updates matrix also removes arc if set to 0 or blank """ textBox = canvas.focus() if textBox != "": value = canvas.itemcget(textBox,"text") if not canvas.gettags(textBox)[0] == "l": #if an arc weight nodes = (int(canvas.gettags(textBox)[1][1:3]), int(canvas.gettags(textBox)[1][3:])) if value not in ["","0"]: if "." in value: try: value = float(value.strip(' "')) except: #If invalid weight entered: #Perform a fix first = True newValue = "" for s in value: if s != ".": newValue += s if s == "." and first: newValue += s first = False canvas.itemconfig(textBox,text=newValue) control.myDescBox.setText("ERROR","Invalid decimal "+value+". Has been corrected") else: value = int(value) if myGraph.getArc(nodes[0],nodes[1])== myGraph.getArc(nodes[1],nodes[0]): myGraph.setArc(int(nodes[0]),int(nodes[1]),value) else: myGraph.setArc(int(nodes[0]),int(nodes[1]),value,True) else: delArc(nodes[0],nodes[1],myGraph.getArc(nodes[0],nodes[1]) == myGraph.getArc(nodes[1],nodes[0])) if clear != False: canvas.focus("") canvas.select_clear() myMatrixView.update() myArcView.update() def togMatrix(event=None): if myMatrixView.isShown(): myMatrixView.hide() else: myMatrixView.show() def togArcView(event=None): if myArcView.isShown(): myArcView.hide() else: myArcView.show() def setStart(): global coordClicked old = myGraph.getStart() if myGraph.getStart() == coordClicked: myGraph.setStart(None) else: myGraph.setStart(coordClicked) if myGraph.getEnd() == coordClicked: drawNode(myGraph.getEnd()) myGraph.setEnd(None) drawNode(coordClicked) if old != None: drawNode(old) def setEnd(): global coordClicked,myGraph old = myGraph.getEnd() if myGraph.getEnd() == coordClicked: myGraph.setEnd(None) else: myGraph.setEnd(coordClicked) if myGraph.getStart() == coordClicked: drawNode(myGraph.getStart()) myGraph.setStart(None) if old != None: drawNode(old) drawNode(coordClicked) def disabledClicked(): global coordClicked,myGraph if myGraph.getNodeState(coordClicked) == "normal": myGraph.setNodeState(coordClicked,"disabled") else: myGraph.setNodeState(coordClicked,"normal") for j in range(0,2): drawNode(coordClicked) #redraw the node at new pos #redraws the arcs connected to the node: neigh = myGraph.neighbors(coordClicked) revNeighbors = myGraph.revNeighbors(coordClicked) for i in neigh: drawArc(coordClicked,i) for i in revNeighbors: drawArc(i,coordClicked) def resize(event=None): myMatrixView.resize() myArcView.resize() #------------------------------------------------------------------------------ # Step Algorithms #------------------------------------------------------------------------------ def doKruskal(event=None): global myGraph,myKruskal,myArcView if myKruskal==None: reset() myKruskal = kruskal(myGraph) kResult= myKruskal.nextStep() if kResult[0] != "3": if kResult[1]: if len(kResult[2]) == 1: control.myDescBox.setText("STEP 1","Choose the arc of least weight ("+myGraph.getLetter(kResult[0][1][0])+myGraph.getLetter(kResult[0][1][1])+").") else: control.myDescBox.setText("STEP 2","Choose from those arcs remaining the arc of least weight\nwhich does not form a cycle with already chosen arcs ("+myGraph.getLetter(kResult[0][1][0])+myGraph.getLetter(kResult[0][1][1])+").") arcCol(myGraph,kResult[0][1][0],kResult[0][1][1],"green") arcCol(myGraph,kResult[0][1][1],kResult[0][1][0],"green") else: control.myDescBox.setText("STEP 2","Arc "+myGraph.getLetter(kResult[0][1][0])+myGraph.getLetter(kResult[0][1][1])+" rejected as it forms a cycle with already chosen arcs.") arcCol(myGraph,kResult[0][1][0],kResult[0][1][1],"red") arcCol(myGraph,kResult[0][1][1],kResult[0][1][0],"red") else: control.myDescBox.setText("STEP 3","Repeat Step 2 until n-1 arcs have been chosen.\nThe minimum spanning tree has weight "+str(kResult[1])+" units.") myKruskal=None myArcView.update() def doPrim(event=None): global myGraph,myPrim,myMatrixView,control if myPrim==None: myMatrixView.clearPrim() reset() myPrim = prim(myGraph) nodeCol(myGraph,myPrim.getStartNode(),"green") pResult= myPrim.nextStep() if isinstance(pResult,int): nodeCol(myGraph,pResult,"green") #update canvas #update matrix myMatrixView.circleNode(pResult) myMatrixView.horizontalLine(pResult) control.myDescBox.setText("STEP 1"," Select any node ("+myGraph.getLetter(pResult) + ") to be the first node of T.") elif pResult[0] != "3": arcCol(myGraph,pResult[1][0],pResult[1][1],"green") nodeCol(myGraph,pResult[1][1],"green") myMatrixView.circleNode(pResult[1][1]) myMatrixView.circleWeight(pResult[1][1],pResult[1][0]) myMatrixView.horizontalLine(pResult[1][1]) control.myDescBox.setText("STEP 2","Consider the arcs which connect nodes in T to nodes outside T.\nPick the one with minimum weight (" +myGraph.getLetter(pResult[1][0])+myGraph.getLetter(pResult[1][1]) +"). Add this arc and the extra node (" +myGraph.getLetter(pResult[1][1]) +") to T.") else: control.myDescBox.setText("STEP 3","Repeat Step 2 until T contains every node of the graph.\n" +"The minimum spanning tree has weight "+str(pResult[1])+" units.") myPrim=None def doDj(event=None): global myGraph,myDj if myDj==None: reset() myDj = djikstra(myGraph) changedNode = myDj.nextStep() if changedNode[1] == "1": resetCols(myGraph) #Redraw start and ends to update if they weren't specified. drawNode(changedNode[0]) canvas.itemconfig("n"+"%02d" % (myGraph.getEnd()),outline="red") drawDj(changedNode[0]) nodeCol(myGraph,changedNode[0],"green") control.myDescBox.setText("STEP 1","Label the start node with zero and box this label.") elif changedNode[1] == "2": drawDj(changedNode[0]) nodeCol(myGraph,changedNode[0],"orange") control.myDescBox.setText("STEP 2","Consider each node, Y connected to the most recently boxed node, X.\n" +"Temperarily label it with: (the perminant label of X) + XY.") elif changedNode[1] == "3": resetCols(myGraph) drawDj(changedNode[0]) nodeCol(myGraph,changedNode[0],"green") control.myDescBox.setText("STEP 3","Choose the least of all the temporary labels of the network (" +myGraph.getLetter(changedNode[0])+")." +"\nMake this label permanent by boxing it") elif changedNode[3] == "4": drawDj(changedNode[0]) resetCols(myGraph) nodeCol(myGraph,changedNode[0],"green") for arc in changedNode[1]: arcCol(myGraph,arc[0],arc[1],"green") control.myDescBox.setText("STEP 5","Go backwards through the network, retracing the path of shortest length\nfrom the destination node to the start node." +" Weight: "+str(changedNode[2])+".") else: #reset() myDj = None def drawDj(node=None): """ Draws a djikstra working out box next to the node specified. """ if myDj != None and node!=None: #Constants BOX_OFFSET = 25 BOXWIDTH = 100 BOXHEIGHT = 50 coords = myGraph.getCoords(node) coords = list(coords) coords[0] = coords[0]+BOX_OFFSET coords[1] = coords[1]+BOX_OFFSET x = coords[0]+BOXWIDTH/2-(len(myDj.getNode(node).getTempLbls())/2) #tempLbls tempLbls = myDj.getNode(node).getTempLbls() tempLbls = list(map(str,tempLbls)) tempLbls = " ".join(tempLbls) strNode = "%02d" % (node) if canvas.find_withtag("djB"+strNode) == (): #if box doesnt exist: #draw box canvas.create_rectangle(coords[0],coords[1],coords[0]+BOXWIDTH,coords[1]+BOXHEIGHT,fill="white",tags=("dj","djB"+strNode)) canvas.create_line(coords[0],coords[1]+BOXHEIGHT/2,coords[0]+BOXWIDTH,coords[1]+BOXHEIGHT/2,tags=("dj","djL1"+strNode)) canvas.create_line(coords[0]+BOXWIDTH/2,coords[1],coords[0]+BOXWIDTH/2,coords[1]+BOXHEIGHT/2,tags=("dj","djL2"+strNode)) #draw text canvas.create_text(coords[0]+BOXWIDTH*0.25,coords[1]+BOXHEIGHT*0.25,text=myDj.getNode(node).getOrderOfLbl(),tags=("dj","djOLb"+strNode)) canvas.create_text(coords[0]+BOXWIDTH*0.75,coords[1]+BOXHEIGHT*0.25,text=myDj.getNode(node).getPerminantLbl(),tags=("dj","djPLb"+strNode)) canvas.create_text(x,coords[1]+BOXHEIGHT*0.75,text=tempLbls,tags=("dj","djTLb"+strNode)) else: #Move box and update labels canvas.coords("djB"+strNode,coords[0],coords[1],coords[0]+BOXWIDTH,coords[1]+BOXHEIGHT) canvas.coords("djL1"+strNode,coords[0],coords[1]+BOXHEIGHT/2,coords[0]+BOXWIDTH,coords[1]+BOXHEIGHT/2) canvas.coords("djL2"+strNode,coords[0]+BOXWIDTH/2,coords[1],coords[0]+BOXWIDTH/2,coords[1]+BOXHEIGHT/2) canvas.coords("djOLb"+strNode,coords[0]+BOXWIDTH*0.25,coords[1]+BOXHEIGHT*0.25) canvas.itemconfig("djOLb"+strNode,text=myDj.getNode(node).getOrderOfLbl()) canvas.coords("djPLb"+strNode,coords[0]+BOXWIDTH*0.75,coords[1]+BOXHEIGHT*0.25) canvas.itemconfig("djPLb"+strNode,text=myDj.getNode(node).getPerminantLbl()) canvas.coords("djTLb"+strNode,x,coords[1]+BOXHEIGHT*0.75) canvas.itemconfig("djTLb"+strNode,text=tempLbls) else: canvas.delete("dj") def doCPostman(): global myGraph,myCPostman,canvas if myCPostman==None: reset() myCPostman = cPostman(myGraph) cpResult= myCPostman.nextStep() if cpResult == None: myCPostman=None resetCols(graph) canvas.delete("cp") elif cpResult[0] == "1": nodes = list(cpResult[1]) resetCols(graph) for n in range(0,len(nodes)): nodeCol(myGraph,nodes[n],"green") nodes[n] = myGraph.getLetter(nodes[n]) nodes = sorted(nodes) if len(nodes)!= 0: control.myDescBox.setText("STEP 1","Find all the nodes of odd order." +"\nThe odd nodes are "+", ".join(nodes)+".") else: control.myDescBox.setText("STEP 1","Find all the nodes of odd order." +"\nThere are no odd nodes.") elif cpResult[0] == "2": for arc in myGraph.arcs(): canvas.itemconfig("a"+"%02d" % (arc[1][0])+"%02d" % (arc[1][1]),fill="black",width=1) canvas.itemconfig("a"+"%02d" % (arc[1][1])+"%02d" % (arc[1][0]),fill="black",width=1) for a in cpResult[2]: arcCol(myGraph,a[0],a[1],"green") control.myDescBox.setText("STEP 2","For each pair of nodes find the connecting path of minimum weight.\n" +"Weight of path connecting "+ myGraph.getLetter(cpResult[1][0])+myGraph.getLetter(cpResult[1][1]) + " is "+ str(cpResult[3])) elif cpResult[0] == "3": for arc in myGraph.arcs(): canvas.itemconfig("a"+"%02d" % (arc[1][0])+"%02d" % (arc[1][1]),fill="black",width=1) canvas.itemconfig("a"+"%02d" % (arc[1][1])+"%02d" % (arc[1][0]),fill="black",width=1) for path in cpResult[1]: for a in path: arcCol(myGraph,a[0],a[1],"green") control.myDescBox.setText("STEP 3","Pair up all the odd nodes so that the sum of the weights of the connecting paths is minimised.") elif cpResult[0] == "4": for arc in myGraph.arcs(): canvas.itemconfig("a"+"%02d" % (arc[1][0])+"%02d" % (arc[1][1]),fill="black",width=1) canvas.itemconfig("a"+"%02d" % (arc[1][1])+"%02d" % (arc[1][0]),fill="black",width=1) for path in cpResult[1]: for a in path: curve = drawCurve(myGraph.getCoords(a[0])[0],myGraph.getCoords(a[0])[1],myGraph.getCoords(a[1])[0],myGraph.getCoords(a[1])[1],True) canvas.addtag_withtag("cp",curve) canvas.lower("cp") control.myDescBox.setText("STEP 4","In the original graph, duplicate the minimum weight paths found in step 3.") elif cpResult[0] == "5": for arc in canvas.find_withtag("a"): canvas.itemconfig(arc,fill="green",width=3) for arc in canvas.find_withtag("cp"): canvas.itemconfig(arc,fill="green",width=3) control.myDescBox.setText("STEP 5","Find a trail containing every arc for the new (Eulerian) graph.") else: canvas.delete("cp") myCPostman=None resetCols(graph) def doNearestN(): global myGraph,myNearestN if myNearestN==None: reset() myNearestN = nearestN(myGraph) control.myDescBox.setText("STEP 1","Choose any starting node ("+myGraph.getLetter(myNearestN.getStartNode())+").") nodeCol(myGraph,myNearestN.getStartNode(),"green") myMatrixView.circleNode(myNearestN.getStartNode()) else: nResult= myNearestN.nextStep() if nResult[0] == "error": warnings = ["All of the neighbors of the current node have already been added", "There is no arc joining the first to the last node."] control.myDescBox.setText("ERROR",warnings[nResult[1]-1]) myNearestN=None return if nResult[0] != None: arcCol(myGraph,nResult[1][1][0],nResult[1][1][1],"green") nodeCol(myGraph,nResult[1][1][1],"green") if nResult[0] == 2: control.myDescBox.setText("STEP 2","Consider the arcs which join the previous chosen node to not-yet-chosen nodes.\n" +"Pick one with the minimum weight. Add this arc (" + myGraph.getLetter(nResult[1][1][0])+myGraph.getLetter(nResult[1][1][1]) +") and the new node (" +myGraph.getLetter(nResult[1][1][1]) +"), to the cycle.") myMatrixView.circleNode(nResult[1][1][1]) myMatrixView.circleWeight(nResult[1][1][1],nResult[1][1][0]) myMatrixView.horizontalLine(nResult[1][1][1]) else: control.myDescBox.setText("STEP 3 & 4","Repeat step 2 until all arcs have been chosen."+"Then add the arc that joins the\n" +"last-chosen node to the first-chosen node (" + myGraph.getLetter(nResult[1][1][0])+myGraph.getLetter(nResult[1][1][1]) +"). Weight: "+ str(nResult[2])) myMatrixView.circleWeight(nResult[1][1][1],nResult[1][1][0]) myMatrixView.horizontalLine(nResult[1][1][1]) else: myNearestN=None resetCols(graph) def doLowerB(): global myGraph,myLowerB if myLowerB==None: reset() myLowerB = lowerB(copy.copy(myGraph)) nodeCol(myGraph,myLowerB.getX(),"green") control.myDescBox.setText("STEP 1","Choose an arbitrary node, say "+myGraph.getLetter(myLowerB.getX())+".") return cResult= myLowerB.nextStep() if cResult[0] == 1: arcCol(myGraph,cResult[1][1][0],cResult[1][1][1],"green") arcCol(myGraph,cResult[2][1][0],cResult[2][1][1],"green") control.myDescBox.setText("STEP 1","Find the total of the two smallest weights of arcs incedent at " +myGraph.getLetter(myLowerB.getX()) +" = " +str(cResult[3]) +".") elif cResult[0] == 2: nodeCol(myGraph,myLowerB.getX(),"grey",DISABLED) for i in cResult[1]: arcCol(myGraph,i[1][0],i[1][1],"grey",DISABLED) for i in cResult[2]: arcCol(myGraph,i[1][0],i[1][1],"green") control.myDescBox.setText("STEP 2","Consider the arc formed by ignoring "+myGraph.getLetter(myLowerB.getX()) +" and all arcs incident to "+myGraph.getLetter(myLowerB.getX())+"." +"\nFind the total weight for the minimum connector for this network = " + str(cResult[3])) elif cResult[0] == 3: arcCol(myGraph,cResult[1][0][1][0],cResult[1][0][1][1],"green") arcCol(myGraph,cResult[1][1][1][0],cResult[1][1][1][1],"green") nodeCol(myGraph,myLowerB.getX(),"grey",NORMAL) control.myDescBox.setText("STEP 3","The sum of the two totals, "+str(cResult[2])+"+"+str(cResult[3])+"="+str(cResult[4])+", is a lower bound.") else: myLowerB=None resetCols(graph) """ def doTourImprov(): global myGraph,myTImprov,myNearestN if myTImprov==None: if myNearestN == None: control.myDescBox.setText("Error","Nearest neighbor must be run first") return tour = myNearestN.nextStep()[1] tour.insert(0,None) myTImprov = tourImprov(myGraph,tour) control.myDescBox.setText("STEP 1","Let i=1") return tiResult= myTImprov.nextStep() if tiResult[0] == "2": control.myDescBox.setText("STEP 2","Compare d(Vi,Vi+2) + d(Vi+1,Vi+3)\n i.e. Distance between " +myGraph.getLetter(tiResult[1]) +myGraph.getLetter(tiResult[1]+2) +" + Distance between " +myGraph.getLetter(tiResult[1]+1) +myGraph.getLetter(tiResult[1]+3) +" ("+str(tiResult[4])+" + "+str(tiResult[5])+" = "+str(tiResult[4]+tiResult[5])+").") resetCols(graph) arcCol(myGraph,tiResult[2][0],tiResult[2][1],"green") arcCol(myGraph,tiResult[3][0],tiResult[3][1],"green") if tiResult[0] == "2.1": control.myDescBox.setText("STEP 2","d(Vi, Vi+2) + d(Vi+1,Vi+3) is not less than d(Vi, Vi+1) + d(Vi+2, Vi+3)\n" + "i.e. "+str(tiResult[3]) +" is not < " + str(tiResult[4])+".") if tiResult[0] == "3": control.myDescBox.setText("STEP 3","Replace i by i+1.\ni is now "+str(tiResult[1])) if tiResult[0] == "4": if tiResult[1] == True: control.myDescBox.setText("STEP 4","i <= n so go back to Step 2") else: control.myDescBox.setText("STEP 4","i > n") """ #------------------------------------------------------------------------------ # General algorirthm procedures #------------------------------------------------------------------------------ def reset(event=None): """resets algorithms""" global myGraph,myKruskal,myPrim,myDj,myNearestN,myLowerB,myCPostman global myMatrixView,myArcView #Clears object instances: myPrim=None myKruskal=None myCPostman = None drawDj() myDj = None myNearestN = None myLowerB = None control.selectChange() myMatrixView.clearPrim() resetColsOnly(myGraph) #resets arc and node colours def clear(event=None): """clears canvas""" global myGraph global canvas global myKruskal,myPrim,myMatrixView,myArcView reset() myGraph = graph() #reinitializes matrix: if myMatrixView.isShown()==True: canvas.delete("matrix") myMatrixView = matrixView(root,canvas,myGraph,NORMAL) else: canvas.delete("matrix") myMatrixView = matrixView(root,canvas,myGraph,HIDDEN) #reinitializes arcs: if myArcView.isShown()==True: canvas.delete("arcView") myArcView = arcView(root,canvas,myGraph,NORMAL) else: canvas.delete("arcView") myArcView = arcView(root,canvas,myGraph,HIDDEN) #deletes all canvas items: canvas.delete("a") canvas.delete("b") canvas.delete("o") canvas.delete("w") canvas.delete("n") canvas.delete("l") canvas.delete("cp") globalVars() def resetCols(graph): """Sets all colors to defaults""" for arc in canvas.find_withtag("a"): canvas.itemconfig(arc,fill="black",width=1,state=NORMAL) for arc in canvas.find_withtag("b"): canvas.itemconfig(arc,state=NORMAL) for arc in canvas.find_withtag("w"): canvas.itemconfig(arc,state=NORMAL) for node in canvas.find_withtag("n"): canvas.itemconfig(node,fill="grey",state=NORMAL) def resetColsOnly(graph): """Sets all colors to defaults""" for arc in canvas.find_withtag("a"): canvas.itemconfig(arc,fill="black",width=1) for arc in canvas.find_withtag("b"): canvas.itemconfig(arc) for arc in canvas.find_withtag("w"): canvas.itemconfig(arc) for node in canvas.find_withtag("n"): canvas.itemconfig(node,fill="grey") def arcCol(graph,n1,n2,col,state=NORMAL): """changes colour of arcs""" srtN1 = "%02d" % (n1) srtN2 = "%02d" % (n2) #as bidirectional arcs are treated as one, arc colour is changed for both canvas.itemconfig("a"+srtN1+srtN2,fill=col,width=3,state=state) canvas.itemconfig("a"+srtN2+srtN1,fill=col,width=3,state=state) canvas.itemconfig("w"+srtN1+srtN2,state=state) canvas.itemconfig("w"+srtN2+srtN1,state=state) canvas.itemconfig("b"+srtN1+srtN2,state=state) canvas.itemconfig("b"+srtN2+srtN1,state=state) def nodeCol(graph,pos,col,state=NORMAL): """changes colour of nodes""" if pos != None: strPos = "%02d" % (pos) else: strPos = str(pos) canvas.itemconfig("n"+strPos,fill=col,state=state) #------------------------------------------------------------------------------ # Main Code #------------------------------------------------------------------------------ myGraph = graph() #initializes Tkinter window root = Tk() root.title(PROGRAM_NAME)#title bar root.minsize(640,480)#sets minimum size for window #initializes gridding root.columnconfigure(0, weight=1) #Attempt to maxamize: try: root.wm_state('zoomed') except: None #setup rows in grid: root.rowconfigure(0, weight=0) root.rowconfigure(1, weight=1) #Intialises canvas canvas = Canvas(root,bg="white") canvas.grid(column=0, row=1, sticky=(N, W,E,S)) canvas.config(insertbackground="white") #adds matrix view myMatrixView = matrixView(root,canvas,myGraph,HIDDEN) myArcView = arcView(root,canvas,myGraph,HIDDEN) #creates undoRedo manager unRedo = UndoRedo() #add menus: menu = Menus(root) control = controls(root) #add status bar bar = StatusBar(root) bar.grid(column=0, row=2, sticky=(N, W,E,S)) bar.setText("For help, press F1") def nnF(event=None): global newNode newNode = False mouseClick(event) def press(event=None): global shift shift = False def tab(event=None): """Highlights next weight when tab pressed""" global canvas tags = list(canvas.find_withtag("w")) if canvas.focus() != "": new = tags[(tags.index(int(canvas.focus()))+1)% len(tags)] else: new = tags[0] canvas.focus(new) canvas.select_from(canvas.focus(), 0) canvas.select_to(canvas.focus(), len(canvas.itemcget(canvas.focus(),"text"))-1) #adds event bindings canvas.bind("<Button-1>", mouseClick) canvas.bind("<ButtonRelease-1>", mouseUp) canvas.bind("<B1-Motion>", addArc) canvas.bind("<Motion>", updateStatus) canvas.bind("<Shift-B1-Motion>", nodeMove,add='+') canvas.bind("<Shift-B1-Motion>", addArc,add='+') canvas.bind("<Shift-Button-1>", nnF,mouseClick) canvas.bind_all("<KeyRelease>", press) canvas.bind("<Button-3>", popup) canvas.bind_all("<Key>", keypress) canvas.bind("<Configure>", resize) canvas.bind_all("<Return>", labelDeselected) canvas.bind_all("<Tab>", tab) #canvas.bind_all("<ErrorToMakeMyLifeEasy>", tab) #TEMP #begins GUI root.mainloop()
true