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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
2413e32be23f1431fa3bf81f4d16d09f8e4b6c23
|
Python
|
furyash/nscLab
|
/3. ceaserCipher/server-socket.py
|
UTF-8
| 686
| 2.765625
| 3
|
[] |
no_license
|
import socket
def decode(message):
message = list(message) #bytes(message.encode('ascii')))
for i in range(len(message)):
message[i] = chr(ord(message[i]) - key)
return ''.join(message)
key = 3
format = 'utf-8'
size = 1024
port = 8585
server = socket.socket()
host = socket.gethostname()
server.bind((host, port))
server.listen()
print('Listening...')
conn, addr = server.accept() ###
print(f"[{addr}] Connected.")
message = conn.recv(size).decode(format) ###
print("CypherText Recieved:", message)
print(f'Decrypted Message : {decode(message)}')
conn.close()
server.close()
| true
|
a3fadc1d0a796e5cd3eb230a226b29a4b509b48d
|
Python
|
shariqx/codefights-python
|
/MsgfrombinaryCode.py
|
UTF-8
| 364
| 2.875
| 3
|
[] |
no_license
|
def messageFromBinaryCode(code):
x = 0
out = ''
while x +8 <= len(code):
y = (x + 8)
subst = code[x:y]
#print(subst)
theInt = int(subst,2)
# print(theInt)
asci = chr(theInt)
out+=asci
x = x+8
return out
print(messageFromBinaryCode('010010000110010101101100011011000110111100100001'))
| true
|
d8f0391c1e8d3bfef161d076b1529867332f28d3
|
Python
|
mvtmm/spaceInvaders
|
/Explosion.py
|
UTF-8
| 1,263
| 3.421875
| 3
|
[] |
no_license
|
import pygame
from Assettype import AssetType
from Assetloader import Assetloader
class Explosion(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
# Bilder die nach einander angezeigt werden um eine Animation zu erzeugen
self.images = []
# Alle Bilder laden
for num in range(1,12):
img = Assetloader.getAsset(AssetType.Shoot, "Explosion1_" + str(num) + ".png")
# Bilder skalieren
img = pygame.transform.scale(img, (100,100))
self.images.append(img)
self.index = 0
self.image = self.images[self.index]
self.rect = self.image.get_rect()
self.rect.center = [x,y]
self.counter = 0
def update(self):
# Schnelligkeit der Bilder Wechsel Methode
explosion_speed = 2
self.counter += 1
if self.counter >= explosion_speed and self.index < len(self.images) -1:
# Animation abspielen
self.counter = 0
self.index += 1
self.image = self.images[self.index]
if self.index >= len(self.images) -1 and self.counter >= explosion_speed:
# Animation abgelaufen deshalb Objekt zerstören
self.kill()
| true
|
c598927e15617378a16d5c76602041660cc0e2d3
|
Python
|
anuj0721/jarivs
|
/jarvis.py
|
UTF-8
| 3,230
| 2.59375
| 3
|
[] |
no_license
|
import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import os
import smtplib
from twilio.rest import Client
from pytube import YouTube
engine = pyttsx3.init('sapi5')
voices=engine.getProperty('voices')
engine.setProperty('voice',voices [0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
def sendEmail(to , contents):
server=smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.login('anujgupta0721@gmail.com','9560430478')
server.sendmail('anujgupta0721@gmail.com',to,content)
server.close()
def wishMe():
hour=int(datetime.datetime.now().hour)
if hour>=0 and hour<12:
speak("good morning anuj!")
elif hour>=12 and hour<18:
speak("good afternoon anuj!")
else:
speak("good evening anuj!")
speak("i m jarvis. please tell me how may I help you")
def takeCommand():
'''it takes microphone input from user and returns string output'''
r = sr.Recognizer()
with sr.Microphone() as source:
print("listening...")
r.pause_threshold=1
r.adjust_for_ambient_noise(source,duration=5)
audio = r.listen(source)
try:
print("recognizing..")
query=r.recognize_google(audio, language='en-in')
print(f"user said:{query}\n")
except Exception as e:
#print(e)
print("say that again please...")
return "none"
return query
if __name__ == "__main__" :
chrome_path='C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
myvideo=YouTube("https://www.youtube.com/watch?v=5MgBikgcWnY")
print(sr.__version__)
wishMe()
if True:
query=takeCommand().lower()
#query='open google'
#logic for executing task based on query
if 'wikipedia' in query:
speak('searching wikipedia..')
query=query.replace('wikipedia','')
results=wikipedia.summary(query,sentences=2)
speak("according to wikipedia")
print(results)
speak(results)
elif 'open youtube' in query:
url="youtube.com"
webbrowser.get(chrome_path).open(url)
elif 'open google' in query:
url="google.com"
webbrowser.get(chrome_path).open(url)
elif 'open stackoverflow' in query:
webbrowser.open("stackoverflow.com")
elif 'send email' in query:
speak("what should i say")
content='send this email to anuj gupta to check code'
to='anujgupta0721@gmail.com'
sendEmail(to,content)
speak("email has been sent ")
elif 'message' in query:
client=Client()
from_whatsapp_number='whatsapp:+918109813801'
to_whatsapp_number='whatsapp:+919009849949'
client.messages.create(body="checking program!",from_=from_whatsapp_number,to=to_whatsapp_number)
speak("whatsapp message has been sent")
elif 'open netflix' in query:
webbrowser.open("netflix.com")
elif 'title' in query:
print(myvideo.title)
elif 'views' in query:
print(myvideo.views)
| true
|
857bb4e8b24aec38b15b91aeaf761618061b4747
|
Python
|
Tribler/application-tester
|
/tribler_apptester/utils/asyncio.py
|
UTF-8
| 434
| 2.8125
| 3
|
[] |
no_license
|
from asyncio import Future, iscoroutine, sleep
def maybe_coroutine(func, *args, **kwargs):
value = func(*args, **kwargs)
if iscoroutine(value) or isinstance(value, Future):
return value
async def coro():
return value
return coro()
async def looping_call(delay, interval, task, *args):
await sleep(delay)
while True:
await maybe_coroutine(task, *args)
await sleep(interval)
| true
|
6b810024a7e0c8c95496102a4bcece07e1456530
|
Python
|
zszzlmt/leetcode
|
/solutions/506.py
|
UTF-8
| 698
| 3.25
| 3
|
[] |
no_license
|
import copy
class Solution(object):
def findRelativeRanks(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
ranks = copy.deepcopy(nums)
ranks.sort(reverse=True)
res = list()
for item in nums:
rank = ranks.index(item) + 1
if rank == 1:
res.append('Gold Medal')
continue
elif rank == 2:
res.append('Silver Medal')
continue
elif rank == 3:
res.append('Bronze Medal')
continue
else:
res.append(str(rank))
continue
return res
| true
|
22552fb057b2665cb35804e524207a268c879c5d
|
Python
|
Wardar-py/Todo_list
|
/todo_list/models.py
|
UTF-8
| 1,011
| 2.546875
| 3
|
[] |
no_license
|
from django.db import models
from datetime import timedelta
# Create your models here.
from django.utils import timezone
class Category(models.Model):
name = models.CharField(max_length=100, unique=True)
class Meta:
verbose_name = 'Категория'
verbose_name_plural = 'Категории'
def __str__(self):
return self.name
def get_due_date():
""" На выполнение задачи по-умолчанию даётся один день """
return timezone.now() + timedelta(days=1)
class Todo(models.Model):
title = models.CharField(max_length=250)
text = models.TextField(blank=True)
created_date = models.DateField(auto_now_add=True)
due_date = models.DateField(default=get_due_date())
category = models.ForeignKey(Category, related_name='todo_list', on_delete=models.PROTECT)
class Meta:
verbose_name = 'Задача'
verbose_name_plural = 'Задачи'
def __str__(self):
return self.title
| true
|
d823f9006189c9d4cebb96248ab0ea4fd2897dfe
|
Python
|
OnurKader/CMP4501
|
/search/search.py
|
UTF-8
| 5,826
| 3.375
| 3
|
[] |
no_license
|
# search.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
"""
In search.py, you will implement generic search algorithms which are called by
Pacman agents (in searchAgents.py).
"""
import util
class SearchProblem:
"""
This class outlines the structure of a search problem, but doesn't implement
any of the methods (in object-oriented terminology: an abstract class).
You do not need to change anything in this class, ever.
"""
def getStartState(self):
"""
Returns the start state for the search problem.
"""
util.raiseNotDefined()
def isGoalState(self, state):
"""
state: Search state
Returns True if and only if the state is a valid goal state.
"""
util.raiseNotDefined()
def getSuccessors(self, state):
"""
state: Search state
For a given state, this should return a list of triples, (successor,
action, stepCost), where 'successor' is a successor to the current
state, 'action' is the action required to get there, and 'stepCost' is
the incremental cost of expanding to that successor.
"""
util.raiseNotDefined()
def getCostOfActions(self, actions):
"""
actions: A list of actions to take
This method returns the total cost of a particular sequence of actions.
The sequence must be composed of legal moves.
"""
util.raiseNotDefined()
def tinyMazeSearch(problem):
"""
Returns a sequence of moves that solves tinyMaze. For any other maze, the
sequence of moves will be incorrect, so only use this for tinyMaze.
"""
from game import Directions
s = Directions.SOUTH
w = Directions.WEST
return [s, s, w, s, w, w, s, w]
def depthFirstSearch(problem):
start = problem.getStartState()
stack = util.Stack()
stack.push((start, list()))
visited_nodes = list()
while not stack.isEmpty():
# print "a"
curr_coord, next_coords = stack.pop()
for xy, comp, _ in problem.getSuccessors(curr_coord):
if problem.isGoalState(xy):
return next_coords + [comp]
# raise Exception("Illegal action " + str(action))
# Exception: Illegal action South
if xy not in visited_nodes:
stack.push((xy, next_coords + [comp]))
visited_nodes.append(curr_coord)
return list()
# BFS = Queue
# Return a list of Directions
def breadthFirstSearch(problem):
# from game import Directions as dir
# TODO "Exception: Illegal action South"
# (35, 1)
start = problem.getStartState()
queue = util.Queue()
# queue = (Current COORD, [Next COORD(S)])
queue.push((start, list()))
visited_nodes = list()
# print queue.list
while not queue.isEmpty():
curr_coord, next_coords = queue.pop() # Tuple and a List
# next_coords == None ?!?!
# getSuccessors returns available coords to visit
for xy, comp, _ in problem.getSuccessors(curr_coord):
if problem.isGoalState(xy):
# Does it 1 block early? how to fix?!
return next_coords + [comp]
if xy not in visited_nodes:
# Compass is a direction NORTH, SOUTH, etc.
visited_nodes.append(xy)
# queue.push((xy, next_coords.append(comp)))
# order of concatanation matters
queue.push((xy, next_coords + [comp]))
# queue.push((xy, next_coords.append(comp)))
# AttributeError: 'NoneType' object has no attribute 'append'
# return [dir.NORTH, dir.NORTH, dir.WEST]
return list()
def uniformCostSearch(problem):
# from game import Directions as dir
p_queue = util.PriorityQueue()
visited_nodes = list()
start = problem.getStartState()
# PriorityQueue = (Item, Priority)
p_queue.push((start, list(), 0), 0)
while not p_queue.isEmpty():
curr_coord, next_coords, cost = p_queue.pop()
for xy, comp, price in problem.getSuccessors(curr_coord):
if problem.isGoalState(xy):
return next_coords + [comp]
if xy not in visited_nodes:
visited_nodes.append(xy)
p_queue.push(
(xy, next_coords + [comp], cost + price), cost + price)
return list()
def nullHeuristic(state, problem=None):
return 0
def aStarSearch(problem, heuristic=nullHeuristic):
p_queue = util.PriorityQueue()
visited_nodes = list()
start = problem.getStartState()
p_queue.push((start, list(), 0), 0 + heuristic(start, problem))
while not p_queue.isEmpty():
curr_coord, next_coords, cost = p_queue.pop()
for xy, comp, price in problem.getSuccessors(curr_coord):
if problem.isGoalState(xy):
return next_coords + [comp]
if xy not in visited_nodes:
visited_nodes.append(xy)
p_queue.push(
(xy, next_coords + [comp], cost + price),
cost + price + heuristic(xy, problem))
return list()
# Abbreviations
dfs = depthFirstSearch
bfs = breadthFirstSearch
ucs = uniformCostSearch
astar = aStarSearch
| true
|
9e42139dec5e830b3a4e35e222bee636aa02b03e
|
Python
|
jskerjan/programming
|
/programming.py
|
UTF-8
| 781
| 3.046875
| 3
|
[] |
no_license
|
#I plan to get the comments competency checked off on this assignment
# A sequence of assignments to generate a random problem :
import random
a = random.randint(5,9)
e = random.randint(1,3) #range is kept between 1 and 3 to ensure b remains a single digit integer
c = random.randint(1,3)
d = random.randint(5,9)
b = c * e #b must be calculated this way to counter c * e, leaving only a coefficient for x in the calculation for u
u = (a + (c * d) + (-b + (c * e)))
print('Problem: ({a}x - {b}) + {c}({d}x + {e}) = ?' .format (a = a,
b = b, c = c, d = d, e = e))
print('Answer : {u}x'. format (u = u))
#This is a comment about editing for the staging and committing competency
#This comment is an edit being made through the GitHub website to demonstrate the pulling competency
| true
|
a4d8705e9b91a82a4d1a0e032e0ecc3a86246067
|
Python
|
Vaild/python-learn
|
/homework/20200707/59_字符串调整.py
|
UTF-8
| 371
| 3.625
| 4
|
[] |
no_license
|
#!/usr/bin/python3
# coding = UTF-8
str1 = 'Hello, 我是David'
str2 = 'OK, 好'
str3 = '很高兴认识你'
n = max(len(str1), len(str2),len(str3))
print(str1.ljust(n))
print(str2.ljust(n))
print(str3.ljust(n))
print('*'*50)
print(str1.rjust(n))
print(str2.rjust(n))
print(str3.rjust(n))
print('*'*50)
print(str1.center(n))
print(str2.center(n))
print(str3.center(n))
| true
|
3ed772d863e1eecbc8578ef3d9be42134e5cab0c
|
Python
|
gmg2719/Geometry
|
/猜数字/匈牙利算法.py
|
UTF-8
| 355
| 2.90625
| 3
|
[] |
no_license
|
from scipy.optimize import linear_sum_assignment
import numpy as np
from scipy.sparse import csr
a = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 9]])
x, y = linear_sum_assignment(a, maximize=True)
print(x, y)
print(a)
print(a[x, y])
a = csr.csr_matrix(([1, 2, 3], (0, 1, 2), (0, 1, 2)))
print(a)
x, y = linear_sum_assignment(a, maximize=True)
print(a[x, y])
| true
|
6c8a1087221ed1fd3128eb20c5f8d24ce1c5091c
|
Python
|
khushaliverma27/Multi-modal-MER
|
/Feature Extraction and Data Analysis/lyric_features.py
|
UTF-8
| 8,794
| 2.765625
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# lyric_features.py [DIRECTORY_NAME] prints an ACE XML 1.1 feature
# value file to standard output with the features corresponding to the
# lyrics in the specified directory
import csv
import os
import os.path
import string
import subprocess
import sys
function_words = [["the"],
["and"],
["to"],
["a", "an"],
["of"],
["in"],
["that", "those"],
["it"],
["not"],
["as"],
["with"],
["but"],
["for"],
["at"],
["this", "these"],
["so"],
["all"],
["on"],
["from"],
["one", "ones"],
["up"],
["no"],
["out"],
["what"],
["then"],
["if"],
["there"],
["by"],
["who"],
["when"],
["into"],
["now"],
["down"],
["over"],
["back"],
["or"],
["well"],
["which"],
["how"],
["here"],
["just"],
["very"],
["where"],
["before"],
["upon"],
["about"],
["after"],
["more"],
["why"],
["some"]]
treebank_tags = [['CC'],
['CD'],
['DT'],
['EX'],
['FW'],
['IN'],
['JJ', 'JJR', 'JJS'],
['LS'],
['MD'],
['NN', 'NNS', 'NNP', 'NNPS'],
['PDT'],
['POS'],
['PRP', 'PRP$'],
['RB', 'RBR', 'RBS'],
['RP'],
['SYM'],
['TO'],
['UH'],
['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ'],
['WDT', 'WP' 'WP$', 'WRB']]
def print_feature(name, value_list):
print(" <feature>\n"
+ " <name>"
+ name
+ "</name>")
for v in value_list:
print(" <v>"
+ str(v)
+"</v>")
print(" </feature>")
def function_word_frequencies(lyrics):
length = len(lyrics)
if length == 0: return [0 for x in range(50)]
return [float(sum([sum([w == y for y in lyrics]) for w in l]))
/ length
for l in function_words]
def average_word_length(lyrics):
length = len(lyrics)
if length == 0: return [0]
return [float(sum([len(s) for s in lyrics])) / length]
def letter_frequencies(lyrics):
length = len(lyrics)
if length == 0: return [0 for x in range(26)]
join = "".join(lyrics)
join_length = len(join)
return [float(join.count(chr(i))) / join_length for i in range(97, 123)]
def punctuation_frequencies(lyrics):
length = len(lyrics)
if length == 0: return [0 for x in range(32)]
return [float(sum([l.count(p) for l in lyrics])) / length
for p in string.punctuation]
def vocabulary_richness(lyrics):
length = len(lyrics)
if length == 0: return [0]
return [float(len(frozenset(lyrics))) / length]
def flesh_list(filename):
process = subprocess.Popen(['java', '-jar', 'CmdFlesh.jar', filename],
stdout = subprocess.PIPE)
process.wait()
result = process.stdout.read()
process.stdout.close()
split = result.replace(',', '.').replace('?', '0').split()
return [split[i] for i in [3, 8, 10, 12, 17, 22]]
def aspell_count(lyrics):
length = len(lyrics)
if length == 0: return [0]
process = subprocess.Popen(['aspell', '-d', 'en', 'list'],
stdin = subprocess.PIPE,
stdout = subprocess.PIPE)
(result, stderrdata) = process.communicate(" ".join(lyrics))
return [float(len(result.split())) / length]
def treebank_frequencies(filename):
process = subprocess.Popen(['./stanford-postagger.sh',
'models/bidirectional-distsim-wsj-0-18.tagger',
filename],
cwd = 'stanford-postagger-2009-12-24',
stdout = subprocess.PIPE)
process.wait()
result = process.stdout.read()
process.stdout.close()
split = result.split()
length = len(split)
if length == 0: return [0 for x in range(20)]
triples = [s.partition('_') for s in result.split()]
return [float(sum([sum([t == y[2] for y in triples]) for t in l]))
/ length
for l in treebank_tags]
def bigram_frequencies(lyrics):
characters = " " + string.ascii_lowercase
length = len(lyrics)
if length == 0: return ",".join(["0" for x in range(27**2)]) + "\n"
join = " ".join(lyrics)
join_length = len(join)
bigrams = [s1 + s2 for s1 in characters for s2 in characters]
return ",".join(["%g" % (float(join.count(b)) / join_length) for b in bigrams]) + "\n"
features = [("Word count", lambda f, l, r: [len(l)]),
("Function word frequencies",
lambda f, l, r: function_word_frequencies(r)),
("Average word length", lambda f, l, r: average_word_length(r)),
("Letter frequencies", lambda f, l, r: letter_frequencies(r)),
("Punctuation frequencies",
lambda f, l, r: punctuation_frequencies(l)),
("Vocabulary size",
lambda f, l, r: [len(frozenset([s.lower() for s in r]))]),
("Vocabulary richness", lambda f, l, r: vocabulary_richness(r)),
("Flesh-Kincaid grade level", lambda f, l, r: flesh_list(f)[0:1]),
("Flesh reading ease", lambda f, l, r: flesh_list(f)[1:2]),
("Sentence count", lambda f, l, r: flesh_list(f)[2:3]),
("Average syllable count per word",
lambda f, l, r: flesh_list(f)[4:5]),
("Average sentence length", lambda f, l, r: flesh_list(f)[5:6]),
("Rate of misspelling", lambda f, l, r: aspell_count(l)),
("Part-of-speech frequencies",
lambda f, l, r: treebank_frequencies(f))]
# intermediate_features = [("bigram_frequencies.dat",
# lambda c, l, r: bigram_frequencies(r))]
# csv_features = [("Letter-bigram components",
# "bigram_components.dat"),
# ("Topic membership probabilities (10 topics)",
# "topics10.dat"),
# ("Topic membership probabilities (24 topics)",
# "topics24.dat")]
# print('<?xml version="1.0"?>\n'
# + " <!DOCTYPE feature_vector_file [\n"
# + " <!ELEMENT feature_vector_file (comments, data_set+)>\n"
# + " <!ELEMENT comments (#PCDATA)>\n"
# + " <!ELEMENT data_set (data_set_id, section*, feature*)>\n"
# + " <!ELEMENT data_set_id (#PCDATA)>\n"
# + " <!ELEMENT section (feature+)>\n"
# + ' <!ATTLIST section start CDATA ""\n'
# + ' stop CDATA "">\n'
# + " <!ELEMENT feature (name, v+)>\n"
# + " <!ELEMENT name (#PCDATA)>\n"
# + " <!ELEMENT v (#PCDATA)>\n"
# + "]>\n\n"
# + "<feature_vector_file>\n\n"
# + " <comments>Features extracted for SLAC</comments>\n")
# csv_files = [(n, open(os.path.join(f))) for (n, f) in csv_features]
# csv_readers = [(n, csv.reader(f)) for (n, f) in csv_files]
# for filename in os.listdir(sys.argv[1]):
# if filename == ".DS_Store": continue
# print(" <data_set>\n"
# + " <data_set_id>"
# + os.path.splitext(filename)[0]
# + "</data_set_id>")
# full_name = os.path.join(sys.argv[1], filename)
# file = open(full_name)
# contents = file.read()
# file.close()
# lyrics = contents.split()
# reduced_lyrics = [s.translate(None, string.punctuation).lower() for s in lyrics]
# for feature in features:
# print_feature(feature[0], feature[1](full_name, lyrics, reduced_lyrics))
# for feature in intermediate_features:
# outside_file = open(feature[0], 'a')
# outside_file.write(feature[1](contents, lyrics, reduced_lyrics))
# outside_file.close()
# for feature in csv_readers:
# print_feature(feature[0], feature[1].next())
# print(" </data_set>")
# for (n, f) in csv_files: f.close()
# print("</feature_vector_file>")
| true
|
4f630b38c60c9197883a419d0b2b31f4653a7130
|
Python
|
nicomn97/Lab-Intermedio
|
/RelacionCM/graf.py
|
UTF-8
| 828
| 2.734375
| 3
|
[] |
no_license
|
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(8,5))
plt.errorbar(1,6.949, yerr=0.046, fmt='o',label="$Relacion B/I\ experimental$")
plt.scatter(2,6.926, label="$Relacion B/I\ Teorica$")
plt.ylabel("$B/I (T/A\\times 10^{-4})$")
plt.xticks([])
plt.title("$B\ vs.\ I$")
plt.legend(loc="best")
plt.savefig("g4.pdf")
plt.figure(figsize=(8,5))
plt.errorbar(1,1.52, yerr=0.24, fmt='o',label="$e/m\ para\ R=2cm$")
plt.errorbar(2,1.51, yerr=0.21, fmt='o',label="$e/m\ para\ R=3cm$")
plt.errorbar(3,1.45, yerr=0.19, fmt='o',label="$e/m\ para\ R=4cm$")
plt.errorbar(4,1.56, yerr=0.23, fmt='o',label="$e/m\ para\ R=5cm$")
plt.scatter(5,1.7588, label="$Valor\ e/m\ CODATA$")
plt.ylabel("$e/m\ (As/kg\\times 10^{11})$")
plt.xlim(0,8)
plt.xticks([])
plt.title("$B\ vs.\ I$")
plt.legend(loc=4)
plt.savefig("g5.pdf")
| true
|
6f75c570b5a9f5e6c5a5ac55cc42bf285481287c
|
Python
|
reachtarunhere/python-workout
|
/ch03-lists-tuples/test_e13_tuple_records.py
|
UTF-8
| 413
| 3.5
| 4
|
[] |
no_license
|
from e13_tuple_records import format_sort_records, PEOPLE
def test_empty():
assert format_sort_records([]) == []
def test_with_people():
output = format_sort_records(PEOPLE)
assert isinstance(output, list)
assert all(isinstance(x, str) for x in output)
assert output[0][:10].strip() == 'Putin'
assert output[0][10:20].strip() == 'Vladimir'
assert output[0][20:].strip() == '3.63'
| true
|
f52ddbe2251c1c850defdc9bdadedb082b5ce82f
|
Python
|
Asherkab/benderopt
|
/benderopt/stats/lognormal.py
|
UTF-8
| 3,715
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
import numpy as np
from scipy import stats
def generate_samples_lognormal(mu_log,
sigma_log,
low_log,
low,
high_log,
step,
base,
size=1,
**kwargs):
"""Generate sample for (truncated)(discrete)log10normal density."""
# Draw a samples which fit between low and high (if they are given)
a = (low_log - mu_log) / sigma_log
b = (high_log - mu_log) / sigma_log
samples = base ** stats.truncnorm.rvs(a=a,
b=b,
size=size,
loc=mu_log,
scale=sigma_log)
if step and low != -np.inf:
samples = step * np.floor((samples - low) / step) + low
elif step and low == -np.inf:
samples = step * np.floor(samples / step)
return samples
def lognormal_cdf(samples,
mu_log,
sigma_log,
low,
high,
base,
):
"""Evaluate (truncated)normal cumulated density function for each samples.
https://onlinecourses.science.psu.edu/stat414/node/157
From scipy:
If X normal, log(X) = Y follow a lognormal dist if s=sigma and scale = exp(mu)
So we infer for a base b : s = sigma * np.log(b) and scale = base ** mu
are similar
mu = 9.2156
sigma = 8.457
base = 145.2
a = (stats.norm.rvs(size=1000000, loc=mu, scale=sigma))
b = np.log(stats.lognorm.rvs(size=1000000, s=sigma * np.log(base), scale=base ** mu)) / np.log(base)
plt.subplot(2, 1, 1)
plt.hist(a, bins=5000)
plt.subplot(2, 1, 2)
plt.hist(b, bins=5000)
plt.show()
"""
parametrization = {
's': sigma_log * np.log(base),
'scale': base ** mu_log,
}
cdf_low = stats.lognorm.cdf(low, **parametrization)
cdf_high = stats.lognorm.cdf(high, **parametrization)
values = (stats.lognorm.cdf(samples, **parametrization) - cdf_low) / (cdf_high - cdf_low)
values[(samples < low)] = 0
values[(samples >= high)] = 1
return values
def lognormal_pdf(samples,
mu,
mu_log,
sigma,
sigma_log,
low,
low_log,
high,
high_log,
base,
step
):
"""Evaluate (truncated)(discrete)normal probability density function for each sample."""
values = None
if step is None:
parametrization = {
's': sigma_log * np.log(base),
'scale': base ** mu_log,
}
cdf_low = stats.lognorm.cdf(low, **parametrization)
cdf_high = stats.lognorm.cdf(high, **parametrization)
values = stats.lognorm.pdf(samples, **parametrization) / (cdf_high - cdf_low)
else:
values = (lognormal_cdf(samples + step,
mu_log=mu_log,
sigma_log=sigma_log,
low=low,
high=high,
base=base) -
lognormal_cdf(samples,
mu_log=mu_log,
sigma_log=sigma_log,
low=low,
high=high,
base=base))
values[(samples < low) + (samples >= high)] = 0
return values
| true
|
34a99ed58ea13b6c899a22ad2aa833111fa7864e
|
Python
|
iccowan/CSC_117
|
/HW_2_20/p163_12.py
|
UTF-8
| 795
| 4.1875
| 4
|
[] |
no_license
|
# Ian Cowan
# Feb 20 2019
# Problem 12 on page 163
# Population
# Prompts the user to input the appropiate fields
start = int(input('Starting number of organisms: '))
daily_inc = float(input('Daily increase (percentage): '))
num_days = int(input('Number of days to multiply: '))
# Adds the headers to the table
print('Day\tApproximate Population')
print('-----------------------------')
# Sets the last_pop variable
last_pop = start
daily_inc = 1 + (daily_inc / 100)
day = 1
# Loops while the day is less than or equal to the number of days inputted by the user and returns the information
while day <= num_days:
if day == 1:
pop = float(start)
else:
pop = last_pop * daily_inc
print(str(day) + '\t' + str('{:.3f}'.format(pop)))
last_pop = pop
day += 1
| true
|
8bf2afd4d6a4770e89c1be94838115f1d4b54fc0
|
Python
|
152334H/aoc_2020
|
/2020/12/solve.py
|
UTF-8
| 746
| 2.640625
| 3
|
[] |
no_license
|
from aoc import *
def parse(l): return (l[0], int(l[1:]))
def rotate(x,y): return (y,-x)
s = sreadlines('input', parse)
MOV, MOVDIR = [(1,0), (0,-1), (-1,0), (0,1)], 'ESWN'
direct, loc = 0, (0,0)
for act,v in s:
if act in 'LR': direct = (direct+(v//90)*[-1,1][act == 'R']) % 4
elif act == 'F': loc = padd(loc, pmul(MOV[direct],v))
elif act in 'NSEW': loc = padd(loc, pmul(MOV[MOVDIR.index(act)],v))
print(sum(map(abs,loc)))
loc, wpt = (0,0), (10,1)
for act,v in s:
if act in 'LR':
direct = ((v//90)*[-1,1][act == 'R']) % 4
for _ in range(direct): wpt = rotate(*wpt)
elif act == 'F': loc = padd(loc, pmul(wpt,v))
elif act in 'NSEW': wpt = padd(wpt, pmul(MOV[MOVDIR.index(act)],v))
print(sum(map(abs,loc)))
| true
|
78400e4e8b49e708f343c1f7d78a84602d8e5b18
|
Python
|
calvinfroedge/erpnext
|
/erpnext/patches/before_jan_2012/remove_duplicate_table_mapper_detail.py
|
UTF-8
| 581
| 2.546875
| 3
|
[] |
no_license
|
"""
Removes duplicate entries created in
"""
import webnotes
def execute():
res = webnotes.conn.sql("""\
SELECT a.name
FROM
`tabTable Mapper Detail` a,
`tabTable Mapper Detail` b
WHERE
a.parent = b.parent AND
a.from_table = b.from_table AND
a.to_table = b.to_table AND
a.from_field = b.from_field AND
a.to_field = b.to_field AND
a.name < b.name""")
if res and len(res)>0:
name_string = ", ".join(["'" + str(r[0]) + "'" for r in res])
res = webnotes.conn.sql("""\
DELETE FROM `tabTable Mapper Detail`
WHERE name IN (%s)""" % name_string)
| true
|
36e0b4075fec730cfd383e64589cc933fb26316a
|
Python
|
damiendevienne/hgt-ghosts
|
/Prediction_ale.py
|
UTF-8
| 4,904
| 2.5625
| 3
|
[] |
no_license
|
#!/usr/bin/python3
##########
########### Utilisation
############ Python3 prediction_ale.py [uts complet] [arbre complet] [arbre prune] [numero de gene]
#############
##############
############################################################################### Importation #########################################################################
from ete3 import Tree
import argparse
import sys
############################################################################### Déclaration #########################################################################
ale = open(sys.argv[1],"r")
arbre_zombi= Tree(sys.argv[2],format=1) #grand
arbre_vivant = Tree(sys.argv[3],format =1) #petit
num_gene = sys.argv[4]
liste = []
liste_feuille_vivante = [i.name for i in arbre_vivant]
liste_feuille = [i.name for i in arbre_zombi]
liste_morte = list(set(liste_feuille)-set(liste_feuille_vivante))
transfert = ale.readlines()
transfert_donneur = []
transfert_receveur = []
score=[]
nouveau_transfert = open("new_transfert.txt","a")
############################################################################### Lecture fichier ALE #########################################################################
try:
info = transfert[1].split()
except:
nouveau_transfert.write("null")
exit()
del transfert[0]
for line in transfert:
events = line.split()
donneur_a = events[0].split("(")
receveur_a = events[1].split("(")
transfert_donneur.append(donneur_a[0])
transfert_receveur.append(receveur_a[0])
score.append(events[2])
############################################################################### Prediction #########################################################################
######## Pour prédire ce que vont devenir les transferts après échantillonnage nous cherchons si les donneurs disparus ont un ascendant vivant et différent du receveur.
######## Pour les cas des receveurs nous cherchons si ils ont un descendant vivant et différent du donneur.
new_transfert_donneur = []
for d in transfert_donneur:
node = arbre_zombi&d
leaves = [i.name for i in node]
descornot = len(list(set(liste_feuille_vivante) & set(leaves)))
while (descornot==0 and node.is_root()!=True):
node=node.up
leaves = [i.name for i in node]
descornot = len(list(set(liste_feuille_vivante) & set(leaves)))
if (descornot==1):
new_transfert_donneur.append(list(set(liste_feuille_vivante) & set(leaves))[0])
else:
new_transfert_donneur.append(arbre_vivant.get_common_ancestor(list(set(liste_feuille_vivante) & set(leaves))).name)
new_transfert_receveur = []
for d in transfert_receveur:
node = arbre_zombi&d
leaves = [i.name for i in node]
descornot = len(list(set(liste_feuille_vivante) & set(leaves)))
if (descornot==0):
new_transfert_receveur.append("none")
elif (descornot==1):
new_transfert_receveur.append(list(set(liste_feuille_vivante) & set(leaves))[0])
else:
new_transfert_receveur.append(arbre_vivant.get_common_ancestor(list(set(liste_feuille_vivante) & set(leaves))).name)
transfert_new = []
transfert_disparu = []
for k in range(len(new_transfert_donneur)):
if (new_transfert_receveur[k]!="none"):
transfert_new.append(new_transfert_donneur[k] + " - " + new_transfert_receveur[k]+ " - "+ score[k])
elif(new_transfert_receveur[k]=="none"):
transfert_disparu.append( transfert_donneur[k] + " - " + transfert_receveur[k] + ";" + "null" + ";" + str(score[k]) + ";" + "0")
############################################################################### Elimination des doublons #########################################################################
############# On conserve un seule copie de chaque transfert, celle qui a le score le plus élevé
mes_transferts = []
for i in range(len(transfert_new)):
for j in range(len(transfert_new)):
if(i!=j):
transfert_1 = transfert_new[i].split("-")
transfert_2 = transfert_new[j].split("-")
if (str(transfert_1[0]) == str(transfert_2[0]) and str(transfert_1[1])==str(transfert_2[1])):
if (float(transfert_1[2])>float(transfert_2[2])):
mes_transferts.append(transfert_new[i])
liste.append(j)
liste.append(i)
elif(float(transfert_1[2])<float(transfert_2[2])):
mes_transferts.append(transfert_new[j])
liste.append(j)
liste.append(i)
for i in range(len(transfert_new)):
if i not in liste:
mes_transferts.append(transfert_new[i])
liste.append(i)
############################################################################### Ecriture #########################################################################
nouveau_transfert = open("new_transfert.txt","a")
transfert_new_final = list(set(mes_transferts))
for i in range(len(transfert_new_final)):
nouveau_transfert.write(str(transfert_new_final[i])+"\n")
sortie = open("sortie.txt", "a")
for i in range(len(transfert_disparu)):
sortie.write(num_gene+ ";" +str(transfert_disparu[i])+"\n")
| true
|
cc0f9995f6fb0ae6658c011b87283fdeee64964b
|
Python
|
futotta-risu/JABA
|
/JABA/service/scraper/spam/filtering.py
|
UTF-8
| 1,508
| 2.765625
| 3
|
[
"Apache-2.0"
] |
permissive
|
from math import ceil
from sklearn.cluster import DBSCAN
from scipy.spatial.distance import pdist, squareform
import numpy as np
from .metrics import jacard
def filter_duplicated(data):
'''
Filters the duplicated elements from the data.
Parameters:
data (list) List of strings.
'''
pass # TODO Implement functions
def filter_spam(data, batch_size=5000, verbose=False, metric=jacard, eps=0.3):
'''
Filters spam based on text similarity.
Parameters
data : Python list of the input data. The list can be a string.
'''
batches = ceil(len(data)/batch_size)
filtered_data = []
if verbose:
import time
start_time = time.time()
for n_batch in range(batches):
if verbose:
last_batch_time = time.time() - start_time
start_time = time.time()
eta_time = (batches + 1 - n_batch) * last_batch_time
batch_output = f'Current batch {n_batch+1} of {batches}.'
time_output = 'ETA : %i:%2i' % (eta_time//60, int(eta_time) % 60)
print(batch_output + ' ' + time_output)
batch = data[batch_size * n_batch:batch_size * (n_batch+1)]
batch = np.array(batch).reshape(-1, 1)
distance_matrix = squareform(pdist(batch, metric))
db = DBSCAN().fit(distance_matrix)
for i, v in enumerate(db.labels_):
if v == -1:
filtered_data += [batch[i]]
return filtered_data
| true
|
f7709b841d2cf7a9c54c7a2015580ad9e47d93a0
|
Python
|
gaoliming123/learn
|
/seq2seq/models/linear.py
|
UTF-8
| 1,154
| 3.09375
| 3
|
[] |
no_license
|
import torch.nn as nn
class Linear(nn.Module):
"""
This context vector, generated by the encoder, will be used as the initial hidden state of the decoder.
In case that their dimension is not matched, a linear layer should be used to transformed the context vector
to a suitable input (shape-wise) for the decoder cell state (including the memory(Cn) and hidden(hn) states).
The shape mismatch is True in the following conditions:
1. The hidden sizes of encoder and decoder are the same BUT we have a bidirectional LSTM as the Encoder.
2. The hidden sizes of encoder and decoder are NOT same.
3. ETC?
"""
def __init__(self, hidden_size_encoder, hidden_size_decoder):
super(Linear, self).__init__()
num_directions = 1
self.linear_connection_op = nn.Linear(num_directions * hidden_size_encoder, hidden_size_decoder)
self.connection_possibility_status = num_directions * hidden_size_encoder == hidden_size_decoder
def forward(self, input):
if self.connection_possibility_status:
return input
else:
return self.linear_connection_op(input)
| true
|
b9a0808db0a8cf23d77601c9f212f2ce4dc2fd99
|
Python
|
tnzw/tnzw.github.io
|
/py3/def/posixpath2.py
|
UTF-8
| 14,296
| 2.65625
| 3
|
[] |
no_license
|
# posixpath2.py Version 1.1.1
# Copyright (c) 2023 <tnzw@github.triton.ovh>
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# http://www.wtfpl.net/ for more details.
def posixpath2(os_module=None, *, use_environ=True, supports_unicode_filenames=False, get_user_home=None, keep_double_initial_slashes=True):
_module__func = posixpath2
_module__name__ = _module__func.__name__ if __name__ == '__main__' else (__name__ + '.' + _module__func.__name__)
#if __name__ != '__main__': _module__name__ = __name__ + '.' + _module__name__
try: export = __builtins__.__class__(_module__name__)
except AttributeError:
class _module__class__: pass
export = _module__class__()
export.__name__ = _module__name__
export.__doc__ = _module__func.__doc__
export._mk_module = _module__func
# beginning of module #
__all__ = [
'curdir', 'pardir', 'sep', 'altsep', 'extsep', 'pathsep',
'basename', 'commonpath', 'commonprefix', 'dirname', 'isabs', 'join',
'normcase', 'normpath', 'relpath', 'split', 'splitdrive', 'splitext',
'supports_unicode_filenames', 'samestat',
]
# https://docs.python.org/3/library/os.path.html
export.os = os_module
curdir = '.'
pardir = '..'
sep = '/'
altsep = None
extsep = '.'
pathsep = ':'
def _check_arg_types(funcname, *args):
# Copied from https://github.com/python/cpython/blob/3.11/Lib/genericpath.py#L144
hasstr = hasbytes = False
for s in args:
if isinstance(s, str): hasstr = True
elif isinstance(s, bytes): hasbytes = True
else: raise TypeError(f'{funcname}() argument must be str, bytes, or os.PathLike object, not {s.__class__.__name__!r}') from None
if hasstr and hasbytes: raise TypeError("Can't mix strings and bytes in path components") from None
if os_module is None:
def _fspath(path):
# Inspired by https://github.com/python/cpython/blob/3.11/Lib/os.py#L1036
if isinstance(path, (str, bytes)): return path
path_type = type(path)
try: fspath_func = path_type.__fspath__
except AttributeError: raise TypeError('expected str, bytes or os.PathLike object, not ' + path_type.__name__) from None
path_repr = fspath_func(path)
if isinstance(path_repr, (str, bytes)): return path_repr
raise TypeError(f'expected {path_type.__name__}.__fspath__() to return str or bytes, not {type(path_repr).__name__}')
export._fspath = _fspath
else:
def _fspath(s): return os_module.fspath(s) # do not use `_fspath = os_module.fspath`
# Pure path operations (uses os.fspath anyway which is part of os module but not a syscall actualy)
def basename(path):
# Algorithm copied from https://github.com/python/cpython/blob/3.11/Lib/posixpath.py#L140
# `PurePosixPath(...).name` returns different result than `posixpath.basename()`.
"""Returns the final component of a pathname"""
path = _fspath(path)
sep = b'/' if isinstance(path, bytes) else '/'
i = path.rfind(sep) + 1
return path[i:]
def commonpath(paths):
# Algorithm copied from https://github.com/python/cpython/blob/3.11/Lib/posixpath.py#L527
"""Given a sequence of path names, returns the longest common sub-path."""
if not paths: raise ValueError('commonpath() arg is an empty sequence')
paths = (*(_fspath(p) for p in paths),) # use our custom fspath
if isinstance(paths[0], bytes): sep = b'/'; curdir = b'.'
else: sep = '/'; curdir = '.'
try:
split_paths = [p.split(sep) for p in paths]
try: isabs, = {p[:1] == sep for p in paths}
except ValueError: raise ValueError("Can't mix absolute and relative paths") from None
split_paths = [[c for c in s if c and c != curdir] for s in split_paths] # removes empty names, curdir names and root
s1 = min(split_paths); s2 = max(split_paths); common = s1
for i, c in enumerate(s1):
if c != s2[i]:
common = s1[:i]
break
return (sep if isabs else sep[:0]) + sep.join(common)
except (TypeError, AttributeError):
_check_arg_types('commonpath', *paths)
raise
def _commonprefix(m):
# Algorithm copied from https://github.com/python/cpython/blob/3.11/Lib/genericpath.py#L69
# PurePath() is useless here as this method does not care of path mechanism.
s1 = min(m); s2 = max(m)
for i, c in enumerate(s1):
if c != s2[i]: return s1[:i]
return s1
def commonprefix(m):
"""Given a list of pathnames, returns the longest common leading component"""
if not m: return ''
if not isinstance(m[0], (list, tuple)): m = (*(_fspath(_) for _ in m),)
return _commonprefix(m)
def dirname(path):
# Algorithm copied from https://github.com/python/cpython/blob/3.11/Lib/posixpath.py#L150
# `PurePosixPath(...).parent.as_posix()` returns different result than `posixpath.dirname()` does.
"""Returns the directory component of a pathname"""
path = _fspath(path)
sep = b'/' if isinstance(path, bytes) else '/'
i = path.rfind(sep) + 1
head = path[:i]
if head and head != sep * len(head): head = head.rstrip(sep)
return head
def _isabs(fspath): return fspath.startswith(b'/' if isinstance(fspath, bytes) else '/') #return PurePosixPath(path).is_absolute()
def isabs(path): return _isabs(_fspath(path))
def _join(fspath, *fspaths):
# Algorithm copied from https://github.com/python/cpython/blob/3.11/Lib/posixpath.py#L71
# `PurePosixPath(...).joinpath(...).as_posix()` returns different result than `posixpath.join()` does.
sep = b'/' if isinstance(fspath, bytes) else '/'
path = fspath
try:
if not fspaths: path[:0] + sep #23780: Ensure compatible data type even if p is null.
for b in fspaths:
if b.startswith(sep): path = b
elif not path or path.endswith(sep): path += b
else: path += sep + b
return path
except (TypeError, AttributeError, BytesWarning):
_check_arg_types('join', fspath, *fspaths)
raise
def join(path, *paths):
"""Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded. An empty last part will result in a path that
ends with a separator."""
return _join(*(_fspath(p) for p in (path,) + paths))
def normcase(path): return _fspath(path) # ~noop
def _normpath(fspath):
# Algorithm copied from https://github.com/python/cpython/blob/3.11/Lib/posixpath.py#L350
if isinstance(fspath, bytes): sep = b'/'; empty = b''; dot = b'.'; dotdot = b'..'
else: sep = '/'; empty = ''; dot = '.'; dotdot = '..'
if fspath == empty: return dot
if fspath.startswith(sep): initial_slashes = 2 if keep_double_initial_slashes and fspath.startswith(sep * 2) and not fspath.startswith(sep * 3) else 1
else: initial_slashes = 0
comps = fspath.split(sep)
new_comps = []
for comp in comps:
if comp in (empty, dot): pass
elif comp != dotdot or (not initial_slashes and not new_comps) or (new_comps and new_comps[-1] == dotdot): new_comps.append(comp)
elif new_comps: new_comps.pop()
comps = new_comps
fspath = sep.join(comps)
if initial_slashes: fspath = sep * initial_slashes + fspath
return fspath or dot
def normpath(path):
"""Normalize path, eliminating double slashes, etc."""
return _normpath(_fspath(path))
def relpath(path, start=None):
# Algorithm adapted from https://github.com/python/cpython/blob/3.11/Lib/posixpath.py#L486
# Handles a pure path version of relpath() if os_module is None.
# /!\ On windows: posixpath.abspath('..') returns '..'! So we can't compare abspath nor relpath from original behavior!
"""Return a relative version of a path"""
if not path: raise ValueError('no path specified')
path = _fspath(path)
if isinstance(path, bytes): curdir = b'.'; sep = b'/'; pardir = b'..'
else: curdir = '.'; sep = '/'; pardir = '..'
start = curdir if start is None else _fspath(start)
try:
if _isabs(path) != _isabs(start):
if os_module is None: raise ValueError("Can't mix absolute and relative paths")
path = _abspath(path); start = _abspath(start)
else:
path = _normpath(path); start = _normpath(start)
start_list = [x for x in start.split(sep) if x and x != curdir] # removes empty names, curdir names and root
path_list = [x for x in path.split(sep) if x and x != curdir] # removes empty names, curdir names and root
i = len(_commonprefix([start_list, path_list]))
rel_list = [pardir] * (len(start_list) - i) + path_list[i:]
if not rel_list: return curdir
return _join(*rel_list)
except (TypeError, AttributeError, BytesWarning, DeprecationWarning):
_check_arg_types('relpath', path, start)
raise
def split(path):
# Algorithm copied from https://github.com/python/cpython/blob/3.11/Lib/posixpath.py#L100
"""Split a pathname. Returns tuple "(head, tail)" where "tail" is
everything after the final slash. Either part may be empty."""
path = _fspath(path)
sep = b'/' if isinstance(path, bytes) else '/'
i = path.rfind(sep) + 1
head, tail = path[:i], path[i:]
if head and head != sep * len(head): head = head.rstrip(sep)
return head, tail
def splitdrive(path):
"""Split a pathname into drive and path. On Posix, drive is always empty."""
path = _fspath(path)
return path[:0], path
def splitext(path):
# Algorithm refactored from https://github.com/python/cpython/blob/3.11/Lib/genericpath.py#L121
"""Split the extension from a pathname.
Extension is everything from the last dot to the end, ignoring
leading dots. Returns "(root, ext)"; ext may be empty."""
path = _fspath(path)
if isinstance(path, bytes): sep = b'/'; dot = b'.'
else: sep = '/'; dot = '.'
si = path.rfind(sep)
di = path.rfind(dot)
if di > si:
fi = si + 1
while fi < di:
if path[fi:fi + 1] != dot: return path[:di], path[di:]
fi += 1
return path, path[:0]
# Non-OS operations
def samestat(s1, s2): return s1.st_ino == s2.st_ino and s1.st_dev == s2.st_dev
if os_module is not None:
__all__ += [
'abspath', 'exists', 'lexists', 'isfile', 'isdir', 'islink',
'getatime', 'getmtime', 'getctime', 'getsize',
'samefile', 'sameopenfile',
'realpath', 'expanduser',
# defpath, ismount, expandvars
]
if hasattr(os_module, 'devnull'):
__all__ += ['devnull']
devnull = os_module.devnull
# OS operations
# FileNotFoundError happens when a node does not exists while traversing a path
# ex: /dir/dir/noent/noent
# ^
# NotADirectoryError happens when a file is traversed like a dir
# ex: /dir/dir/file/noent
# ^
def _abspath(fspath):
cwd = os_module.getcwdb() if isinstance(fspath, bytes) else os_module.getcwd()
return _normpath(_join(cwd, fspath))
def abspath(path): return _abspath(os_module.fspath(path))
def exists(path):
try: s = os_module.stat(path)
except (NotADirectoryError, FileNotFoundError): return False
return True
def lexists(path):
try: s = os_module.lstat(path)
except (NotADirectoryError, FileNotFoundError): return False
return True
def isfile(path):
try: s = os_module.stat(path)
except (NotADirectoryError, FileNotFoundError): return False
return stat.S_ISREG(s.st_mode)
def isdir(path):
try: s = os_module.stat(path)
except (NotADirectoryError, FileNotFoundError): return False
return stat.S_ISDIR(s.st_mode)
def islink(path):
try: s = os_module.lstat(path)
except (NotADirectoryError, FileNotFoundError): return False
return stat.S_ISLNK(s.st_mode)
def getatime(path): return os_module.stat(path).st_atime
def getctime(path): return os_module.stat(path).st_ctime # caution! windows ctime != linux ctime
def getmtime(path): return os_module.stat(path).st_mtime
def getsize(path): return os_module.stat(path).st_size
def samefile(f1, f2): return samestat(os_module.stat(f1), os_module.stat(f2))
def sameopenfile(f1, f2): return samestat(os_module.fstat(f1), os_module.fstat(f2))
def realpath(path, *, strict=False): # documentation says that we "should not" use this function anyway
return os_realpath(path, strict=strict, os_module=os_module)
def expanduser(path):
# Algorithm adapted from https://github.com/python/cpython/blob/3.11/Lib/posixpath.py#L229
# Handles more options from module configuration, like the use of get_user_home().
"""Expand ~ and ~user constructions."""
path = os_module.fspath(path)
is_bytes = isinstance(path, bytes)
if is_bytes: tilde = b'~'; sep = b'/'
else: tilde = '~'; sep = '/'
if not path.startswith(tilde): return path
i = path.find(sep, 1)
if i < 0: i = len(path)
if i == 1:
if use_environ and hasattr(os_module.environ) and 'HOME' in os_module.environ: userhome = os_module.environ['HOME']
# XXX also use a fake pwd module?
elif get_user_home is not None: userhome = get_user_home(path[1:1])
else: return path
else:
# XXX also use a fake pwd module?
if get_user_home is not None: userhome = get_user_home(path[1:i])
else: return path
if userhome is None: return path
if is_bytes:
if not isinstance(userhome, bytes): userhome = os_module.fsencode(userhome)
else:
if not isinstance(userhome, str): userhome = os_module.fsdecode(userhome)
userhome = userhome.rstrip(sep)
return (userhome + path[i:]) or sep
__export__ = ['__all__', *__all__]
# end of module #
_module__locals = locals()
for _ in _module__locals.get('__export__', _module__locals):
if not hasattr(export, _): setattr(export, _, _module__locals[_])
return export
posixpath2 = posixpath2()
posixpath2._required_globals = ['stat', 'os_realpath']
| true
|
85e4157b15c92eb318d6eed6c6763fd9384379de
|
Python
|
Sinan-96/BoligPrisTracker
|
/database/dataBaseFunctions.py
|
UTF-8
| 1,496
| 3
| 3
|
[] |
no_license
|
import sqlite3
from datetime import datetime
"""
Functions that sends a variety
of queries to the database. These queries are
adding, altering and removing data from the
different tables of the database.
"""
#Conn is the database
def addBolig(pris:int,by:int,bydel:int,gate:int,conn):
query = "INSERT INTO Bolig VALUES (?, ?, ?, ?);"
data_tuple = (pris,by,bydel,gate)
conn.execute(query,data_tuple)
def addBy(navn:str,conn):
query = "INSERT INTO By VALUES (?, ?, ?);"
data_tuple = (navn,0)
conn.execute(query,data_tuple)
def addBydel(navn:str,by:int,conn):
query = "INSERT INTO Bydel VALUES (?, ?, ?);"
data_tuple = (by,navn,0)
conn.execute(query,data_tuple)
def addGate(navn:str,bydel:int,conn):
query = "INSERT INTO Gate VALUES (?, ?, ?);"
data_tuple = (bydel,navn,0)
conn.execute(query,data_tuple)
#Gets GJpris for a specific date from a by,bydel or gate
def getGJpris(dato:datetime,table:str,navn:str,conn):
#TODO may have to change this query to fit the tables
query = f"SELECT GjPris" \
f"FROM {table}" \
f"WHERE Navn = {navn} AND Dato = {dato}"
return conn.execute(query)
#Meant to be called in regular time intervals, every day for example
#Takes table name as argument
def updateGjPris(table:str,conn):
query = f"UPDATE {table}" \
f"FROM Bolig ,{table}" \
f"SET GjPris = SUM(Bolig.Pris)" \
f"WHERE {table}.ID = Bolig.{table}"
conn.execute(query)
| true
|
1f8e3fce61404645c5f0554cda86dc6ad843ea0d
|
Python
|
teotiwg/studyPython
|
/200/pt3/084.py
|
UTF-8
| 195
| 3.15625
| 3
|
[] |
no_license
|
txt1 = 'A'
txt2 = 'Hi'
txt3 = 'Warcraft Three'
txt4 = '3PO'
ret1 = txt1.isalpha()
ret2 = txt2.isalpha()
ret3 = txt3.isalpha()
ret4 = txt4.isalpha()
print(ret1)
print(ret2)
print(ret3)
print(ret4)
| true
|
11db749c6ace2fb754d543560c0035cf05cfb4f8
|
Python
|
seadsystem/Backend
|
/Analysis and Classification/Analysis/Code/Vince's_Code/Analysis/Testing Data/vince_Analysis.py
|
UTF-8
| 9,242
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
##
# Analysis.py
#
# Author: Vincent Steffens, vsteffen@ucsc.edu
# Date: 16 November 2014
#
# Produces a mean power spectrum of raw SEAD plug current
# data, normalized by total current.
# Outputs to spectrum in a numpy array to stdout or a text
# file, each array element on a line.
##
#For numerical analysis
import numpy as np
import math
#For visualization
import matplotlib.pyplot as pyp
#For manipulating command-line arguments
import sys
#For handling files
import os
#For using regular expressions
import re
def init():
#Check for proper number of arguments, die if necessary
#max args = 2 + number of valid options
max_args = 10
if len(sys.argv) < 2:
print "Usage: Analysis.py [-cfhpvVw] source_file"
print "Call with -h for help"
sys.exit(-1)
if len(sys.argv) > max_args:
print "Usage: Analysis.py [-cfhpvVw] source_file"
print "Call with -h for help"
sys.exit(-2)
#handle calling with only Analysis.py -h
if sys.argv[1] == '-h':
print_help()
exit()
#Check for options. Break the option area of argv into a list of
#characters. Make a list of those that are valid, and a list of
#those that aren't. Let the user know if they endered an invalid
#option.
#When adding options, be sure to add a description to the -h section
#below
valid_options = 'cdfhpvVw'
alleged_options = list(set(''.join(sys.argv[1:-1])))
options = [x for x in alleged_options if re.search(x, valid_options)]
non_options = [x for x in alleged_options if x not in options and x != '-']
for i in non_options:
print "Ignoring invalid option: \'%s\'" % (i)
return options
def import_and_trim():
Currents = []
amp_ids = [70, 66, 74, 62, 78, 58, 50, 14, 54]
#Try to open source file for reading
filename = sys.argv[len(sys.argv) - 1]
if os.path.isfile(filename):
with open(filename) as f:
#Check the first element of the first line.
#if it's "sensor_id", it's the old format
#if it's "1", it's the new format
line = f.readline().split(',')
#New format
if len(line) == 2:
#discard first one
for line in f:
line = line.split(',')
Currents.append(line[1])
elif line[0] == '1':
if line[1] == 'I':
Currents.append(line[3])
for line in f:
line = line.split(',')
if line[1] == 'I':
Currents.append(line[2])
else:
for line in f:
line = re.split(',|\t', line)
if int(line[0]) in amp_ids:
Currents.append(line[1])
else:
print "Analysis: cannot open file:", filename
#Convert currents to milliamps
Currents = [ 27*float(x)/1000 for x in Currents ]
return Currents
def produce_blocklist():
blocklist = []
data_length = len(Currents) #or Times, just to de-specify
i = 0
while i < data_length:
if i + 200 > len(Currents):
break
blocklist.append(Currents[i:i+blockwidth])
i += blockwidth
return blocklist
def produce_mean_normalized_power_spectrum(blocklist):
#question: mean then normalize, or normalized then mean?
#doesn't matter because multiplication commutes
#units are in square amps
#here's why:
#original was in amps
#take ft (not fft)
#break up original into frequency components
#view from frequency perspective
#frequency components are in amps
#take mod square using absolute
#mod square(a + bi) = a^2 + b^2
#units are now in square amps per hz
#integrate it in piecese from a to a + blockwidth
#now you have units of amps sqared
#put those in an array
#oh yeah
#so now we have a power spectrum for an amp signal (odd sounding)
#in amps squared
#Produce power spectrum, sum
power_spectrum = np.square(np.absolute(np.fft.rfft(blocklist[0])))
sum_power_spectrum = power_spectrum
for i in xrange(1, len(blocklist)):
power_spectrum = np.square(np.absolute(np.fft.rfft(blocklist[i])))
sum_power_spectrum = np.add(sum_power_spectrum, power_spectrum)
#Take integral
total_sq_amps = 0.0
for i in xrange(0, len(sum_power_spectrum)):
total_sq_amps += sum_power_spectrum[i]
#Normalize by total amps measured
normalized_power_spectrum = sum_power_spectrum * (1/total_sq_amps)
#Finish taking mean
mean_normalized_spectrum = normalized_power_spectrum / len(blocklist)
return mean_normalized_spectrum
def display(spectrum):
template = np.ones(len(spectrum))
#Get the plot ready and label the axes
pyp.plot(spectrum)
max_range = int(math.ceil(np.amax(spectrum) / standard_deviation))
for i in xrange(0, max_range):
pyp.plot(template * (mean + i * standard_deviation))
pyp.ylabel('Amps Squared')
pyp.title('Mean Normalized Power Spectrum')
if 'V' in Options:
pyp.show()
if 'v' in Options:
tokens = sys.argv[-1].split('.')
filename = tokens[0] + ".png"
input = ''
if os.path.isfile(filename):
input = raw_input("Error: Plot file already exists! Overwrite? (y/n)\n")
while input != 'y' and input != 'n':
input = raw_input("Please enter either \'y\' or \'n\'.\n")
if input == 'y':
pyp.savefig(filename)
else:
print "Plot not written."
else:
pyp.savefig(filename)
def write_output():
tokens = sys.argv[-1].split('.')
filename = tokens[0] + ".txt"
#If a file with the same name already exists,
#check before overwriting and skip if necessary
if os.path.isfile(filename):
input = raw_input("Error: Output file already exists! Overwrite? (y/n) : ")
while input != 'y' and input != 'n':
input = raw_input("Please enter either \'y\' or \'n\'.\n")
if input == 'n':
print "Writing skipped."
return
#Write
out = open(filename, 'w')
for element in Spectrum:
out.write(str(element) + ",")
out.close()
def print_help():
print "\nAnalysis.py."
print "Used to produce a mean power spectrum of raw SEAD plug current data, normalized by total current"
print "\nCall using this syntax:"
print "$ python Analysis.py [-fhpvVw] [input file]"
print ""
print "Input: Raw, 4-column SEAD plug data"
print "Output: Either or both of:"
print "1. Numpy array printed to stdout."
print "2. Spectrum written to text file."
print "\nOptions may be arranged in any order, and in any number of groups"
print ""
print "-c:\t Classify. Match input data to a known group."
print " This only works for microwaves, lamps, and laptop computers"
print "-f:\t Fragmented data. This handles gaps in the data."
print "-h:\t Help. Display this message."
print "-p:\t Print. Print numpy array containing spectrum to terminal."
print "-V:\t View. Display plot of spectrum, with the mean and multiples of the standard deviation."
print "-v:\t Visualize. Print plot to file."
print "-w:\t Write. Write spectrum to file, each array element on its own line"
print "\nExamples:"
print "1: Handle fragmented data, view plot, write spectrum to file"
print " python Analysis.py -vfw 1_raw.csv"
print " python Analysis.py -f -wv 1_raw.csv"
print "2: View plot of spectrum"
print " python Analysis.py -V 1_raw.csv"
def classify(spectrum):
variation_coefficient = standard_deviation / mean
#count regions
count = 0
flag = 0
threshold = mean + standard_deviation
for i in xrange(0, len(spectrum)):
if flag == 0 and spectrum[i] > threshold:
flag = 1
count += 1
continue
elif flag == 1 and spectrum[i] < threshold:
flag = 0
output_string = sys.argv[-1]
if len(output_string) < 24:
output_string = output_string + "\t"
if variation_coefficient < 3.511:
print "%s\t was recorded from a laptop computer." % (output_string)
return
elif np.amax(spectrum) < 0.01 or count > 1:
print "%s\t was recorded from a microwave." % (output_string)
return
else:
print "%s\t was recorded from a lamp." % (output_string)
#Execution begins here
blockwidth = 200
Currents = []
Times = []
Options = init()
Currents = import_and_trim()
Blocklist = produce_blocklist()
Spectrum = produce_mean_normalized_power_spectrum(Blocklist)
#mean and std are used by both display() and classify()
#only calculate once.
mean = np.mean(Spectrum)
standard_deviation = np.std(Spectrum)
#This should be done first
if 'h' in Options:
print_help()
if 'c' in Options:
classify(Spectrum)
if 'p' in Options:
print Spectrum
if 'w' in Options:
write_output()
if 'v' in Options or 'V' in Options:
display(Spectrum)
| true
|
1d364a408f91bac7b5fa6ba7287503445d0aa1b5
|
Python
|
geosaleh/Sorting_Algorithms
|
/sort_barchart.py
|
UTF-8
| 4,351
| 3.515625
| 4
|
[] |
no_license
|
# Collection of sorting functions
#
# follow us on twitter @PY4ALL
#
import numpy as np
import matplotlib.pyplot as plt
import random
plt.ion()
x = np.arange(1, 20)
fig, ax = plt.subplots(2, 2, dpi=120)
plt.show()
my_list = np.arange(1, 20)
random.shuffle(my_list)
bubble_rects = ax[0][0].bar(x, my_list, align='center')
insertion_rects = ax[0][1].bar(x, my_list, align='center')
selection_rects = ax[1][0].bar(x, my_list, align='center')
shell_rects = ax[1][1].bar(x, my_list, align='center')
plt.tight_layout()
ax[0][0].set_ylim(0, 20)
ax[0][0].set_title('Bubble Sort', pad=-40)
ax[0][1].set_ylim(0, 20)
ax[0][1].set_title('Insertion Sort', pad=-40)
ax[1][0].set_ylim(0, 20)
ax[1][0].set_title('Selection Sort')
ax[1][1].set_ylim(0, 20)
ax[1][1].set_title('Shell Sort')
def bubble_sort(inlist):
n = len(inlist)
out_list = [*inlist]
for i in range(n-1):
swapped = False
for j in range(n-1):
# Compare elements
if out_list[j] > out_list[j+1]:
# Swap elements
out_list[j+1], out_list[j] = out_list[j], out_list[j+1]
swapped = True
# Update the plot after swapping the elemnts
for rect, h in zip(bubble_rects, out_list):
rect.set_height(h)
plt.draw()
plt.pause(0.02)
# Break the main loop if no more swap
if not swapped:
break
return out_list
def insertion_sort(inlist):
n = len(inlist)
out_list = [*inlist]
for i in range(n):
# Select element to be inserted
value_to_insert = out_list[i]
hole_position = i
# Locate hole position for the element to be inserted
while hole_position > 0 and out_list[hole_position-1] > value_to_insert:
out_list[hole_position] = out_list[hole_position-1]
hole_position = hole_position - 1
for rect, h in zip(insertion_rects, out_list):
rect.set_height(h)
plt.draw()
plt.pause(0.02)
# Insert the elemnt at hole position
out_list[hole_position] = value_to_insert
# Update the plot after inserting the elemnt
for rect, h in zip(insertion_rects, out_list):
rect.set_height(h)
plt.draw()
plt.pause(0.02)
return out_list
def selection_sort(inlist):
n = len(inlist)
out_list = [*inlist]
for i in range(n):
# Set current element as minimum
_min = i
# Check the elements to get the minimum
for j in range(i+1, n):
if out_list[j] < out_list[_min]:
_min = j
# Swap the minimum element with the current element
if _min != i:
out_list[i], out_list[_min] = out_list[_min], out_list[i]
# Update the plot after swapping the elemnts
for rect, h in zip(selection_rects, out_list):
rect.set_height(h)
plt.draw()
plt.pause(0.02)
return out_list
def shell_sort(inlist):
out_list = [*inlist]
interval = 0
# Calculate interval
while interval < len(out_list):
interval = interval * 3 + 1
while interval > 0:
for outer in range(interval, len(out_list)):
# Select value to be inserted
value_to_insert = out_list[outer]
inner = outer
# Shift element toward right
while inner > interval - 1 and out_list[inner - interval] >= value_to_insert:
out_list[inner] = out_list[inner - interval]
inner = inner - interval
# Update the plot after shifting the elemnt
for rect, h in zip(shell_rects, out_list):
rect.set_height(h)
plt.draw()
plt.pause(0.02)
# Insert the element at the hole position
out_list[inner] = value_to_insert
# Update the plot after inserting the element
for rect, h in zip(shell_rects, out_list):
rect.set_height(h)
plt.draw()
plt.pause(0.02)
interval = (interval - 1) // 3
return out_list
# Run all sorting algorithms
bubble_sort(my_list)
insertion_sort(my_list)
selection_sort(my_list)
shell_sort(my_list)
| true
|
cafc150115a8a61f275bd8d764bdc9ff4e1d63a3
|
Python
|
ISmilingFace/weather
|
/wetapp/views.py
|
UTF-8
| 1,100
| 2.515625
| 3
|
[] |
no_license
|
import json
from urllib.request import urlopen
import requests
from django.shortcuts import render
# Create your views here.
class GetWeather(object):
def __init__(self):
self.weather_url = 'http://api.map.baidu.com/telematics/v3/weather?location={}&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'
self.ip_url = 'https://api.map.baidu.com/location/ip?ak=KHkVjtmfrM6NuzqxEALj0p8i1cUQot6Z'
def get_location(self):
loc_js = urlopen(self.ip_url).read().decode()
loc_dict = json.loads(loc_js)
city = loc_dict['content']['address_detail']['city']
return city
def get_data(self, location):
url = self.weather_url.format(location)
js_content = requests.get(url).text
js_dict = json.loads(js_content)
return js_dict
def index(request):
weather = GetWeather()
location = weather.get_location()
location = request.GET.get('location', location)
data_list = weather.get_data(location)['results'][0]
return render(request, template_name='index.html', context=data_list)
| true
|
2ccaf5429947bba985ea88a8264979357c1856dc
|
Python
|
topdeliremegagroove/Game-of-life-CPES
|
/Ancienne version/rapide.py
|
UTF-8
| 8,105
| 3.03125
| 3
|
[] |
no_license
|
from tkinter import *
from functools import partial
from time import sleep
root = Tk()
root.title("Le Jeu de la Vie")
# A faire : changer la taille de la grille ;
# détecter la taille du fichier lu (ou en faire une par défaut, et dans ce cas, centrer les coordonnées) ;
# --> faire avancer étape par étape
# bouton de réinitialisation
taille = 30
pixel = 650
c = Canvas(root, height = pixel, width = pixel, bg="grey")
c.grid(row=0, column=0, rowspan = 30) #creation de la grille à gauche
side = pixel/taille
grid_display = [] #liste qui stockera la couleur des cellules
def change_col(coord, _) : # changement de couleur des cellules
i,j = coord
if c.itemcget(grid_display[i][j], "fill") == "white" :
c.itemconfig(grid_display[i][j], fill="black")
else :
c.itemconfig(grid_display[i][j], fill="white")
def initialisation() : # implémentation des cellules pour initialiser la grille et les contrôles
for i in range(taille) :
grid_display.append([])
for j in range(taille) :
grid_display[i].append(c.create_rectangle(side*j, side*i, side*(j+1), side*(i+1), width=1, fill="white", tags=f"{i}_{j}"))
c.tag_bind(f"{i}_{j}","<Button-1>", partial(change_col, (i,j)))
global entry_file, launch_button, speed_scale, step, step_label, save_button, save_entry
# Entrée du fichier d'initialistion
entry_file = Entry(root, width = 30)
entry_file.grid(row=4, column=2)
# Bouton de départ
launch_button = Button(root, command=grid_generation, text=" Go ! ")
launch_button.grid(row=5, column=2)
# Curseur de la vitesse
speed_scale = Scale(root, orient="horizontal", from_ = 0, to = 16, resolution=0.1, tickinterval=2, label="Speed (steps/sec)", length = 330)
speed_scale.set(2)
speed_scale.grid(row=7, column=2, rowspan=3)
# Affichage de l'étape actuelle
step = 0
step_label = Label(root, text=f"Step {step}")
step_label.grid(row=11, column=2)
# Bouton pour sauvegarder l'affichage actuel
save_button = Button(root, command=sauvegarde, text="Save the grid")
save_button.grid(row=15, column=2)
# Et une boîte d'entrée pour le nom du fichier
save_entry = Entry(root, width=30)
save_entry.grid(row=14, column=2)
def sauvegarde() :
file_name = save_entry.get()
if file_name == "" :
file_name = "Sauvegarde_tmp"
f = open(f"{file_name}.txt", "w")
for i in range(len(grid_display)) :
for j in range(len(grid_display)) :
if c.itemcget(grid_display[i][j], "fill") == "black" :
f.write(f"{i} {j}\n")
f.close
def grid_generation() : # création de la première grille 0_1
for i in range(len(grid_display)) : # désactivation des cases
for j in range(len(grid_display)) :
c.dtag(grid_display[i][j], f"{i}_{j}")
if entry_file.get() != "" :
file = open(f"{entry_file.get()}.txt", "r")
lines = file.readlines()
file.close()
grid = [[0]*taille for _ in range(taille)]
for i in range(len(lines)) :
coords = lines[i].split()
grid[int(coords[0])][int(coords[1])] = 1
else :
grid = []
for i in range(len(grid_display)) :
grid.append([])
for j in range(len(grid_display)) :
if c.itemcget(grid_display[i][j], "fill") == "white" :
grid[i].append(0)
else :
grid[i].append(1)
# Sauvegarde automatique de la position de départ
sauvegarde()
first_grid = [[0]*taille for _ in range(taille)]
for x in range(1, taille-1) :
for y in range(1, taille-1) :
if grid[x][y] == 1 :
first_grid[x][y] += 1 #indique que la cellule était vivante au tour d'avant
first_grid[x-1][y-1] += 2
first_grid[x][y-1] += 2
first_grid[x+1][y-1] += 2
first_grid[x-1][y] += 2
first_grid[x+1][y] += 2
first_grid[x-1][y+1] += 2
first_grid[x][y+1] += 2
first_grid[x+1][y+1] += 2
#boucle d'initialisation à partir de la grille racine
entry_file.destroy()
launch_button.destroy()
save_button.destroy()
save_entry.destroy()
global pause_button
# Bouton de pause
pause_button = Button(root, text="Pause", command=partial(pause, grid))
pause_button.grid(row=0, column = 2)
global reset_button
reset_button = Button(root, command=reset, text="Reset") #le bouton reset permet de revenir à la grille vierge
reset_button.grid(row=16, column=2)
update(first_grid)
# generation_plateau(first_grid)
def update(grid) : # fonction d'actualisation des Labels à partir d'une grille donné.
global step
step += 1
step_label.configure(text=f"Step {step}") #step est le compteur de tour
for i in range(len(grid)) :
for j in range(len(grid)) :
if grid[i][j] % 2 == 0 :
color = "white"
else :
color = "black"
c.itemconfig(grid_display[i][j], fill = color) #change l'objet du canva, change la couleur du rectangle dans grid display
new_grid = main_evaluate(grid) # fonction qui calcule la grille suivante
if grid == new_grid : # arrêt du programme quand il n'y a plus d'évolution
return
speed = speed_scale.get()
if speed != 0 :
root.after(int(1000/speed), update, new_grid) #pendant un certain temps j'attends, puis j'appelle la fonction update
else :
pause(new_grid)
def main_evaluate(grid) :
stock = [[0]*len(grid) for _ in range(len(grid))]
for x in range(1, len(grid)-1) :
for y in range(1, len(grid)-1) :
if grid[x][y] in [5, 6, 7] :
stock[x][y] += 1 #indique que la cellule était vivante au tour suivant
stock[x-1][y-1] += 2
stock[x][y-1] += 2
stock[x+1][y-1] += 2
stock[x-1][y] += 2
stock[x+1][y] += 2
stock[x-1][y+1] += 2
stock[x][y+1] += 2
stock[x+1][y+1] += 2
return stock
def pause(grid) :
speed_scale.set(0)
pause_button.configure(text="Resume", command=partial(resume, grid)) #le bouton pause pointe vers la fonction resume
global step_button
step_button = Button(root, text="Next step", command=partial(update_step_by_step, grid))
step_button.grid(row=5, column=2)
def resume(grid) :
step_button.destroy()
speed_scale.set(2)
pause_button.configure(text="Pause", command=partial(pause, grid)) #le bouton pause pointe vers la fonction pause
update(grid)
def update_step_by_step(grid) :
global step
step += 1
step_label.configure(text=f"Step {step}")
for i in range(len(grid)) :
for j in range(len(grid)) :
if grid[i][j] % 2 == 0 :
color = "white"
else :
color = "black"
c.itemconfig(grid_display[i][j], fill = color)
new_grid = main_evaluate(grid) # fonction qui calcule la grille suivante
if grid == new_grid : # arrêt du programme quand il n'y a plus d'évolution
step_button.configure(state=DISABLED)
pause_button.configure(command=partial(resume, new_grid))
step_button.configure(command=partial(update_step_by_step, new_grid))
def reset():
speed_scale.set(0)
c.delete("all")
step_label.destroy()
speed_scale.destroy()
pause_button.destroy()
reset_button.destroy()
#next_step.destroy()
initialisation()
initialisation()
root.mainloop()
| true
|
6d2803b80216de7df59c67840cf596ea93be4293
|
Python
|
valeriekamen/python
|
/rotate-image.py
|
UTF-8
| 3,322
| 4.15625
| 4
|
[] |
no_license
|
# Rotate a square matrix clockwise one rotation
import math
def get_new_position(start_i, start_j, lim):
# [0,0] -> [0,2]
# print(start_j, lim - start_i)
return start_j, lim - start_i
def rotate_image(input_matrix, number_times=None, start_i=0, start_j=0):
print(input_matrix, number_times, start_i, start_j)
lim = len(input_matrix)
if number_times == 0:
return input_matrix
if not number_times:
number_times = lim - 1
print(number_times)
# check if actually a square
for side in input_matrix:
if not len(side) == lim:
return False
starting_i = start_i
starting_j = start_j
# moving_i = start_i
# moving_j = start_j
# moving_val = input_matrix[moving_i][moving_j]
for n in range(number_times):
moving_i = start_i
moving_j = start_j
moving_val = input_matrix[moving_i][moving_j]
for n in range(0, 4):
print("moving", moving_val)
new_i, new_j = get_new_position(moving_i, moving_j, lim - 1)
next_moving_val = input_matrix[new_i][new_j]
input_matrix[new_i][new_j] = moving_val
moving_val = next_moving_val
moving_i = new_i
moving_j = new_j
start_j += 1
rotate_image(
input_matrix, math.floor(number_times / 2), starting_i + 1, starting_j + 1
)
print(input_matrix)
return input_matrix
assert rotate_image([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3],
]
assert rotate_image(
[[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]
) == [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]
assert rotate_image([[1, 2], [3, 4]]) == [[3, 1], [4, 2]]
assert rotate_image([[1]]) == [[1]]
"""
Works, maybe overly complicated
def rotate_image(input_matrix):
lim = len(input_matrix)
# check if actually a square
for side in input_matrix:
if not len(side) == lim:
return False
# list of proper length in order of final positions
new_nums = [None] * (lim ** 2)
for i in range(lim): # inside matrix
for j in range(lim): # inside row
num = input_matrix[i][j]
# new position in matrix is [(lim - 1) - j][i]
# ex: [0][0] moves to [0][2]
new_j = (lim - 1) - i
# new index in grand scheme is 3 * i + j
# ex: [0][2] is 3rd in list of 9 numbers, 3 * 0 + 2 as index 2
new_pos = (lim * j) + new_j
new_nums[new_pos] = num
# go through matrix and replace what has been calculated in new_nums
for i in range(lim): # inside matrix
for j in range(lim): # inside row
this_pos = (lim * i) + j
input_matrix[i][j] = new_nums[this_pos]
return input_matrix
Creates new matrix, does not change in place
def rotate_image(input_matrix):
# check if actually a square
for side in input_matrix:
if not len(side) == len(input_matrix):
return False
new_matrix = []
for i in range(len(input_matrix)):
new_row = []
for side in input_matrix:
new_row.append(side[i])
new_row.reverse()
new_matrix.append(new_row)
return new_matrix
"""
| true
|
1a46ffac355c4058bc6013f5f890188f188c83fc
|
Python
|
rickypeng99/codingDocFinder
|
/scraper_scripts/c_lib.py
|
UTF-8
| 1,867
| 2.875
| 3
|
[] |
no_license
|
# coding: utf-8
# In[1]:
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import re
import urllib
import pandas as pd
options = Options()
options.headless = True
browser = webdriver.Chrome('./chromedriver',options=options)
# In[2]:
title = []
description = []
links = []
Syntax = []
Text = []
# In[4]:
def get_js_soup(url,browser):
browser.get(url)
res_html = browser.execute_script('return document.body.innerHTML')
soup = BeautifulSoup(res_html,'html.parser') #beautiful soup object to be used for parsing html content
return soup
# In[5]:
dir_url = 'https://doc.bccnsoft.com/docs/cppreference_en/all_c_functions.html'
soup = get_js_soup(dir_url,browser)
# In[7]:
find = soup.find_all('td',class_='category-table-td')
# In[9]:
i = 0
while i < len(find):
a = find[i].get_text(separator=' ')
a = a.replace("\n","")
a = a.replace(" "," ")
title.append(a)
i += 1
a = find[i].get_text(separator=' ')
a = a.replace("\n","")
a = a.replace(" "," ")
description.append(a)
i += 1
# In[26]:
web_base = "https://doc.bccnsoft.com/docs/cppreference_en/"
# In[27]:
for link_holder in soup.find_all('td',class_='category-table-td'):
try:
rel_link = link_holder.find('a')['href']
links.append(web_base + rel_link)
except:
continue
# In[52]:
for url in links:
soupp = get_js_soup(url,browser)
try:
Syntax.append(soupp.find('pre',class_='syntax-box').get_text(separator=' '))
except:
Syntax.append(" ")
Text.append(soupp.getText())
# In[62]:
df = pd.DataFrame({'title':title, 'url':links, 'description':description, 'syntax':Syntax,
'text':Text })
# In[63]:
df.to_csv('C_Library.csv', index=False, encoding='utf-8')
| true
|
62239e799006db9c164ea0ff849088958ad6a67e
|
Python
|
ztxm/Python_level_1
|
/lesson6/task4.py
|
UTF-8
| 3,149
| 4.46875
| 4
|
[] |
no_license
|
"""
4) Реализуйте базовый класс Car. У данного класса должны быть следующие атрибуты: speed, color, name, is_police (булево).
А также методы: go, stop, turn(direction), которые должны сообщать, что машина поехала, остановилась, повернула (куда).
Опишите несколько дочерних классов: TownCar, SportCar, WorkCar, PoliceCar. Добавьте в базовый класс метод show_speed,
который должен показывать текущую скорость автомобиля. Для классов TownCar и WorkCar переопределите метод show_speed.
При значении скорости свыше 60 (TownCar) и 40 (WorkCar) должно выводиться сообщение о превышении скорости.
Создайте экземпляры классов, передайте значения атрибутов. Выполните доступ к атрибутам, выведите результат.
Выполните вызов методов и также покажите результат.
"""
class Car():
def __init__(self, speed, color, name, is_police=False):
self.speed = speed
self.color = color
self.name = name
self.is_police = is_police
def go(self):
return f"{self.name} Машина поехала"
def stop(self):
return f"{self.name} Машина остановилась"
def turn(self, direction):
if direction == "left":
return "повернула на лево"
if direction == "right":
return "повернула на право"
def show_speed(self):
return self.speed
class TownCar(Car):
def show_speed(self):
if self.speed > 60:
return f"Вы превысили скорость на {self.speed - 60}"
return self.speed
class SportCar(Car):
"""dsf"""
class WorkCar(Car):
def show_speed(self):
if self.speed > 40:
return f"Вы превысили скорость на {self.speed - 40}"
return self.speed
class PoliceCar(Car):
def __init__(self, speed, color, name, is_police=True):
super().__init__(speed, color, name, is_police)
my_car = Car(60, "silver", "Mazda")
my_town_car = TownCar(45, "black", "Volvo")
my_sport_car = SportCar(100, "Red", "Ferrari")
my_work_car = WorkCar(50, "white", "Gaz")
my_police_car = PoliceCar(0, "white", "Ford")
print(f"{my_car.name} {my_car.color}")
print(f"{my_town_car.name} {my_town_car.color} {my_town_car.is_police}")
print(f"{my_sport_car.name} {my_sport_car.color} {my_sport_car.turn('left')}")
my_sport_car.speed = 150
print(my_sport_car.go())
print(f"{my_sport_car.name} Скрость: {my_sport_car.show_speed()} км/ч")
print(my_sport_car.stop())
my_town_car.speed = 80
print(f"\n{my_town_car.name} {my_town_car.show_speed()} км/ч")
my_work_car.speed = 70
print(f"{my_work_car.name} {my_work_car.show_speed()} км/ч")
| true
|
80112411c19ac07dad1cca8e6c543817f1d8ba36
|
Python
|
croguerrero/pythonexercises
|
/bisiesto.py
|
UTF-8
| 360
| 3.765625
| 4
|
[] |
no_license
|
## Ano bisiesto
year = int(input("Year: "))
if year % 4 == 0:
if year % 100:
if year % 400:
print("This year {} is bisiesto".format(year))
else: print("This year {} is not bisiesto".format(year))
else:
print("This year {} is bisiesto".format(year))
else:
print("This year {} is not bisiesto ".format(year))
| true
|
e65bd24262ca1466d057bce241d1a2fb609da441
|
Python
|
swaroop1995/assignment
|
/ass2_12.py
|
UTF-8
| 330
| 3.796875
| 4
|
[] |
no_license
|
print("1)Monkey A and B are smiling")
print("2)Monkey A and B are not smiling")
print("3)Monkey A is smiling")
print("4)Monkey B is not smiling")
option=int(input("select the option:"))
if option==1 or option==2:
print("we are in trouble")
else:
if option==3 or option==4:
print("we are not in trouble")
| true
|
adf4029fd1527714922d0171a51ec0f5a87ac762
|
Python
|
latufla/EventSystem
|
/models/forms/form_base.py
|
UTF-8
| 189
| 2.578125
| 3
|
[] |
no_license
|
from wtforms import Form
class FormBase(Form):
def errors_str(self):
error = ""
for k, v in self.errors.items():
error += v[0] + '\n'
return error
| true
|
019406d342621ef9d77a4fd331576b064c8e299f
|
Python
|
linn24/mrt_route_suggestion
|
/mrt_app/initialize_data.py
|
UTF-8
| 1,964
| 2.859375
| 3
|
[] |
no_license
|
import sys
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.expression import true
from sqlalchemy.sql.sqltypes import Boolean
from mrt_app.models import Base, Line, Station, Traffic
import pandas as pd
from datetime import datetime
SQLALCHEMY_DATABASE_URI = 'sqlite:///mrt.db'
DATA_FILE_NAME = 'StationMap.csv'
TRAFFIC_FILE_NAME = 'TrafficInfo.csv'
engine = create_engine(SQLALCHEMY_DATABASE_URI)
Base.metadata.bind = create_engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
def load_data(file_name):
data = pd.read_csv(file_name)
return data.values.tolist()
try:
row_list = load_data(DATA_FILE_NAME)
line_set = set()
# Populate lines
for row in row_list:
line_set.add(row[0][0:2])
for line_name in line_set:
line = Line(
name=line_name
)
session.add(line)
session.commit()
lines = session.query(Line).order_by(Line.id.asc())
line_dict = {line.name:line.id for line in lines}
# Populate stations
for row in row_list:
station = Station(
name = str(row[1]),
line_id = line_dict[str(row[0][0:2])],
code_number = int(row[0][2:]),
opening_date = datetime.strptime(row[2], '%d %B %Y').date(),
)
session.add(station)
row_list = load_data(TRAFFIC_FILE_NAME)
# Populate traffic information
for row in row_list:
traffic = Traffic(
line_id = line_dict.get(str(row[0])),
start_hour = int(row[1]),
end_hour = int(row[2]),
is_weekend = bool(row[3]),
is_operating = bool(row[4]),
delay_in_minutes = int(row[5]),
)
session.add(traffic)
session.commit()
except:
print("Unexpected error:", sys.exc_info())
# Rollback the changes on error
session.rollback()
finally:
# Close the connection
session.close()
| true
|
5e84a310a962945b16094b60d409f60e1a2d1d01
|
Python
|
dionwang88/lc1
|
/algo/241_Different_Ways_To_Add_Parentheses/Q241.py
|
UTF-8
| 1,067
| 3.109375
| 3
|
[] |
no_license
|
class Solution(object):
def __init__(self):
self.map = {}
def diffWaysToCompute(self, inputs):
if not inputs:
return []
return self.helper(inputs)
def helper(self, inputs):
res = []
for i in xrange(len(inputs)):
c = inputs[i]
if c == '+' or c == '-' or c == '*':
p1 = inputs[:i]
p2 = inputs[i + 1:]
l1 = self.map.get(p1, self.helper(p1))
l2 = self.map.get(p2, self.helper(p2))
for i1 in l1:
for i2 in l2:
r = 0
if c == '+':
r = i1 + i2
elif c == '-':
r = i1 - i2
elif c == '*':
r = i1 * i2
res.append(r)
if len(res) == 0:
res.append(int(inputs))
self.map[inputs] = res
return res
sol = Solution()
print sol.diffWaysToCompute('2*3-4*5')
| true
|
238fccf0aadd04f683e603fce07d8b07d133c132
|
Python
|
victorxuli/traitement-d-image
|
/tp4.py
|
UTF-8
| 5,497
| 2.53125
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 23 14:10:42 2018
@author: victo
"""
from skimage import util as ut
from PIL import Image
import numpy as np
import scipy.fftpack as sc
import scipy as sp
import skimage.io as skio
from skimage import exposure as ske
from skimage import color
import matplotlib.pyplot as plt
from skimage import filters as fl
from skimage import img_as_float as img_as_float
from skimage.segmentation import clear_border
import skimage.measure as skim
from skimage.morphology import disk
import skimage.restoration as re
import skimage
import skimage.morphology as sm
import cv2
plt.close("all")
imag = skio.imread('D:\image\code.bmp')
plt.figure("image original ")
plt.title("image original ")
plt.imshow(imag,cmap = 'gray')
plt.axis('off')
## mdian
seuil1 = np.median(imag)
rows,cols=imag.shape
for i in range(rows):
for j in range(cols):
if (imag[i,j]>=seuil1):
imag[i,j]=255
else:
imag[i,j]=0
plt.figure("image bilanisation par median")
plt.title("image bilanisation par median ")
plt.imshow(imag,cmap = 'gray')
plt.axis('off')
## mean
imag = skio.imread('D:\image\code.bmp')
seuil2 = np.mean(imag)
rows,cols=imag.shape
for i in range(rows):
for j in range(cols):
if (imag[i,j]>=seuil2):
imag[i,j]=255
else:
imag[i,j]=0
plt.figure("image bilanisation par mean")
plt.title("image bilanisation par mean ")
plt.imshow(imag,cmap = 'gray')
plt.axis('off')
##图像膨胀滤波 图像变亮 粗化区域 亮特征增大 暗特征减小 dilatation
imag = skio.imread('D:\image\code.bmp')
dst1=sm.dilation(imag,sm.square(3)) #用边长为3的正方形滤波器进行膨胀滤波
plt.figure("image dilation 3")
plt.title("image dilation 3")
plt.imshow(dst1,cmap = 'gray')
plt.axis('off')
dst2=sm.dilation(imag,sm.square(11)) #用边长为11的正方形滤波器进行膨胀滤波
plt.figure("image dilation 11")
plt.title("image dilation 11")
plt.imshow(dst2,cmap = 'gray')
plt.axis('off')
##图像腐蚀滤波 图像变暗 细化区域 亮特征减小 暗特征增加 erosion
dst5=sm.erosion(imag,sm.square(5)) #用边长为5的正方形滤波器进行腐蚀滤波
plt.figure("image erosion 5")
plt.title("image erosion 5")
plt.imshow(dst5,cmap = 'gray')
plt.axis('off')
dst6=sm.erosion(imag,sm.square(25)) #用边长为25的正方形滤波器进行腐蚀滤波
plt.figure("image erosion 25")
plt.title("image erosion 25")
plt.imshow(dst6,cmap = 'gray')
plt.axis('off')
##图像开运算 先腐蚀再膨胀 小亮点消失 原图中大片黑色区域中的亮点消失 可以消除小物体或小斑块
dst3=sm.opening(imag,sm.disk(9)) #用边长为9的圆形滤波器进行膨胀滤波
plt.figure("image openning 9")
plt.title("image openning 9")
plt.imshow(dst3,cmap = 'gray')
plt.axis('off')
dst4=sm.opening(imag,sm.disk(3)) #用边长为3的圆形滤波器进行膨胀滤波
plt.figure("image openning 3")
plt.title("image openning 3")
plt.imshow(dst4,cmap = 'gray')
plt.axis('off')
##图像闭运算 先膨胀再腐蚀,可用来填充孔洞。
dst7=sm.closing(imag,sm.disk(9)) #用边长为9的圆形滤波器进行膨胀滤波
plt.figure("image close 9")
plt.title("image close 9")
plt.imshow(dst7,cmap = 'gray')
plt.axis('off')
dst8=sm.closing(imag,sm.disk(3)) #用边长为3的圆形滤波器进行膨胀滤波
plt.figure("image close 3")
plt.title("image close 3")
plt.imshow(dst8,cmap = 'gray')
plt.axis('off')
##图像白帽(white-tophat) 将原图像减去它的开运算值,返回比结构化元素小的白点
dst9=sm.white_tophat(imag,sm.square(25))
plt.figure("image white_tophat 25")
plt.title("image white_tophat 25")
plt.imshow(dst9,cmap = 'gray')
plt.axis('off')
##图像黑帽(black-tophat) 将原图像减去它的闭运算值,返回比结构化元素小的黑点,且将这些黑点反色。 bottom-Hat
dst10=sm.black_tophat(imag,sm.square(23))
dst10 = clear_border(dst10)
plt.figure("image black_tophat 27")
plt.title("image black_tophat 27")
plt.imshow(dst10,cmap = 'gray')
plt.axis('off')
dst10=sm.opening(dst10,sm.disk(6))
#dst10=sm.opening(dst10,sm.square(3))
#dst10=sm.closing(dst10,sm.disk(6))
#dst10=sm.erosion(dst10,sm.square(6))
dst10=sm.dilation(dst10,sm.square(12))
#dst10=sm.erosion(dst10,sm.square(4))
#Imax1 = np.percentile(dst10,60)
#rows,cols=dst10.shape
#for i in range(rows):
# for j in range(cols):
# if (dst10[i,j]<=Imax1):
# dst10[i,j]=0
dst10 = clear_border(dst10)
plt.figure("image bilanisation par mean_final")
plt.title("image bilanisation par mean_final ")
plt.imshow(dst10,cmap = 'gray')
plt.axis('off')
#dst10=sm.opening(dst10,sm.disk(3))
#dst10=sm.dilation(dst10,sm.square(3))
#plt.figure("image black_tophat asd 25")
#plt.title("image black_tophat das 25")
#plt.imshow(dst10,cmap = 'gray')
#plt.axis('off')
#seuil_f = np.mean(dst10)
ass = fl.threshold_otsu(dst10)
dst10 = dst10<=ass
#Imax = np.percentile(dst10,87)
rows,cols=dst10.shape
for i in range(rows):
for j in range(cols):
if (dst10[i,j]==True):
dst10[i,j]=False
else:
dst10[i,j]=True
#dst10 = clear_border(dst10)
dst10=sm.erosion(dst10,sm.square(5))
plt.figure("image bilanisation ")
plt.title("image bilanisation")
plt.imshow(dst10,cmap = 'gray')
plt.axis('off')
| true
|
95941824cf8e93a55c61928b29564db7dfc73673
|
Python
|
yass0016/beagle-project
|
/python_client/index.py
|
UTF-8
| 579
| 2.609375
| 3
|
[] |
no_license
|
import requests
import Adafruit_BBIO.GPIO as GPIO
import time
import string
import random
GPIO.setup("P9_15", GPIO.IN)
old_switch_state = 0
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
while True:
new_switch_state = GPIO.input("P9_15")
if new_switch_state == 1 and old_switch_state == 0:
r = requests.post('http://sayadev.com:2000/list', data={'text':id_generator()})
print(r.status_code, r.reason)
time.sleep(0.1)
old_switch_state = new_switch_state
| true
|
25319e241f385d1a7533e56559a17ca55872c633
|
Python
|
vivekaxl/CodeLab
|
/hacker_rank/6.py
|
UTF-8
| 1,391
| 3.40625
| 3
|
[] |
no_license
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
from __future__ import division
class line_segments:
def __init__(self, start, end):
self. start = start
self.end = end
self.distance = end - start
def __str__(self):
return str(self.start) + " " + str(self.end) + " " + str(self.distance)
def good_bad(line1, line2):
count = 0
if line1.start <= line2.start and line1.end >= line2.end: return False
elif line1.start >= line2.start and line1.end <= line2.end: return False
return True
def temp_remove(lines, line):
return [l for l in lines if not (l.start == line.start and l.end == line.end)]
def subset_selection(lines, new_line):
for line in lines:
if good_bad(line, new_line) is False:
return False, line
return True, None
first_line = raw_input()
lines = []
for _ in xrange(int(first_line)):
second_line = raw_input()
start, end = [int(x) for x in second_line.split()]
lines.append(line_segments(start, end))
subset = []
for line in lines:
cond, odd_line = subset_selection(subset, line)
if cond is True: subset.append(line)
else:
if subset_selection(temp_remove(subset, odd_line), line) and odd_line.distance < line.distance:
subset.remove(odd_line)
subset.append(line)
for l in subset: print l
print len(subset)
| true
|
0929e714f7306dc8dec50e00cbf65a46aae1cc16
|
Python
|
HoeYeon/Algorithm
|
/Python_Algorithm/Baek/1120.py
|
UTF-8
| 257
| 3.140625
| 3
|
[] |
no_license
|
a, b = input().split(' ')
if len(b) > len(a):
a, b = b, a
result = 0
for i in range(0,len(a)-len(b)+1):
count = 0
for j in range(0, len(b)):
if a[i+j] == b[j]:
count += 1
result = max(result,count)
print(len(b) - result)
| true
|
071bf19b7be7c011c8d938bfeb8b1f3a17188cbf
|
Python
|
aleonnet/Vision_Marker_Chaser
|
/Mechanum Wheel Equations.py
|
UTF-8
| 1,132
| 2.890625
| 3
|
[] |
no_license
|
from math import sin, cos, radians
'''
VX is the Speed Multiplier for Wheel X
Vd is mostly a constant - the max speed you want for this run
T0 is Theta Zero the desired direction of travel, hopefully to be variable
Vo is an offset to help change direction, I think?
0.7854 is Pi/4
'''
V1 = 0
V2 = 0
V3 = 0
V4 = 0
Vd = 5
T0 = 90
Vo = 0
RADS = radians(T0)
# robot_ctrl.set_mode(rm_define.robot_mode_chassis_follow)
# chassis_ctrl.set_trans_speed(0)
V1 = Vd * (sin(RADS + 0.7854) + Vo)
V1a = Vd * sin(T0 + 0.7854) + Vo
V2 = Vd * (cos(RADS + 0.7854) - Vo)
V2a = Vd * cos(T0 + 0.7854) - Vo
V3 = Vd * (cos(RADS + 0.7854) + Vo)
V3a = Vd * cos(T0 + 0.7854) + Vo
V4 = Vd * (sin(RADS + 0.7854) - Vo)
V4a = Vd * sin(T0 + 0.7854) - Vo
# V2 = Vd * cos(T0 + 0.7854) - Vo
# V3 = Vd * cos(T0 + 0.7854) + Vo
# V4 = Vd * sin(T0 + 0.7854) - Vo
# print(V1, V1a, V2, V2a, V3, V3a, V4, V4a)
print(V1, V2, V3, V4)
'''
circle_1 = 50 * (1 + sin(radians(n * 10)))
circle_2 = 50 * (1 + cos(radians(n * 10)))
chassis_ctrl.set_wheel_speed(V1, V2, V3, V4)
time.sleep(2)
chassis_ctrl.set_trans_speed(0)
'''
| true
|
6b9a52705db44085a49a72d6ee07a4330723eec3
|
Python
|
changhw01/Maneki
|
/fr/test_ipca.py
|
UTF-8
| 11,619
| 3.28125
| 3
|
[] |
no_license
|
import sys
import os
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.decomposition import PCA
import cv2
import time
import pickle
class CCIPCA(BaseEstimator, TransformerMixin):
"""Candid covariance-free incremental principal component analysis (CCIPCA)
Linear dimensionality reduction using an online incremental PCA algorithm.
CCIPCA computes the principal components incrementally without
estimating the covariance matrix. This algorithm was designed for high
dimensional data and converges quickly.
This implementation only works for dense arrays. However it should scale
well to large data. Time Complexity: per iteration 3 dot products and 2
additions over 'n' where 'n' is the number of features (n_features).
Implementation of:
author={Juyang Weng and Yilu Zhang and Wey-Shiuan Hwang}
journal={Pattern Analysis and Machine Intelligence, IEEE Transactions}
title={Candid covariance-free incremental principal component analysis}
year={2003}
month={aug}
volume={25}
number={8}
pages={1034-1040}
Parameters
----------
n_components : int
Number of components to keep.
Must be set
amnesia : float
A parameter that weights the present more strongly than the
past. amnesia=1 makes the present count the same as anything else.
copy : bool
If False, data passed to fit are overwritten
Attributes
----------
`components_` : array, [n_components, n_features]
Components.
`explained_variance_ratio_` : array, [n_components]
Percentage of variance explained by each of the selected components.
Notes
-----
Calling fit(X) multiple times will update the components_ etc.
Examples
--------
>>> import numpy as np
>>> from sklearn.decomposition import CCIPCA
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> ccipca = CCIPCA(n_components=2)
>>> ccipca.fit(X)
CCIPCA(amnesic=2.0, copy=True, n_components=2)
>>> print(ccipca.explained_variance_ratio_)
[ 0.97074203 0.02925797]
See also
--------
PCA
ProbabilisticPCA
RandomizedPCA
KernelPCA
SparsePCA
IPCA
"""
def __init__(self, n_components=2, amnesic=2.0, copy=True):
self.n_components = n_components
if self.n_components < 2:
raise ValueError("must specifiy n_components for CCIPCA")
self.copy = copy
self.amnesic = amnesic
self.iteration = 0
def fit(self, X, y=None, **params):
"""Fit the model with X.
Parameters
----------
X: array-like, shape (n_samples, n_features)
Training data, where n_samples in the number of samples
and n_features is the number of features.
Returns
-------
self : object
Returns the instance itself.
Notes
-----
Calling multiple times will update the components
"""
n_samples, n_features = X.shape
# init
if self.iteration == 0:
self.mean_ = np.zeros([n_features], np.float)
self.components_ = np.zeros([self.n_components, n_features], np.float)
else:
if n_features != self.components_.shape[1]:
raise ValueError('The dimensionality does not match')
# incrementally fit the model
for i in range(0, X.shape[0]):
self.partial_fit(X[i, :])
# update explained_variance_ratio_
self.explained_variance_ratio_ = np.sqrt(np.sum(self.components_ ** 2, axis=1))
# sort by explained_variance_ratio_
idx = np.argsort(-self.explained_variance_ratio_)
self.explained_variance_ratio_ = self.explained_variance_ratio_[idx]
self.components_ = self.components_[idx, :]
# re-normalize
self.explained_variance_ratio_ = (self.explained_variance_ratio_ / self.explained_variance_ratio_.sum())
for r in range(0, self.components_.shape[0]):
self.components_[r, :] /= np.sqrt(np.dot(self.components_[r, :], self.components_[r, :]))
return self
def partial_fit(self, u):
""" Updates the mean and components to account for a new vector.
Parameters
----------
_u : array [1, n_features]
a single new data sample
"""
n = float(self.iteration)
V = self.components_
# amnesic learning params
if n <= int(self.amnesic):
w1 = float(n + 2 - 1) / float(n + 2)
w2 = float(1) / float(n + 2)
else:
w1 = float(n + 2 - self.amnesic) / float(n + 2)
w2 = float(1 + self.amnesic) / float(n + 2)
# update mean
self.mean_ = w1 * self.mean_ + w2 * u
# mean center u
u = u - self.mean_
# update components
for j in range(0, self.n_components):
if j > n:
# the component has already been init to a zerovec
pass
elif j == n:
# set the component to u
V[j, :] = u
else:
# update the components
V[j, :] = w1 * V[j, :] + w2 * np.dot(u, V[j, :]) * u / np.linalg.norm(V[j, :])
normedV = V[j, :] / np.linalg.norm(V[j, :])
u = u - np.dot(np.dot(u.T, normedV), normedV)
self.iteration += 1
self.components_ = V
return
def transform(self, X):
"""Apply the dimensionality reduction on X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
New data, where n_samples in the number of samples
and n_features is the number of features.
Returns
-------
X_new : array-like, shape (n_samples, n_components)
"""
X_transformed = X - self.mean_
X_transformed = np.dot(X_transformed, self.components_.T)
return X_transformed
def inverse_transform(self, X):
"""Transform data back to its original space, i.e.,
return an input X_original whose transform would be X
Parameters
----------
X : array-like, shape (n_samples, n_components)
New data, where n_samples in the number of samples
and n_components is the number of components.
Returns
-------
X_original array-like, shape (n_samples, n_features)
"""
return np.dot(X, self.components_) + self.mean_
def read_cvimages(path, sz=None):
c = 0
X = []
y, z = [], []
for dirname, dirnames, filenames in os.walk(path):
for subdirname in dirnames:
subject_path = os.path.join(dirname, subdirname)
for filename in os.listdir(subject_path):
try:
if filename[-3:] == "png":
im = cv2.imread(os.path.join(subject_path, filename))
im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
im = cv2.resize(im, (128, 128), interpolation=cv2.INTER_CUBIC)
im = cv2.equalizeHist(im)
X.append(im.flatten("C").copy()) # flatten 2D to 1D
#X.append(im.flatten().astype(np.float32, copy=False))
y.append(c)
except:
print "Unexpected error:", sys.exc_info()[0]
raise
z.append(subdirname)
c = c + 1
return [X, y, z]
def project(W, X, mu=None):
if mu is None:
return np.dot(X, W)
return np.dot(X - mu, W)
def EuclideanDistance(p, q):
p = np.asarray(p).flatten()
q = np.asarray(q).flatten()
return np.sqrt(np.sum(np.power((p - q), 2)))
def CosineDistance(p, q):
p = np.asarray(p).flatten()
q = np.asarray(q).flatten()
return -np.dot(p.T, q) / (np.sqrt(np.dot(p, p.T) * np.dot(q, q.T)))
def predict(Xin, W, mu, projections, y, z, labels):
minDist = 0,
print "min dist: %f" % minDist
minClass = -1
Q = project(W, Xin.reshape(1, -1), mu)
for i in xrange(len(projections)):
dist = CosineDistance(projections[i], Q)
#print y[i], dist
if dist < minDist:
minDist = dist
print "found min dist: %f (%s)" % (minDist, labels[z[y[i]]])
minClass = y[i]
else:
#print "dist: %f (%s)"%(dist, z[y[i]])
pass
return minClass, minDist
def asRowMatrix(X):
if len(X) == 0:
return np.array([])
mat = np.empty((0, X[0].size), dtype=X[0].dtype)
for row in X:
mat = np.vstack((mat, np.asarray(row).reshape(1, -1)))
return mat
if __name__ == "__main__":
# read labels
indata = open("labels.bin", "rb")
labels = pickle.load(indata)
# read images
[X, y, z] = read_cvimages("raw")
X = np.vstack(X)
print "X. total pixel per face", X.shape
print "y. numbers of samples", np.array(y).shape
print "z. numbers of labels", np.array(z).shape
# PCA
k = len(z)
print "principal component no: ", k
pca_m = PCA(n_components=k).fit(X)
W_pca = pca_m.components_.T
pca_projections = [] # build pca projection model
for xi in X:
pca_projections.append(project(W_pca, xi.reshape(1, -1), mu=pca_m.mean_))
# CCIPCA
sample_no = len(y) - 2
ccipca_m = CCIPCA(n_components=k, amnesic=1.0).fit(X[:sample_no, :])
W_ipca = ccipca_m.components_.T
ccipca_projections = [] # build pca projection model
for xi in X[:sample_no, :]:
ccipca_projections.append(project(W_ipca, xi.reshape(1, -1), mu=ccipca_m.mean_))
### testing phase
test_img = cv2.imread(sys.argv[1])
test_img = cv2.cvtColor(test_img, cv2.COLOR_BGR2GRAY)
test_img = cv2.resize(test_img, (128, 128), interpolation=cv2.INTER_CUBIC)
test_img = cv2.equalizeHist(test_img)
test_img = test_img.flatten("C").copy()
print ""
print "pca-based prediction result"
t0 = time.time()
[output_label, score] = predict(
test_img, W_pca, pca_m.mean_, pca_projections, y, z, labels)
print "took", "%f" % ((time.time() - t0) * 1000.), "ms"
if output_label > -1:
print "Label:", labels[z[output_label]], score
else:
print "no suitable label found"
print ""
print "ccipca-based prediction result (%d samples)" % sample_no
t0 = time.time()
[output_label, score] = predict(test_img, W_ipca, ccipca_m.mean_, ccipca_projections, y[:sample_no], z, labels)
print "took", "%f" % ((time.time() - t0) * 1000.), "ms"
if output_label > -1:
print "Label:", labels[z[output_label]], score
else:
print "no suitable label found"
print ""
print "add more samles"
add_no_files = 4
ccipca_m.fit(X[sample_no:(sample_no + add_no_files), :])
W_ipca2 = ccipca_m.components_.T
for xi in X[sample_no:(sample_no + add_no_files), :]:
ccipca_projections.append(
project(W_ipca2, xi.reshape(1, -1), mu=ccipca_m.mean_))
print "ccipca-based prediction result (%d samples)" % (sample_no + add_no_files)
t0 = time.time()
[output_label, score] = predict(test_img, W_ipca2, ccipca_m.mean_, ccipca_projections, y[:(sample_no + add_no_files)], z, labels)
print "took", "%f" % ((time.time() - t0) * 1000.), "ms"
if output_label > -1:
print "Label:", labels[z[output_label]], score
else:
print "no suitable label found"
| true
|
d445475903574783ae7dd99fc99e13da4a9c0521
|
Python
|
mstepan/algorithms-py
|
/excel2sql.py
|
UTF-8
| 324
| 3.703125
| 4
|
[] |
no_license
|
def create_palindrome(value):
for i in range(len(value)-1, 0, -1):
if str[i] != str[i+1]:
break
value
def main():
base_str = "test"
palindrome = create_palindrome(base_str)
print("str: %s, palindrome: %s" % (base_str, palindrome))
if __name__ == "__main__":
main()
| true
|
e13b2e13beacd37dc48e6bc6debdc3cae863e9ad
|
Python
|
Sophie1218/IE221_L22_CNCL
|
/myprogram/option1/point.py
|
UTF-8
| 2,740
| 3.609375
| 4
|
[] |
no_license
|
# import libraries
from math import sqrt
from pygame.draw import circle
from pygame.draw import rect
from myprogram.interface import BLACK, WHITE, COLORS, LIGHT_COLORS
class Point:
"""
A class to represent a two-dimensional data point.
...
Attributes
----------
x : float
coordinates[0]
y : float
coordinates[1]
label : None/int
data is labeled after K - means predict
Methods
-------
distance(point2):
return value of distance between two points
update_coordinates(x, y):
update coordinates of point
update_label(label):
update label
return_coordinates():
return value of coordinates
return_label():
return label
show(screen):
draw point on the screen
draw_boundary(screen):
draw rectangle with color depends on label
this function supports to draw boundaries after running K - means
"""
def __init__(self, x, y):
self.x = x
self.y = y
self.label = None
def distance(self, point2):
"""
Calculate the distance between two points
Parameter:
point2 is another Point object
Returns:
value of distance (float)
"""
return sqrt((self.x - point2.x) ** 2 + (self.y - point2.y) ** 2)
def update_coordinates(self, x, y):
self.x = x
self.y = y
def update_label(self, label):
self.label = label
def return_coordinates(self):
return [self.x, self.y]
def return_label(self):
return self.label
def show(self, screen):
circle(screen, BLACK, (self.x + 50, self.y + 50), 6)
if None == self.label:
circle(screen, WHITE, (self.x + 50, self.y + 50), 5)
else:
circle(screen, COLORS[self.label], (self.x + 50, self.y + 50), 5)
def draw_boundary(self, screen):
if None != self.label:
rect(screen, LIGHT_COLORS[self.label],
(self.return_coordinates()[0] + 50, self.return_coordinates()[1] + 50, 5, 5))
class PointCluster(Point):
"""
A derived class of Point class.
...
Attributes
----------
same as base class
x : float
coordinates[0]
y : float
coordinates[1]
label : None/int
data is labeled after K - means predict
Methods
-------
show(screen):
draw point on the screen with size of circle is bigger
"""
def show(self, screen):
circle(screen, COLORS[self.label], (self.x + 50, self.y + 50), 10)
| true
|
bcfe054c1cbab0fa7b8609386c9e1d6ca2d8f00f
|
Python
|
KKainz/Uebungen
|
/UE1/3 - spaziergang.py
|
UTF-8
| 573
| 3.765625
| 4
|
[] |
no_license
|
def wieweitSpazieren(gewicht: float, letzesMal: float, vertraegtsich: bool) -> float:
if gewicht < 5:
if not vertraegtsich:
return "2 km"
else:
return "4 km"
elif gewicht > 15 or letzesMal > 24:
while vertraegtsich:
return "8 km"
else:
return "5 km"
if __name__ == '__main__':
print(wieweitSpazieren(0.8, 15, False))
print(wieweitSpazieren(10, 2, False))
print(wieweitSpazieren(3.5, 8, True))
print(wieweitSpazieren(20, 26, True))
print(wieweitSpazieren(20, 26, False))
| true
|
7983877722212be109f685c7cd6b8c38b84ec162
|
Python
|
bryantChhun/CardiacUltrasoundSegmentation
|
/imagePreprocess.py
|
UTF-8
| 1,101
| 2.671875
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 05 February, 2018 @ 11:16 PM
@author: Bryant Chhun
email: bchhun@gmail.com
Project: BayLabs
License:
"""
import glob
import src.preprocess.mask_preprocess as mp
import os
def imagePreprocess():
'''
method to generate images, binary-interpolated-aligned masks, and save them as npy arrays:
1) load img.mhd, scale it, then save to directory './images'
2) load mask.vtk
a) preprocess with contour_preprocess
b) align using apply_recentering_mask3d
c) save to directory './masks'
:return:
'''
data_dir = './data'
glob_search = os.path.join(data_dir, "Patient*")
patient_dirs = sorted(glob.glob(glob_search))
if len(patient_dirs) == 0:
raise Exception("No patient directories found in {}".format(data_dir))
for patient_dir in patient_dirs:
# each Patient folder contains approx 20 time frames of 3D images
p = mp.preprocessData(patient_dir, frame="ED")
p = mp.preprocessData(patient_dir, frame="ES")
if __name__ == '__main__':
imagePreprocess()
| true
|
2ef0741d6ad84dda93349f1cc6f6e7c0b490acc6
|
Python
|
bmuftic1/ImageProcessing
|
/Extracting signatures/Boss/boss.py
|
UTF-8
| 2,754
| 3.078125
| 3
|
[] |
no_license
|
#Student: Belma Muftic
#Student number: D17127216
#Assignment number: 1.1
#Assignment objective: Find and crop the signature
#importing needed packages
import numpy as np
import cv2
from matplotlib import pyplot as plt
from matplotlib import image as image
import easygui
#opening the wanted image
f = easygui.fileopenbox()
I = cv2.imread(f)
#convert image to greyscale
G = cv2.cvtColor(I, cv2.COLOR_BGR2GRAY)
#equalize the greyscale image
H=cv2.equalizeHist(G)
#find the binary image of the equalized greyscale
B = cv2.adaptiveThreshold(H, maxValue = 255, adaptiveMethod = cv2.ADAPTIVE_THRESH_GAUSSIAN_C, thresholdType = cv2.THRESH_BINARY, blockSize = 21, C = 35)
#invert the binary image
B = 255-B
#find the region of interest
ROI = cv2.bitwise_and(I,I, mask=B)
#get the height and width of the ROI
h,w,d = ROI.shape
#find the sum values of each row and column
#IDEA: the row/column that has a non-black pixel will have a sum that is greater than zero, thus, it is the first/last pixel to take for the cropping
rowsSum=B.sum(axis=0)
columnsSum=B.sum(axis=1)
#initialize values
upperMostPixel=1
lowerMostPixel=len(rowsSum)-1
leftMostPixel=1
rightMostPixel=len(columnsSum)-1
#find upper-most pixel by searching for the first pixel (from above) that has a row sum that is different from zero
for x in range (1, len(rowsSum)):
if (rowsSum[x]!=0):
upperMostPixel=x-1
break
#find lower-most pixel by searching for the first pixel (from below) that has a row sum that is different from zero
#condition x!=len(rowsSum)-1 is there in case it tries to set the value of the found pixel to a value greater than the size of the image
for x in range (len(rowsSum)-1, 0, -1):
if (rowsSum[x]!=0 & x!=len(rowsSum)-1):
lowerMostPixel=x+1
break
#find left-most pixel by searching for the first pixel (from left) that has a column sum that is different from zero
for x in range (1, len(columnsSum)):
if (columnsSum[x]!=0):
leftMostPixel=x-1
break
#find right-most pixel by searching for the first pixel (from right) that has a column sum that is different from zero
#condition x!=len(columnsSum)-1 is there in case it tries to set the value of the found pixel to a value greater than the size of the image
for x in range (len(columnsSum)-1, 0, -1):
if (columnsSum[x]!=0 & x!=len(columnsSum)-1):
rightMostPixel=x+1
break
#turn the black pixels to white
h,w,d = ROI.shape
for x in range (0, h):
for y in range (0, w):
#test if pixel is black
if (ROI[x,y][0]==0 & ROI[x,y][1]==0 & ROI[x,y][2]==0):
#if it is, turn it into white
ROI[x,y]=(255,255,255)
#crop signature from original image
Ci = ROI[leftMostPixel:rightMostPixel, upperMostPixel:lowerMostPixel]
#show final image
cv2.imshow("signature", Ci)
key = cv2.waitKey(0)
| true
|
15455ebec4bd530467f70ba90e9ff84fa5f5d11c
|
Python
|
xioashitou/algorithm013
|
/Week_03/50.pow-x-n.py
|
UTF-8
| 1,311
| 3.546875
| 4
|
[] |
no_license
|
#
# @lc app=leetcode.cn id=50 lang=python3
#
# [50] Pow(x, n)
#
# https://leetcode-cn.com/problems/powx-n/description/
#
# algorithms
# Medium (36.29%)
# Likes: 466
# Dislikes: 0
# Total Accepted: 116.2K
# Total Submissions: 319.9K
# Testcase Example: '2.00000\n10'
#
# 实现 pow(x, n) ,即计算 x 的 n 次幂函数。
#
# 示例 1:
#
# 输入: 2.00000, 10
# 输出: 1024.00000
#
#
# 示例 2:
#
# 输入: 2.10000, 3
# 输出: 9.26100
#
#
# 示例 3:
#
# 输入: 2.00000, -2
# 输出: 0.25000
# 解释: 2^-2 = 1/2^2 = 1/4 = 0.25
#
# 说明:
#
#
# -100.0 < x < 100.0
# n 是 32 位有符号整数,其数值范围是 [−2^31, 2^31 − 1] 。
#
#
#
# @lc code=start
class Solution:
def myPow(self, x: float, n: int) -> float:
# 1、dumb, recursion depth exceeded in comparison
# if n == 0:
# return 1
# if x == 0:
# return 0
# if n > 0:
# return x * self.myPow(x, n - 1)
# else:
# return 1/(x * self.myPow(x, -n - 1))
# 2.快速幂(exponentiation by squaring)
def helper(n):
if n == 0:
return 1
m = helper(n // 2)
return m * m if not n % 2 else m * m * x
return helper(n) if n >= 0 else 1/helper(-n)
# @lc code=end
| true
|
c03cfa1fdc134be5dcc832e78b8d8a011712b754
|
Python
|
hhy5277/LeetCode-9
|
/008_字符串转换整数/Solution.py
|
UTF-8
| 964
| 3.078125
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/3/24 20:54
# @Author : zenRRan
# @Version : python3.7
# @File : Solution.py
# @Software: PyCharm
class Solution:
def myAtoi(self, str: str) -> int:
s = str.strip()
syb = 1
ptr = 0
res = 0
if len(s) == 0:
return 0
if s[0] == '-':
syb = -1
s = s[1:]
elif s[0] == '+':
s = s[1:]
if len(s) == 0:
return 0
while s[ptr].isnumeric():
res = res * 10 + int(s[ptr])
ptr += 1
if ptr >= len(s):
break
res = res * syb
if res > 2147483647:
res = 2147483647
elif res < -2147483648:
res = -2147483648
return res
data = ['--2', '0-1', '42', ' -42', '4193 with words', 'words and 987', '-91283472332']
for elem in data:
print(Solution().myAtoi(str=elem))
| true
|
39c24221bdc9cce4195fbf6782e4265f5d038b98
|
Python
|
dr-dos-ok/Code_Jam_Webscraper
|
/solutions_python/Problem_8/33.py
|
UTF-8
| 1,916
| 3.046875
| 3
|
[] |
no_license
|
#!/usr/bin/env python
#-*- encoding: utf-8 -*-
#
# FILE.py
# DESC
#
# Copyright (c) 2008 Pierre "delroth" Bourdon <root@delroth.is-a-geek.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import math
def primes(a, b):
for n in xrange(a, b + 1):
ok = True
for d in xrange(2, int(math.sqrt(n)) + 1):
if n % d == 0:
ok = False
break
if ok:
yield n
def primedivisors(m, n):
for p in primes(m, n):
if n % p == 0:
yield p
def nsets(a, b, p):
sets = [set(primedivisors(p, n)) for n in xrange(a, b + 1)]
newsets = []
while True:
for s in sets:
found = None
for i,n in enumerate(newsets):
for e in s:
if e in n:
found = n
break
if not found:
continue
else:
newsets[i] = newsets[i].union(s)
break
if not found:
newsets.append(s)
if sets == newsets:
return len(sets)
else:
sets, newsets = newsets, []
return len(newsets)
for n in xrange(int(raw_input())):
a, b, p = [int(e) for e in raw_input().split()]
print 'Case #%d: %d' % (n + 1, nsets(a, b, p))
| true
|
0a03ea23892dca6618f540e1b8d5eb58a8c37bb5
|
Python
|
joysjohney/Luminar_Python
|
/PythonPrograms/collections/dictionary/emp.py
|
UTF-8
| 427
| 3.03125
| 3
|
[] |
no_license
|
employee={
"eid":1002,
"ename":"person",
"desig":"tester",
"salary":15000
}
#print employee name
print(employee["ename"])
#check for company is there
print("company" in employee)
#add new record comapany name Luminar
employee["cname"]="Luminar"
#update employee salary = current salary + 5000
employee["salary"]+=5000
#print all key:value pairs
for key in employee:
print(key,":",employee[key])
| true
|
8e25c1b7887435715c2fd9633442400fc77b78f7
|
Python
|
JamesWo/Algorithms
|
/topcoder/division2-2/PiecewiseLinearFunctionDiv2.l2.SRM586.py
|
UTF-8
| 3,265
| 3.8125
| 4
|
[] |
no_license
|
"""
# [PiecewiseLinearFunctionDiv2](http://community.topcoder.com/tc?module=ProblemDetail&rd=15698&pm=12698)
*Single Round Match 586 Round 1 - Division II, Level Two*
## Statement
F is a function that is defined on all real numbers from the closed interval [1,N].
You are given a int[] *Y* with N elements.
For each i (1 <= i <= N) we have F(i) = *Y*[i-1].
Additionally, you know that F is piecewise linear: for each i, on the interval [i,i+1] F is a linear function.
The function F is uniquely determined by this information.
For example, if F(4)=1 and F(5)=6 then we must have F(4.7)=4.5.
As another example, this is the plot of the function F for *Y* = {1, 4, -1, 2}.

You are also given a int[] *query*.
For each i, compute the number of solutions to the equation F(x) = *query*[i].
Note that sometimes this number of solutions can be infinite.
Return a int[] of the same length as *query*.
For each i, element i of the return value should be -1 if the equation F(x) = *query*[i] has an infinite number of solutions.
Otherwise, element i of the return value should be the actual number of solutions this equation has.
## Definitions
- *Class*: `PiecewiseLinearFunctionDiv2`
- *Method*: `countSolutions`
- *Parameters*: `int[], int[]`
- *Returns*: `int[]`
- *Method signature*: `int[] countSolutions(int[] Y, int[] query)`
## Constraints
- *Y* will contain between 2 and 50 elements, inclusive.
- Each element of *Y* will be between -1,000,000,000 and 1,000,000,000, inclusive.
- *query* will contain between 1 and 50 elements, inclusive.
- Each element of *query* will be between -1,000,000,000 and 1,000,000,000, inclusive.
## Examples
### Example 1
#### Input
<c>[1, 4, -1, 2],<br />[-2, -1, 0, 1]</c>
#### Output
<c>[0, 1, 2, 3 ]</c>
#### Reason
This is the example from the problem statement. The detailed information about the queries is:
There is no such x that F(x) = -2 is satisfied.
F(x) = -1 is only true for x = 3.
F(x) = 0 has two roots: 2.8 and 10/3.
F(x) = 1 has three roots: 1, 2.6 and 11/3.
### Example 2
#### Input
<c>[0, 0],<br />[-1, 0, 1]</c>
#### Output
<c>[0, -1, 0 ]</c>
#### Reason
This function's plot is a horizontal segment between points (1, 0) and (2, 0). F(x) = 0 is satisfied for any x between 1 and 2 and thus the number of solutions is infinite. For any other value on the right-hand side, it has no solutions.
### Example 3
#### Input
<c>[2, 4, 8, 0, 3, -6, 10],<br />[0, 1, 2, 3, 4, 0, 65536]</c>
#### Output
<c>[3, 4, 5, 4, 3, 3, 0 ]</c>
### Example 4
#### Input
<c>[-178080289, -771314989, -237251715, -949949900, -437883156, -835236871, -316363230, -929746634, -671700962],<br />[-673197622, -437883156, -251072978, 221380900, -771314989, -949949900, -910604034, -671700962, -929746634, -316363230]</c>
#### Output
<c>[8, 6, 3, 0, 7, 1, 4, 8, 3, 4 ]</c>
"""
def solve( Y, i ):
count = 0
for j in range( len(Y)-1 ):
if Y[j] == i == Y[j+1]:
return -1
if (Y[j] <= i <= Y[j+1]) or (Y[j] >= i >= Y[j+1]):
count += 1
for elem in Y[1:-1]:
if elem == i:
count -= 1
return count
def countSolutions(Y, query):
result = []
for i in query:
s = solve( Y, i )
result.append( s )
return result
| true
|
3d54e2f77a0ff57a7ddd5661a50ddcef81b0b357
|
Python
|
AAO2014/promprog15_1
|
/lesson4/classwork_3.py
|
UTF-8
| 2,320
| 3.46875
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function # для совместимости с python 2.x.x
# Дата некоторого дня определяется тремя натуральными числами y (год), m (месяц) и d (день).
# По заданным d, m и y определите дату предыдщуего дня.
#
# Заданный год может быть високосным. Год считается високосным, если его номер кратен 4,
# однако из кратных 100 високосными являются лишь кратные 400,
# например 1700, 1800 и 1900 — невисокосные года, 2000 — високосный.
from classwork_2 import is_leap_year
# lenOfMonths -> months_lengths
months_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
class NonValidDataExeption(Exception):
pass
def yesterday(year, month, day):
try:
if not ((0 <= int(year) <= 9999) and (0 < int(month) < 13) and (0 < int(day) < 32)):
print("Data isn't correct") # мы договорились что пишем на 3м пайтоне => print()
# здесь по логике тоже надо скидывать NonValidDataExeption
return None
except:
raise NonValidDataExeption("Data isn't integer number")
# здесь по логике тоже надо скидывать NonValidDataExeption
return None
if day > months_lengths[month - 1]:
# в сообщении Exception нужно максимально детализировать ошибку
# - что было передано, какие значения допустимы
# NonValidDataExeption("Month {} isn't correct! Valid values is {}-{}".format(...))
raise NonValidDataExeption("Month isn't correct")
if is_leap_year(year):
months_lengths[1] = 29
else:
months_lengths[1] = 28
if (month == 1) and (day == 1):
y = year - 1
m = 12
d = 31
else:
y = year
if day == 1:
m = month - 1
d = months_lengths[m - 1]
else:
m = month
d = day - 1
return y, m, d
| true
|
25d3e6a41dd86a216cf489e141c89b6d86b6a65d
|
Python
|
qmnguyenw/python_py4e
|
/geeksforgeeks/python/basic/18_9.py
|
UTF-8
| 2,872
| 4.28125
| 4
|
[] |
no_license
|
Binary Search (bisect) in Python
Binary Search is a technique used to search element in a sorted list. In this
article, we will looking at library functions to do Binary Search.
**Finding first occurrence of an element.**
> bisect.bisect_left(a, x, lo=0, hi=len(a)) : Returns leftmost insertion point
> of x in a sorted list. Last two parameters are optional, they are used to
> search in sublist.
__
__
__
__
__
__
__
# Python code to demonstrate working
# of binary search in library
from bisect import bisect_left
def BinarySearch(a, x):
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
else:
return -1
a = [1, 2, 4, 4, 8]
x = int(4)
res = BinarySearch(a, x)
if res == -1:
print(x, "is absent")
else:
print("First occurrence of", x, "is present at", res)
---
__
__
**Output:**
First occurrence of 4 is present at 2
**Finding greatest value smaller than x.**
__
__
__
__
__
__
__
# Python code to demonstrate working
# of binary search in library
from bisect import bisect_left
def BinarySearch(a, x):
i = bisect_left(a, x)
if i:
return (i-1)
else:
return -1
# Driver code
a = [1, 2, 4, 4, 8]
x = int(7)
res = BinarySearch(a, x)
if res == -1:
print("No value smaller than ", x)
else:
print("Largest value smaller than ", x, " is at index ", res)
---
__
__
**Output:**
Largest value smaller than 7 is at index 3
**Finding rightmost occurrence**
> bisect.bisect_right(a, x, lo=0, hi=len(a)) Returns rightmost insertion point
> of x in a sorted list a. Last two parameters are optional, they are used to
> search in sublist.
__
__
__
__
__
__
__
# Python code to demonstrate working
# of binary search in library
from bisect import bisect_right
def BinarySearch(a, x):
i = bisect_right(a, x)
if i != len(a)+1 and a[i-1] == x:
return (i-1)
else:
return -1
a = [1, 2, 4, 4]
x = int(4)
res = BinarySearch(a, x)
if res == -1:
print(x, "is absent")
else:
print("Last occurrence of", x, "is present at", res)
---
__
__
**Output:**
Last occurrence of 4 is present at 3
Please refer Binary Search for writing your own Binary Search code.
**Reference :**
https://docs.python.org/3/library/bisect.html
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
| true
|
cab4316f300282c8c115f9361023210158c7ff9a
|
Python
|
thekrisharmon/Open-Street-Map-SQL-Project
|
/countyAudit.py
|
UTF-8
| 1,549
| 3.15625
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 23 12:09:05 2018
My goal for this python file is to size up the counties listed in my data sample. I'm curious how many counties are covered and
if any data clean-up is needed at this point. I utilized my code from the StreetNameAudit.py file and modified it to look for
the county information.
@author: kharmon
"""
import xml.etree.cElementTree as ET
from collections import defaultdict
import re
osmFile = open("kcsample.osm", "r")
# changed the 'S' to a 'D' to pull in the entire string from the tiger:county attribute
county_type_re = re.compile(r'\D+\.?$', re.IGNORECASE)
countyTypes = defaultdict(int)
def auditCountyType(countyTypes, countyName):
counties = county_type_re.search(countyName)
if counties:
countyType = counties.group()
countyTypes[countyType] += 1
def printSortedDict(d):
keys = d.keys()
keys = sorted(keys, key=lambda s: s.lower())
for k in keys:
v = d[k]
print "%s: %d" % (k, v)
#Looking for tags that have the attribute of 'tiger:county' so I can see the counties listed in my data sample
def is_county_name(element):
return (element.tag == "tag") and (element.attrib['k'] == "tiger:county") #changed the focus to county instead of street name
def audit():
for row, element in ET.iterparse(osmFile):
if is_county_name(element):
auditCountyType(countyTypes, element.attrib['v'])
printSortedDict(countyTypes)
if __name__ == '__main__':
audit()
| true
|
40b00cba2d98af6009812c653eff3abad8fb682e
|
Python
|
srirambandi/AI_TAK
|
/AI_TAK.py
|
UTF-8
| 22,694
| 3.328125
| 3
|
[
"MIT"
] |
permissive
|
# * AI TAK Bot
# * Sri Ram Bandi (srirambandi.654@gmail.com)
import sys
import pdb
import time
import random
from copy import deepcopy
from collections import deque
from math import exp
class Game:
class Player:
def __init__(self, flats, capstones):
self.flats = flats
self.capstones = capstones
def __init__(self, n):
self.n = n
self.total_squares = n * n
self.board = [ [] for i in xrange(self.total_squares) ]
self.turn = 0
if n == 5:
self.max_flats = 21
self.max_capstones = 1
elif n == 6:
self.max_flats = 30
self.max_capstones = 1
elif n == 7:
self.max_flats = 40
self.max_capstones = 1
self.max_movable = n
self.max_down = 1
self.max_up = n
self.max_left = 'a'
self.max_right = chr(ord('a') + n - 1)
self.moves = 0
self.players = []
self.players.append(Game.Player(self.max_flats, self.max_capstones))
self.players.append(Game.Player(self.max_flats, self.max_capstones))
self.all_squares = [ self.square_to_string(i) for i in xrange(self.total_squares) ]
def square_to_num(self, square_string):
""" Return -1 if square_string is invalid
"""
if len(square_string) != 2:
return -1
if not square_string[0].isalpha() or not square_string[0].islower() or not square_string[1].isdigit():
return -1
row = ord(square_string[0]) - 96
col = int(square_string[1])
if row < 1 or row > self.n or col < 1 or col > self.n:
return -1
return self.n * (col - 1) + (row - 1)
def square_to_string(self, square):
"""Convert square number to string
"""
if square < 0 or square >= self.total_squares:
return ''
row = square % self.n
col = square / self.n
return chr(row + 97) + str(col + 1)
def unexecute_move(self, move_string):
"""Unexecute placement move
"""
if self.moves == 1 or self.moves == 0:
current_piece = 1 - self.turn
else:
current_piece = self.turn
square = self.square_to_num(move_string[1:])
self.board[square].pop()
if move_string[0] == 'C':
self.players[current_piece].capstones += 1
else:
self.players[current_piece].flats += 1
def execute_move(self, move_string):
"""Execute move
"""
if self.turn == 0:
self.moves += 1
if self.moves != 1:
current_piece = self.turn
else:
current_piece = 1 - self.turn
if move_string[0].isalpha():
square = self.square_to_num(move_string[1:])
if move_string[0] == 'F' or move_string[0] == 'S':
self.board[square].append((current_piece, move_string[0]))
self.players[current_piece].flats -= 1
elif move_string[0] == 'C':
self.board[square].append((current_piece, move_string[0]))
self.players[current_piece].capstones -= 1
elif move_string[0].isdigit():
count = int(move_string[0])
square = self.square_to_num(move_string[1:3])
direction = move_string[3]
if direction == '+':
change = self.n
elif direction == '-':
change = -self.n
elif direction == '>':
change = 1
elif direction == '<':
change = -1
prev_square = square
for i in xrange(4, len(move_string)):
next_count = int(move_string[i])
next_square = prev_square + change
if len(self.board[next_square]) > 0 and self.board[next_square][-1][1] == 'S':
self.board[next_square][-1] = (self.board[next_square][-1][0], 'F')
if next_count - count == 0:
self.board[next_square] += self.board[square][-count:]
else:
self.board[next_square] += self.board[square][-count:-count + next_count]
prev_square = next_square
count -= next_count
count = int(move_string[0])
self.board[square] = self.board[square][:-count]
self.turn = 1 - self.turn
def partition(self, n):
"""Generates all permutations of all partitions
of n
"""
part_list = []
part_list.append([n])
for x in xrange(1, n):
for y in self.partition(n - x):
part_list.append([x] + y)
return part_list
def check_valid(self, square, direction, partition):
"""For given movement (partition), check if stack on
square can be moved in direction. Assumes active player
is topmost color
"""
if direction == '+':
change = self.n
elif direction == '-':
change = -self.n
elif direction == '>':
change = 1
elif direction == '<':
change = -1
for i in xrange(len(partition)):
next_square = square + change * (i + 1)
if len(self.board[next_square]) > 0 and self.board[next_square][-1][1] == 'C':
return False
if len(self.board[next_square]) > 0 and self.board[next_square][-1][1] == 'S' and i != len(partition) - 1:
return False
if i == len(partition) - 1 and len(self.board[next_square]) > 0 and self.board[next_square][-1][1] == 'S' and partition[i] > 1:
return False
if i == len(partition) - 1 and len(self.board[next_square]) > 0 and self.board[next_square][-1][1] == 'S' and self.board[square][-1][1] != 'C':
return False
return True
def generate_stack_moves(self, square):
"""Generate stack moves from square
Assumes active player is topmost color
"""
all_moves = []
r = square % self.n
c = square / self.n
size = len(self.board[square])
dirs = ['+',
'-',
'<',
'>']
up = self.n - 1 - c
down = c
right = self.n - 1 - r
left = r
rem_squares = [up,
down,
left,
right]
for num in xrange(min(size, self.n)):
part_list = self.partition(num + 1)
for di in range(4):
part_dir = [ part for part in part_list if len(part) <= rem_squares[di] ]
for part in part_dir:
if self.check_valid(square, dirs[di], part):
part_string = ''.join([ str(i) for i in part ])
all_moves.append(str(sum(part)) + self.all_squares[square] + dirs[di] + part_string)
return all_moves
def generate_all_moves(self, player):
"""Generate all possible moves for player
Returns a list of move strings
"""
all_moves = []
for i in xrange(len(self.board)):
if len(self.board[i]) == 0:
if self.players[player].flats > 0:
all_moves.append('F' + self.all_squares[i])
if self.moves != player and self.players[player].flats > 0:
all_moves.append('S' + self.all_squares[i])
if self.moves != player and self.players[player].capstones > 0:
all_moves.append('C' + self.all_squares[i])
for i in xrange(len(self.board)):
if len(self.board[i]) > 0 and self.board[i][-1][0] == player and self.moves != player:
all_moves += self.generate_stack_moves(i)
return all_moves
class Agent:
def __init__(self):
data = sys.stdin.readline().strip().split()
self.player = int(data[0]) - 1
self.n = int(data[1])
self.time_left = int(data[2])
self.game = Game(self.n)
self.max_depth = self.n
self.play()
def getNeighbors(self, square,length=1):
total_squares = self.n * self.n
if square < 0 or square >= total_squares:
return []
elif square == 0:
arr = []
for i in xrange(length):
arr.append(square + 1+i)
arr.append(square + (1+i)*self.n)
return arr
elif square == self.n - 1:
arr = []
for i in xrange(length):
arr.append(square - 1-i)
arr.append(square + (1+i)*self.n)
return arr
elif square == total_squares - self.n:
arr = []
for i in xrange(length):
arr.append(square + 1+i)
arr.append(square - (1+i)*self.n)
return arr
elif square == total_squares - 1:
arr = []
for i in xrange(length):
arr.append(square - 1-i)
arr.append(square - (1+i)*self.n)
return arr
elif square < self.n:
arr = []
for i in xrange(length):
if square - 1-i >= 0:
arr.append(square - 1-i)
if square + 1+i < self.n:
arr.append(square + 1+i)
arr.append(square + (1+i)*self.n)
return arr
elif square % self.n == 0:
arr = []
for i in xrange(length):
arr.append(square + 1+i)
if square + (1+i)*self.n < total_squares:
arr.append(square + (1+i)*self.n)
if square - (1+i)*self.n >=0 :
arr.append(square - (1+i)*self.n)
return arr
elif (square + 1) % self.n == 0:
arr = []
for i in xrange(length):
arr.append(square - 1-i)
if square + (1+i)*self.n < total_squares:
arr.append(square + (1+i)*self.n)
if square - (1+i)*self.n >= self.n-1 :
arr.append(square - (1+i)*self.n)
# arr = [elm if 0<= elm <self.n for elm in arr]
return arr
elif square >= total_squares - self.n:
arr = []
for i in xrange(length):
if square - 1-i >= total_squares-self.n:
arr.append(square - 1-i)
if square + 1+i < total_squares:
arr.append(square + 1+i)
arr.append(square - (1+i)*self.n)
# arr = [elm if 0<= elm <self.n for elm in arr]
return arr
else:
arr = []
for i in xrange(length):
if square + 1+i < ((square/self.n)+1)*self.n:
arr.append(square + 1+i)
if square - 1-i >= ((square/self.n))*self.n:
arr.append(square - 1-i)
if square + (1+i)*self.n <= total_squares-self.n +(square%self.n):
arr.append(square + (1+i)*self.n)
if square - (1+i)*self.n >= (square%self.n):
arr.append(square - (1+i)*self.n)
return arr
def bfs(self, source, direction, player):
if direction == '<' and source % self.n == 0 or direction == '-' and source // self.n == 0 or direction == '>' and (source + 1) % self.n == 0 or direction == '+' and source // self.n == self.n - 1:
return 0
fringe = deque()
fringe.append((source, 0))
value = 0
reached_end = False
while not len(fringe) == 0 and value < self.n + 1:
node, val = fringe.popleft()
value = val
if direction == '<' and node % self.n == 0 or direction == '-' and node // self.n == 0 or direction == '>' and (node + 1) % self.n == 0 or direction == '+' and node // self.n == self.n - 1:
reached_end = True
break
nbrs = self.getNeighbors(node)
for nbr in nbrs:
if len(self.game.board[nbr]) == 0 or self.game.board[nbr][-1][0] == player and self.game.board[nbr][-1][1] != 'S':
if direction == '<':
if nbr % self.n <= node % self.n:
fringe.append((nbr, value + 1))
elif direction == '-':
if nbr // self.n <= node // self.n:
fringe.append((nbr, value + 1))
elif direction == '>':
if nbr % self.n >= node % self.n:
fringe.append((nbr, value + 1))
elif direction == '+':
if nbr // self.n >= node // self.n:
fringe.append((nbr, value + 1))
if reached_end:
return value
else:
return self.n * self.n
def dfs(self, source, direction, player, visited):
fringe = []
fringe.append(source)
dfs_val = self.n * self.n
while not len(fringe) == 0:
node = fringe.pop()
visited.add(node)
nbrs = self.getNeighbors(node)
has_children = False
for nbr in nbrs:
if len(self.game.board[nbr]) > 0 and nbr not in visited and self.game.board[nbr][-1][0] == player and self.game.board[nbr][-1][1] != 'S':
fringe.append(nbr)
has_children = True
if not has_children:
if direction == '>':
dfs_val = min(self.bfs(node, '>', player), dfs_val)
elif direction == '+':
dfs_val = min(self.bfs(node, '+', player), dfs_val)
if dfs_val == self.n * self.n:
return -1
else:
if dfs_val != 0:
pass
return dfs_val
def score_combination(self, bfs, dfs):
if dfs == -1:
return 0
else:
return self.n * self.n * exp(-0.5 * (bfs + dfs))
def road_score(self, player):
value = 0
visited = [set(), set()]
for r in xrange(0, self.n / 2):
for c in xrange(0, self.n):
idx = r * self.n + c
if len(self.game.board[idx]) > 0 and self.game.board[idx][-1][0] == player and self.game.board[idx][-1][1] != 'S' and idx not in visited[1]:
value = max(value, self.score_combination(self.bfs(idx, '-', player), self.dfs(idx, '+', player, visited[1])))
idx = c * self.n + r
if len(self.game.board[idx]) > 0 and self.game.board[idx][-1][0] == player and self.game.board[idx][-1][1] != 'S' and idx not in visited[0]:
value = max(value, self.score_combination(self.bfs(idx, '<', player), self.dfs(idx, '>', player, visited[0])))
return value
def evaluation_function(self):
if self.n == 5:
bonus = 1000;
cutoff_bonus = 20000;
fc = 100;
cs = 85;
w = 30;
c = 15;
ccap = 15;
s = 18;
inf = 10;
rd = 10;
wallpenalty = 10;
attack = 1;
fw = 15.5;
ccw = 6.0;
sw = 3.0;
iw = 6.0;
rw = 4.0;
cw = 4.0;
ww = 1.0;
cow = 1.3;
else:
bonus = 2500;
cutoff_bonus = 45000;
fc = 100;
cs = 85;
w = 40;
c = 15;
ccap = 20;
s = 18;
rd = 1;
inf = 10;
wallpenalty = 10;
attack = 2;
fw = 15.5;
ccw = 6.0;
sw = 3.0;
iw = 6.0;
rw = 4.0;
cw = 4.0;
ww = 1;
cow = 1.3;
infl = [[0,0,0,0,0,0,0],
[0,1,0,1,1,0,0],
[0,0,0,0,1,0,0],
[0,1,1,1,1,1,0],
[0,-1,0,0,0,0,-1],
[0,-1,0,0,-1,0,0],
[0,-1,-1,-1,-1,-1,0]]
flats_owned = [0, 0]
color = [0,0]
stack_score = 0;
wall_dis = 0;
total_influence =0;
composition = 0;
total_squares = len(self.game.board)
influence_table = [0 for i in xrange(total_squares)]
for idx in xrange(len(self.game.board)):
################# Feature 1 #################
if len(self.game.board[idx]) > 0:
if self.game.board[idx][-1][1] == 'F':
flats_owned[self.game.board[idx][-1][0]] += fc
if self.game.board[idx][-1][1] == 'C':
flats_owned[self.game.board[idx][-1][0]] += cs
if self.game.board[idx][-1][1] == 'S':
flats_owned[self.game.board[idx][-1][0]] += w
##############################################
################# Feature 2 #################
if len(self.game.board[idx]) > 1: #if it is stack
for h in xrange(len(self.game.board[idx])-1):
color[self.game.board[idx][h][0]] += s
stack_score = color[self.player] - color[1 - self.player]
piece = self.game.board[idx][-1][1];
owner = self.game.board[idx][-1][0];
if owner == self.player and stack_score >0:
if piece == 'F':
stack_score += 4*s;
if piece == 'C':
stack_score += 7*s;
else:
stack_score += 5*s;
elif owner == self.player and stack_score <=0:
if piece == 'F':
stack_score += -2*s;
if piece == 'C':
stack_score += -5*s;
else:
stack_score += -3*s;
elif owner != self.player and stack_score >0:
if piece == 'F':
stack_score += 2*s;
if piece == 'C':
stack_score += 5*s;
else:
stack_score += 3*s;
else:
if piece == 'F':
stack_score += -4*s;
if piece == 'C':
stack_score += -7*s;
else:
stack_score += -5*s;
if owner == self.player and color[self.player]>0:
ttt = min(self.n-1,color[self.player]+1)
nbrs = nbrs = self.getNeighbors(idx,ttt)
for nbr in nbrs:
if len(self.game.board[nbr]) == 0 :
influence_table[nbr] += 1;
elif self.game.board[nbr][-1] == [1-self.player,'F']:
influence_table[nbr] += 1;
elif self.game.board[nbr][-1][1] != 'F':
influence_table[nbr] -= 1;
elif piece == 'C' and self.game.board[idx][-2][0] == self.player and self.game.board[nbr][-1] == [1-self.player,'S']:
influence_table[nbr] += 1;
if abs(idx-nbr)==1 :
if len(self.game.board[nbr]) > 0 :
if self.game.board[nbr][-1][0] == self.player and self.game.board[nbr][-1][1] != 'F':
wall_dis -= color[self.player]*wallpenalty;
if self.game.board[nbr][-1][0] == 1-self.player and self.game.board[nbr][-1][1] != 'F':
wall_dis -= color[1-self.player]*wallpenalty
##############################################
##################Feature 3 ##################
if len(self.game.board[idx]) == 1:
nbrs = nbrs = self.getNeighbors(idx)
mapping = {'F':1,'S':2,'C':3}
piece = self.game.board[idx][-1][1];
owner = self.game.board[idx][-1][0];
for nbr in nbrs:
if len(self.game.board[nbr]) > 0:
nbr_piece = self.game.board[nbr][-1][1]
nbr_owner = self.game.board[nbr][-1][0]
xx = mapping[piece] if owner==self.player else 3+mapping[piece]
yy = mapping[nbr_piece] if nbr_owner==self.player else 3+mapping[nbr_piece]
influence_table[nbr] += infl[xx][yy]
row = 0;
for i in range(0,total_squares,self.n):
row_num = 0;
for j in range(i,i+self.n):
if len(self.game.board[j]) > 0:
if self.game.board[j][-1][0]== self.player and self.game.board[j][-1][1] != 'S':
row_num +=1;
elif self.game.board[j][-1][0]== 1-self.player and self.game.board[j][-1][1] != 'S':
row_num -= attack;
composition += row_num**3;
total_influence += influence_table[j]*10;
row += influence_table[j]*10
col = 0;
for i in range(self.n):
col_num = 0;
for _j in range(self.n):
j = i+ (_j*self.n);
if len(self.game.board[j]) > 0:
if self.game.board[j][-1][0]== self.player and self.game.board[j][-1][1] != 'S':
col_num +=1;
elif self.game.board[j][-1][0]== 1-self.player and self.game.board[j][-1][1] != 'S':
col_num -= attack;
composition += col_num**3;
# total_influence += influence_table[j]*10;
col += influence_table[j]*10
flat_comp = flats_owned[self.player] - flats_owned[1 - self.player]
road_comp = self.road_score(1 - self.player) + self.road_score(self.player)
return rd*road_comp + fw*flat_comp + sw*stack_score + iw*total_influence + rw* row + cw*col + ww*wall_dis + cow*composition;
def play(self):
a = random.randint(0,self.n-1)
b = random.randint(1,self.n)
if self.player == 0:
move = 'F' + chr(97+a)+str(b)
self.game.execute_move(move)
sys.stdout.write(move + '\n');
sys.stdout.flush()
opponent_move = sys.stdin.readline().strip()
move = self.min_max(opponent_move)
sys.stdout.write(move + '\n');
sys.stdout.flush()
else:
opponent_move = sys.stdin.readline().strip()
self.game.execute_move(opponent_move)
move = 'F' + chr(97+a)+str(b)
while(move == opponent_move):
a = random.randint(0,self.n-1)
b = random.randint(1,self.n)
move = 'F' + chr(97+a)+str(b)
self.game.execute_move(move)
sys.stdout.write(move + '\n');
sys.stdout.flush()
while True:
opponent_move = sys.stdin.readline().strip()
move = self.min_max(opponent_move)
sys.stdout.write(move + '\n')
sys.stdout.flush()
def min_max(self,move):
if move != '':
self.game.execute_move(move)
(my_move,val) = self.max_node(float('-inf'), float('inf'), 2,move)
self.game.execute_move(my_move)
return my_move
def unexecute_move(self, board, players, moves, turn):
self.game.board = board
self.game.players = players
self.game.moves = moves
self.game.turn = turn
def max_node(self, alpha, beta, depth,opponent_move):
if depth == 0:
return (opponent_move,self.evaluation_function())
val = float('-inf')
# store_val = False
# if depth == 0:
# store_val = True
action = opponent_move;
for move in self.game.generate_all_moves(self.player):
old_game = deepcopy(self.game)
self.game.execute_move(move)
node_val = self.min_node(alpha, beta, depth - 1)
self.game = old_game
val = max(node_val, val)
if val == node_val:
action = move
alpha = max(alpha, val)
if beta <= alpha:
break
# if store_val:
# sys.stderr.write('Value: ' + str(val) + '\n')
# return (action,val)
# else:
# return (action,val)
return (action,val)
def min_node(self, alpha, beta, depth):
if depth == 0:
return self.evaluation_function()
val = float('inf')
# store_val = False
# if depth == 0:
# store_val = True
action = ''
for move in self.game.generate_all_moves(1 - self.player):
old_game = deepcopy(self.game)
self.game.execute_move(move)
(some_move,node_val) = self.max_node(alpha, beta, depth - 1,move)
self.game = old_game
val = min(node_val, val)
if val == node_val:
action = move
beta = min(beta, val)
if beta <= alpha:
break
# if store_val:
# sys.stderr.write('Value: ' + str(val) + '\n')
# return action
# else:
# return val
return val
random_player = Agent()
# +++ okay decompyling AgentBFS.pyc
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
# 2016.10.20 22:47:40 IST
| true
|
aec8b0e5b7a9dceaead55424e965d40c2cd6d426
|
Python
|
hoatd/Ds-Algos-
|
/GeeksforGeeks/Random-problems/all_character.py
|
UTF-8
| 907
| 3.390625
| 3
|
[] |
no_license
|
from collections import defaultdict
def solve(s, lst):
cnt1 = defaultdict()
for i in s:
p = ord(i)
if i.islower():
p -= 97
else:
p -= 65
if p in cnt1:
cnt1[p] += 1
else:
cnt1[p] = 1
ans = []
for l in lst:
k = l
cnt2 = defaultdict()
for c in k:
p = ord(c)
if c.islower():
p -= 97
else:
p -= 65
if p in cnt2:
cnt2[p] += 1
else:
cnt2[p] = 1
flag = True
for key in cnt1.keys():
if key not in cnt2.keys():
flag = False
break
if flag == True:
ans.append(k)
return ans
s = "sun"
lst = ["geeksforgeeks","unsorted","sunday","just","sss"]
ans = solve(s, lst)
print(ans)
| true
|
402ca0908c4a1dfcb56bfc482621957778e92051
|
Python
|
lurak/Coursework
|
/SimpleSite/map_cities.py
|
UTF-8
| 315
| 2.59375
| 3
|
[] |
no_license
|
import folium
def get_map(place, path):
m = folium.Map(
location=(place.latitude, place.longitude),
zoom_start=12,
)
folium.Marker(
location=(place.latitude, place.longitude),
popup=place.name,
icon=folium.Icon(icon='cloud')
).add_to(m)
m.save(path)
| true
|
33db14f4d5a9a39301ea0d465a51fc1d13fc6ad4
|
Python
|
Rajeshdraksharapu/Leetcode-Prblems
|
/BackTrackingProblems/islandBackTracking.py
|
UTF-8
| 1,208
| 3.328125
| 3
|
[] |
no_license
|
island = [
[0, 1, 0, 0, 0],
[0, 1, 0, 1, 1],
[1, 1, 1, 0, 1],
[0, 1, 0, 0, 0]
]
grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
count=0
def findingIsland(row,column,island,visited):
if row<0 or column<0 or row>len(island)-1 or column>len(island[0])-1:
return
elif island[row][column]=="1" and visited[row][column]!=True:
visited[row][column]=True
findingIsland(row-1,column,island,visited)
findingIsland(row+1,column,island,visited)
findingIsland(row,column+1,island,visited)
findingIsland(row,column-1,island,visited)
return 1
def islandToFind(row,column,island):
visited = [[False for i in range(len(grid[0]))] for j in range(len(island))]
count=0
for i in range(len(island)):
for j in range(len(island[0])):
if grid[i][j]=="1" and visited[i][j]!=True:
row=i
column=j
count+=(findingIsland(row,column,grid,visited))
return count
row=0
column=0
print(islandToFind(row,column,grid))
#print(findingIsland(row,column))
| true
|
1a85de4bc3847c1550870232e52fcf6b95c79570
|
Python
|
SanchRepo/Intro-Python
|
/Ece 203/BugClass.py
|
UTF-8
| 913
| 4.1875
| 4
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 25 13:51:09 2017
@author: szh24
"""
class Bug:
def __init__(self,initialPosition):
self.initialPosition = float(initialPosition)
self.pot=1
def move(self):
self.initialPosition+=self.pot
def turn(self):
self.pot=self.pot*-1
def position(self):
return self.initialPosition
def direction(self):
if self.pot==1:
print("Bug is facing right")
elif self.pot==-1:
print("Bug is facing left")
ant = Bug(10) # starts at position 10 facing right
ant.move() # Position is 11
ant.turn() # now facing left
ant.move() # Position is 10
ant.move() # Position is 9
print ant.position() # prints ‘9’ to the screen
print ant.direction() # prints ‘left’ to the screen
| true
|
0e6cc6d63ea07d43ec77db58b9006332a64ec0ed
|
Python
|
brenolemes/exercicios-python
|
/exercicios/CursoemVídeo/ex085.py
|
UTF-8
| 662
| 4.625
| 5
|
[
"MIT"
] |
permissive
|
'''
Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os
em uma lista única que mantenha separados os valores pares e ímpares.
No final, mostre os valores pares e ímpares em ordem crescente.
'''
num = [[], []]
for c in range(1, 8):
valor = int(input(f'Digite o {c}º valor: '))
if valor % 2 == 0:
num[0].insert(0, valor) # Poderia dar um append
elif valor % 2 != 0:
num[1].insert(0, valor) # Poderia dar um append
num[0].sort() # Ordem crescente
num[1].sort() # Ordem crescente
print(f'Os valores pares digitados foram: {num[0]}')
print(f'Os valores ímpares digitados foram: {num[1]}')
| true
|
e9e9293fd5506eb789a82f6a6d6dd8c5457ac743
|
Python
|
aishwarya202005/Decision-Tree-Classifier
|
/q-1-2.py
|
UTF-8
| 7,704
| 2.953125
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# coding: utf-8
# In[70]:
import pprint
import sys
import numpy as np
import pandas as pd
eps = np.finfo(float).eps
from numpy import log2 as log
# In[71]:
a=pd.read_csv('train_data.csv')
a.describe()
df = pd.DataFrame(a)#,columns=['Work_accident','promotion_last_5years','sales','salary','left'])
# In[72]:
# train, validate = np.split(df, [int(.8*len(df))]) #for sequential data
train, validate = np.split(df.sample(frac=1), [int(.8*len(df))]) # for random
# df= train
# In[73]:
def find_entropy(df):
Class = 'left' #To make the code generic, changing target variable class name
entropy = 0
values = df['left'].unique()
for value in values:
fraction = df['left'].value_counts()[value]/float(len(df[Class]))
entropy += -fraction*np.log2(fraction+eps)
return entropy
def find_entropy_attribute(df,attribute):
Class = 'left' #To make the code generic, changing target variable class name
target_variables = df[Class].unique() #This gives all 'Yes' and 'No'
variables = df[attribute].unique() #This gives different features in that attribute (like 'Hot','Cold' in Temperature)
if len(target_variables) == 1 or len(variables) == 1:
return 0;
entropy2 = 0
for variable in variables:
entropy = 0
for target_variable in target_variables:
num = len(df[attribute][df[attribute]==variable][df[Class] ==target_variable])
den = len(df[attribute][df[attribute]==variable])
fraction = num/(den+eps)
entropy += -fraction*np.log2(fraction+eps)
fraction2 = den/float(len(df))
entropy2 += fraction2*entropy
return entropy2
def min_num_entropy(df,attribute):
# temp_d=df
# x=temp_d.sort_values(by=attribute)
# print "min_continuous entropy"
# variables = x[attribute].unique()
variables = df[attribute].unique() #This gives different features in that attribute (like 'Hot','Cold' in Temperature)
entropy2 = 0
entropy1 = 0
min_entr=sys.maxint
min_split=sys.maxint
entropy_fin=0
for variable in variables:
entropy = 0
df1 = df[df[attribute]<=variable]
df2 = df[df[attribute]>variable]
entropy1 = find_entropy(df1)
entropy2 = find_entropy(df2)
fraction2 = len(df2)/float(len(df))
fraction1 = len(df1)/float(len(df))
entropy_fin = fraction1*entropy1+ fraction2*entropy2
if min_entr>entropy_fin:
min_entr=entropy_fin
min_split=variable
return min_entr,min_split
# print min_num_entropy(df,'satisfaction_level')
# In[74]:
numerical_attributes=[]
for i in df.keys()[0:5]:
numerical_attributes.append(i)
# print(i)
# print numerical_attributes
# In[75]:
def max_IG(dataf):
IG = []
i=0
split=-1
max_=0
max_in=None
#categ
for key in dataf.keys()[5:-1]:
if key!= 'left':
temp_en = find_entropy_attribute(dataf,key)
# print temp_en
ig1= find_entropy(dataf)-temp_en
# print("IG 1: ",ig1,key)
if ig1>max_:
max_=ig1
max_in=key
IG.append(ig1)
#continuous
for key in dataf.keys()[0:5]:
temp_en = min_num_entropy(dataf,key)[0]
ig1=find_entropy(dataf)-temp_en
# print("IG 2conti: ",ig1,key)
if ig1>max_:
max_=ig1
max_in=key
split=min_num_entropy(dataf,key)[1]
IG.append(ig1)
# print 'ig=',IG
return max_in,max_,split,IG
# max_IG(df)
# In[76]:
class DTree:
def __init__(self,pos=0,neg=0, child={},val = None,spl_pt=-1):
self.val = val
self.child = child
self.pos=pos
self.neg=neg
self.spl_pt=spl_pt
def buildTree(df1,label_node,tree=None):
max_ig_node,gn,split,Info_gain_array = max_IG(df1)
# print max_ig_node,gn,split
# dd=find_entropy_attribute(df1,label_node)
# print 'MAX IG= ',gn,'split=',split
# pprint.pprint(max_ig_node)
c_pos=0
c_len=0
if gn <= 0.000001 or len(df1.columns)==1:
# print 'IG-array',Info_gain_array
########switched 0 and 1
c_pos=len(df1[df1[label_node]==1])
c_len=len(df1[df1[label_node]==0])
if c_pos>c_len:
max_ig_node="YES"
else:
max_ig_node="NO"
child={}
# print "leaf nnode hai"
leaf_n=DTree(c_pos,c_len,child,max_ig_node)
return leaf_n
print 'node is--- ',max_ig_node
c_pos=len(df1[max_ig_node][df1[label_node]==1])
c_len=len(df1[max_ig_node][df1[label_node]==0])
child={}
if split==-1:
newnode=DTree(c_pos,c_len,child,max_ig_node,-1)
attr = df1[max_ig_node].unique()
for labels in attr:
nd1=df1[df1[max_ig_node]==labels]
nd1=nd1.drop(columns=[max_ig_node])
newnode.spl_pt=-1
newnode.child[labels] = buildTree(nd1,label_node) #Calling the function recursively
else:
newnode=DTree(c_pos,c_len,child,max_ig_node,split)
label1="<="+str(split)
label2=">"+str(split)
# print "numericl ka bno"
nd1=df1[df1[max_ig_node]<=split]
nd2=df1[df1[max_ig_node]>split]
# print len(nd1)
# print len(nd2)
if len(nd1)==0 or len(nd2)==0:
c_pos=len(df1[df1[label_node]==1])
c_len=len(df1[df1[label_node]==0])
if c_pos>c_len:
max_ig_node="YES"
else:
max_ig_node="NO"
child={}
# print "leaf nnode hai"
leaf_n=DTree(c_pos,c_len,child,max_ig_node)
return leaf_n
newnode.child[label1] = buildTree(nd1,label_node) #Calling the function recursively
newnode.child[label2] = buildTree(nd2,label_node) #Calling the function recursively
return newnode
# In[77]:
def traverse(tree):
print(tree.val) #,'split=',tree.spl_pt)
if tree.val==1:
return
for k,vals in tree.child.items():
pprint.pprint(k)
traverse(vals)
tree = buildTree(train,'left')
print "tree:-"
traverse(tree)
# pprint.pprint(tree.val)
# In[79]:
def predict(row,tree):
# global tp,tn,fp,fn
if tree.val=="YES" or tree.val=="NO":
return tree.val
attr=row[tree.val]
if tree.val in numerical_attributes:
if attr<=tree.spl_pt:
x="<="+str(tree.spl_pt)
return predict(row,tree.child[x])
else:
x=">"+str(tree.spl_pt)
return predict(row,tree.child[x])
else:
if attr in tree.child:
return predict(row,tree.child[attr])
return "NO"
def calc_measures(df,tree):
tp=0
tn=0
fp=0
fn=0
i=0
while i< len(df):
pred_val=predict(df.iloc[i],tree)
if df.iloc[i]['left']==1:
if pred_val=="YES":
tp=tp+1
else:
fn=fn+1 #### fn here
elif df.iloc[i]['left']==0:
if pred_val=="NO":
tn=tn+1
else:
fp=fp+1 #### fp here
i=i+1
# print"i="
return tp,fp,tn,fn
tp,fp,tn,fn=calc_measures(validate,tree)
print "tp=",tp
print "tn=",tn
print "false positive=",fp
print "False negative=",fn
total=tp+tn+fp+fn
prec=tp/float(tp+fp)
rec=tp/float(tp+fn)
den=float((1/rec)+(1/prec))
f1=2/float(den)
print "Precision: ", prec
print "Recall: ",rec
print "F1: ",f1
print "accuracy: ",(tp+tn)/float(total)
# In[ ]:
| true
|
9e0df50a0df2a3cf99f86c88e8273d31196c6d69
|
Python
|
NuclearPython/OptimizeCassette_PC
|
/GnoweeNSGAPython3/MultiObjectiveTest.py
|
UTF-8
| 1,350
| 2.625
| 3
|
[] |
no_license
|
# Gnowee Modules
import Gnowee_multi
from ObjectiveFunction_Multi import ObjectiveFunction_multi
from Constraints import Constraint
from GnoweeHeuristics_multi import GnoweeHeuristics_multi
import numpy as np
from OptiPlot import plot_vars
import matplotlib.pyplot as plt
# User Function Module
from TestFunction import testfittness
#second Function
#objective function array
testarray = np.zeros(6)
print(testfittness(testarray))
sz = 100
all_ints = ["i" for i in range(sz)]
LB = np.zeros(sz)
UppB = np.ones(sz)
# Select optimization problem type and associated parameters
gh = GnoweeHeuristics_multi(objective=ObjectiveFunction_multi(testfittness),
lowerBounds=LB, upperBounds=UppB,
varType=all_ints, optimum=0)
print(gh)
# Run optimization
(timeline) = Gnowee_multi.main_multi(gh)
length = len(timeline)
fitnesses = np.zeros(length)
generations = np.zeros(length)
for i in range(0,length):
t = timeline[i]
fitnesses[i] = t.fitness
generations[i] = t.generation
plt.plot(generations, fitnesses, '-r', lw=2) # plot the data as a line
plt.xlabel('Generation', fontsize=14) # label x axis
plt.ylabel('Fittness', fontsize=14) # label y axis
plt.gca().grid() # add grid lines
plt.show() # display the plot
print('\nThe result:\n', timeline[-1])
| true
|
3f8c14201772e3603d8e0d3c8a72df53eb53b70b
|
Python
|
lmorinishi/leetcode-practice
|
/solutions/lc_014_longestCommonPrefix.py
|
UTF-8
| 479
| 2.90625
| 3
|
[] |
no_license
|
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) == 0 or '' in strs:
return ''
if len(strs) == 1:
return strs[0]
result = ''
min_len = min(len(k) for k in strs)
i = 0
while i < min_len:
if len(set([k[i] for k in strs])) == 1:
result += strs[0][i]
i += 1
else:
return result
return result
| true
|
e5de1f9a9e702c3c3f7bdecfce9586963692f7cf
|
Python
|
Ehtycs/scicomp-project
|
/test_pod.py
|
UTF-8
| 4,203
| 3.234375
| 3
|
[] |
no_license
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 4 20:47:53 2018
@author: marjamaa
This is an invented toy example on how this POD works.
Circuit has an input current and output voltage, four resistor values
out of seven are adjustable. So the system formed from the circuit by
nodal analysis is 1-in 1-out and parametrized by four
resistor values (conductances).
Circuit has six nodes -> five DoFs.
After POD analysis we could reduce this to less than five by discarding the
least important 'modes'.
See circuit.png for the topology of the circuit.
"""
import numpy as np
import matplotlib.pyplot as plt
from pod import make_reducer
G3,G4,G5 = 1,1,1
def Zmu(params):
""" Parametrized part of the nodal analysis admittance matrix """
G1, G2, G6, G7 = params
Z = np.zeros(shape=(5,5))
Z[0,0] = G1+G3
Z[1,1] = G1+G2+G4
Z[2,2] = G2+G5
Z[3,3] = G5+G7
Z[4,4] = G4+G6+G7
Z[0,1] = -G1
Z[1,2] = -G2
Z[1,0] = -G1
Z[2,1] = -G2
Z[3,4] = -G7
Z[4,3] = -G7
return Z
# Constant part of nodal analysis matrix
Zconst = np.zeros(shape=(5,5))
Zconst[1,4] = -G4
Zconst[2,3] = -G5
Zconst[3,2] = -G5
Zconst[4,1] = -G4
Zconst[0,0] = G3
Zconst[1,1] = G4
Zconst[2,2] = G5
Zconst[3,3] = G5
Zconst[4,4] = G4
# Input current vector
J1 = np.zeros(shape=(5,1))
J1[0] = 1
# Limits for the input current and the conductances of the resistors
parameter_limits = [(1,10)] + 4*[(0.1, 10.0)]
def full_model(params):
""" Calculate a solution for given parameter vector """
i1 = params[0]
conds = params[1:]
Z = Zconst + Zmu(conds)
J = J1*i1
u = np.linalg.solve(Z,J)
return u
def rom_builder(psi):
""" Build a reduced order model. A function which
given a parameter vector returns a reduced order solution """
rZconst = psi.T@Zconst@psi
rJ1 = psi.T@J1
def reduced_model(params):
i1 = params[0]
conds = params[1:]
rZ = rZconst + psi.T@Zmu(conds)@psi
rJ = rJ1*i1
return np.linalg.solve(rZ, rJ)
return reduced_model
def error_estimator(psi, reduced_model, params):
""" Estimates the error of the reduced model by evaluating
norm(Z * psi * u_red - J) which should be zero if reduced order
model is perfectly accurate. """
i1 = params[0]
conds = params[1:]
rsol = reduced_model(params)
Z = Zconst + Zmu(conds)
J = J1*i1
return np.linalg.norm(Z@psi@rsol - J)
# Make a reducer instance using The Awesome Constructor Function(TM)
red = make_reducer(full_model=full_model,
parameter_limits=parameter_limits,
error_estimator=error_estimator,
# The "cutoff" dimension, ie. take this many
# modes into the reduced order model.
poddim=3,
# or
# The error limit for the cutoff,
# podtol = 1e-9,
rom_builder=rom_builder,
# print stuff
verbose=True,
# If exceptions are thrown from argument functions,
# rethrow them
rethrow_exceptions=True)
# Do an initial reduced order model using 2 samples
# this is very little
res = red.reduce(4)
# Improve the model iteratively
# by finding the maximum of the error function
for i in range(0,100):
red.improve(res)
if res.error < 1e-9:
break
else:
print("The error didn't converge to required tolerance.")
print("This happens if poddim is too small or podtol "
"is too big or too small amount of samples")
print("Remainder error is {}".format(res.error))
# Plot the singular values of the system
plt.plot(np.arange(1,res.ss.shape[0]+1), res.ss)
plt.title('Magnitude of singular values')
plt.xlabel("Index of $\sigma$")
plt.ylabel("Magnitude of $\sigma$")
plt.xticks(np.arange(1,res.ss.shape[0]+1))
plt.show()
print("Original dimension {}, reduced dimension {}".format(res.psi.shape[0],
res.psi.shape[1]))
| true
|
e9a5d8b49025077cebef3d8f276e25869ab9227c
|
Python
|
TommyCpp/nx-poprank
|
/test/GraphTestCase.py
|
UTF-8
| 428
| 2.75
| 3
|
[] |
no_license
|
from unittest import TestCase
from heterogeneousgraph import HeGraph
import networkx as nx
class GraphTestCase(TestCase):
def _setup(self, sub_graph_count=1, node_per_graph=3, probability_of_edge_creation=0.8):
G = HeGraph()
for i in range(sub_graph_count):
sub_graph = nx.fast_gnp_random_graph(node_per_graph, probability_of_edge_creation)
G.add_graph(sub_graph)
return G
| true
|
f23f9fee270af5242b41e81cdef42554c38358a7
|
Python
|
skdy33/Video-Copyright-Detector
|
/Plagierism.py
|
UTF-8
| 8,744
| 2.765625
| 3
|
[] |
no_license
|
# Input data의 파일형식에 따라 FPS가 안맞을수도 있다.
# 안 맞는 경우 파일형식의(예.avi) Header의 문제인데, 실험 때는 그냥 되는 파일형식으로 convert해서 사용하자.
class plagierism:
"""
원본 영상을 받는다.
input :
self = str of the video
out = str of the name of the output video, including
"""
codec = {'mp4':'H264','avi':'XVID'}
def WriterChecker(self):
if (self.cap.isOpened()!=1):
print("Refresh opener")
return 0
if (self.out.isOpened()!=1):
print("Refresh writer")
return 0
return 1
def __init__(self,video,out):
self._fileName = video
self._outFile = out
self.cap = cv2.VideoCapture(video)
print(self.cap.isOpened())
#Checking
if (cap.isOpened()==False):
print ("Problem reading a video file")
return
#the property of the video
self.width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
self.height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
self.FPS = cap.get(cv2.CAP_PROP_FPS)
# For later issue. If we wanna keep our output w/ a same extension
out_file, out_extension = out.split('.')
dec = self.codec.get(out_extension,1)
if dec == 1:
return
print (dec)
try:
fourcc = cv2.VideoWriter_fourcc(*'XVID') # 일단 output은 무조건 .avi
except:
print ("I said write the name of the output including extension")
return
# Output은 무조건 .avi
self.out = cv2.VideoWriter(out_file+'_m.avi',fourcc,self.FPS,(640,480))
if (self.out.isOpened()==False):
print ("There might be a existing file that has your target name.")
return
"""
writer class
name : str of the name of the file that'll be the modified one.
"""
def writer(self,name):
return
"""
영상의 절단 후 재배포
"""
def Cutting(self):
while(self.cap.isOpened()):
ret, frame = self.cap.read()
if ret == True:
frame = frame[int(height/8):int(height/8*7),int(width/8):int(width/8*7)]
frame = cv2.resize(frame,(640,480))
self.out.write(frame)
cv2.imshow('frame',frame)
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
"""
영상 아래에 임의의 영상 혹은 사진 끼워넣기
data : String of background에 깔릴 영상(or 사진) location
"""
def Padding(self,data):
back = cv2.VideoCapture(data)
#checking
if (back.isOpened()!=True):
print ("Prob opening background video or image")
return
BackWidth = int(back.get(cv2.CAP_PROP_FRAME_WIDTH))
BackHeight = int(back.get(cv2.CAP_PROP_FRAME_HEIGHT))
BackFPS = back.get(cv2.CAP_PROP_FPS)
while(self.cap.isOpened()):
ret, frame = self.cap.read()
if ret == True:
# 여기서 back frame을 계속 읽어줘야해. 나중에 regarding complexity 우리가 picture 의 경우는 fixation 할 수 있지만
# 지금은 일단 편의를 위해 닫히면 계속 새로 open 하도록 할게
if back.isOpened() == True:
BackRet, BackFrame = back.read()
if BackRet == 1:
pass
else :
back.release()
back = cv2.VideoCapture(data)
BackRet, BackFrame = back.read()
else :
back.release()
back = cv2.VideoCapture(data)
BackRet, BackFrame = back.read()
# padding은 일단 1/2 사이즈로 줄여서 넣어볼게.
frame = cv2.resize(frame,(int(BackWidth/2),int(BackHeight/2)))
BackFrame[int(BackHeight/4):int(BackHeight/4*3),int(BackWidth/4):int(BackWidth/4*3)] = frame
BackFrame = cv2.resize(BackFrame,(640,480))
self.out.write(BackFrame)
cv2.imshow('frame',BackFrame)
else:
cap.release()
out.release()
back.release()
break
cap.release()
out.release()
back.release()
cv2.destroyAllWindows()
"""
영상 일부분만 배포
s = starting point. 몇 초 후 부터 녹화할것인가. 초 단위
d = duration. 몇 분을 녹화할 것인가. 초 단위
"""
def Slicing(self,s,d):
# sec to frame
start = int(s * self.FPS)
fin = int(d * self.FPS)
#Checking before writing
if (WriterChecker()==0):
return
#Frame counter
cnt = 0
#Write
while(self.cap.isOpened()):
if (cnt < s):
continue
if (cnt > d):
break
ret, frame = self.cap.read()
if ret == True:
cnt +=1
frame = cv2.resize(frame,(640,480))
self.out.write(frame)
cv2.imshow('frame',frame)
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
return
"""
영상 화질 낮추기
일단 (640,480) 으로 나오는 걸로 한다.
이것보다 더 극단적으로 낮추고 싶으면 writer 정의할 때 작게해야 하는데,
이건 writer function 정의하고 그거 이용하면 쉬울거다.
그러면 writer refresh func 에는 해상도 default var 로 주면 될 것 같다.
"""
def Dequalify(self):
#Checking before writing
if (WriterChecker()==0):
return
#write
while(self.cap.isOpened()):
ret, frame = self.cap.read()
if ret == True:
frame = cv2.resize(frame,(640,480))
self.out.write(frame)
cv2.imshow('frame',frame)
else:
break
return
"""
좌우 대칭
flip
"""
def Flip(self):
#Checking before writing
if (WriterChecker()==0):
return
#write
while(self.cap.isOpened()):
ret, frame = self.cap.read()
if ret == True:
frame = cv2.resize(frame,(640,480))
frame = cv2.flip(frame)
self.out.write(frame)
cv2.imshow('frame',frame)
else:
break
return
"""
속도 빠르게 만들기.
x : times faster(slower).
이것도 writer 재정의야.
일단은 hard coding,
refreshing writing func 만들면 그걸로 대신 사용.
"""
def SpeedUp(self,x):
# self.out 재정의
if (self.out.isOpened()):
self.out.release()
out_file = self._outFile.split('.')[0]
#FPS 재정의
FPS = self.FPS * x
fourcc = cv2.VideoWriter_fourcc(*'XVID') # 일단 output은 무조건 .avi
self.out = cv2.VideoWriter(out_file+'_m.avi',fourcc,FPS,(640,480))
#check
if (WriterChecker()==0):
return 0
#write
while(self.cap.isOpened()):
ret, frame = self.cap.read()
if ret == True:
frame = cv2.resize(frame,(640,480))
frame = cv2.flip(frame)
self.out.write(frame)
cv2.imshow('frame',frame)
else:
break
"""
음성 바꾸기
opencv로 음성 안들어옴.
"""
def AudioChg(self):
return
"""
조도 변화
a = param
b = bias
"""
def Jodo(self,a=2,b=3):
#Checking before writing
if (WriterChecker()==0):
return
#write
while(self.cap.isOpened()):
ret, frame = self.cap.read()
if ret == True:
frame = cv2.resize(frame,(640,480))
frame = frame*a + b
self.out.write(frame)
cv2.imshow('frame',frame)
else:
break
return
| true
|
a1147e0cf00953fb903935bff9fdd58eb8f007f6
|
Python
|
mami-project/lurk
|
/proxySTAR_V3/certbot/venv/lib/python2.7/site-packages/pylint/test/functional/method_hidden.py
|
UTF-8
| 323
| 2.984375
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
# pylint: disable=too-few-public-methods,print-statement
"""check method hidding ancestor attribute
"""
class Abcd(object):
"""dummy"""
def __init__(self):
self.abcd = 1
class Cdef(Abcd):
"""dummy"""
def abcd(self): # [method-hidden]
"""test
"""
print(self)
| true
|
5fab108b90adbf2f0c58b579e0826ee23a620390
|
Python
|
Mary-Li-shuangyue/wadlab
|
/tango_with_django_project/populate_rango.py
|
UTF-8
| 2,469
| 3.140625
| 3
|
[] |
no_license
|
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
"tango_with_django_project.settings")
import django
django.setup()
from rango.models import Category, Page
def populate():
'''create lists of dictionaries containing the pages we want to add into each category
then, create a dictionary of dictionaries for the categories so we can iterate through
each data structure, and add the data to the models'''
python_pages = [
{"title": "Official Python ~Tutorial",
"url": "http://docs.python.org/2/tutorial/", "views":12},
{"title": "How to think like a computer scientist",
"url": "http://www.greenteapress.com/thinkpython/", "views":34},
{"title": "Learn Python in 10 minutes",
"url": "http://www.korokithakis.net/tutorials/python/", "views":23},
]
django_pages = [
{"title": "Offical Django Tutorial",
"url": "https://docs.djangoproject.com/en/1.9/intro/tutorial01/", "views":76},
{"title": "Django Rocks",
"url": "http://www.djangorocks.com/", "views":32},
{"title": "How to Tango with Django",
"url": "http://www.tangowithdjango.com/", "views":18},
]
other_pages = [
{"title": "Bottle",
"url": "http://bottlepy.org/docs/dev/", "views":33},
{"title": "Flask",
"url": "http://flask.pocoo.org", "views":11},
]
cats = {"Python":{"pages": python_pages, "views":128, "likes":64},
"Django":{"pages": django_pages, "views":64, "likes":32},
"Other Frameworks":{"pages": other_pages, "views":32, "likes":16}}
for cat, cat_data in cats.items():
c = add_cat(cat, cat_data["views"], cat_data["likes"])
for p in cat_data["pages"]:
add_page(c,p["title"],p["url"],p["views"])
#print out the categories added
for c in Category.objects.all():
for p in Page.objects.filter(category = c):
print("- {0} - {1}".format(str(c),str(p)))
def add_page(cat, title, url, views ):
p = Page.objects.get_or_create(category = cat, title=title)[0]
p.url = url
p.views = views
p.save()
return p
def add_cat(name, views=0, likes=0):
c = Category.objects.get_or_create(name=name )[0]#[0] returns the object reference only
c.views = views
c.likes = likes
c.save()
return c
if __name__ == '__main__':
print("Starting Rango population script...")
populate()
| true
|
3c5dec1420458ba250d287744053707fee27ac20
|
Python
|
riki900/mySketches
|
/examples/coding-creative-examples/examples/cc_07_loops/cc_07_loops.pyde
|
UTF-8
| 142
| 3.140625
| 3
|
[] |
no_license
|
size(600, 600)
background(50)
stroke(200)
for i in range(5):
line(random(width), random(height),
random(width), random(height))
| true
|
e2e9b20224e73478c08b728a0ec826a499cdd863
|
Python
|
Yakobo-UG/Python-by-example-challenges
|
/challenge 17.py
|
UTF-8
| 545
| 4.65625
| 5
|
[] |
no_license
|
#Ask the user’s age. If they are 18 or over, display the message “You can vote”, if they are aged 17, display the message “You can learn to drive”, if they are 16, display the message “You can buy a lottery ticket”, if they are under 16, display the message “You can go Trick-or-Treating”.
Age = int(input("Enter your age: "))
if Age >= 18:
print("You can vote")
elif Age == 17:
print("You can learn to drive")
elif Age == 16 :
print("You can buy a lottery ticket")
else:
print("You can go Trick-or-Treating")
| true
|
0be8c103b5bdbac9de542f4415890b105c21dd47
|
Python
|
Fleskimiso/MemoryPuzzle
|
/Puzzle.py
|
UTF-8
| 1,589
| 3.28125
| 3
|
[] |
no_license
|
import pygame
from Shapes import *
class Puzzle:
def __init__(self, shape, color, x_pos, y_pos):
self.width = 50
self.height = 50
self.shape = shape
self.color = color
self.x_position = x_pos
self.y_position = y_pos
self.surface = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
self.surface.fill((0, 0, 0, 0))
self.surface_orignal = self.surface.copy()
self.draw_blank()
def draw_figure(self):
self.surface = self.surface_orignal.copy()
pygame.draw.rect(self.surface, (0, 0, 0), (0, 0, self.width, self.height), 1)
if self.shape == Shapes.circle:
pygame.draw.circle(self.surface, self.color.value, self.surface.get_rect().center, int(self.width / 2), 10)
elif self.shape == Shapes.square:
pygame.draw.polygon(self.surface, self.color.value, [
(10, 10), (self.width - 10, 10), (self.width - 10, self.height - 10), (10, self.height - 10)
], 5)
elif self.shape == Shapes.cross:
pygame.draw.line(self.surface, self.color.value, (0, 0), (self.width, self.height))
pygame.draw.line(self.surface, self.color.value, (self.width, 0), (0, self.height))
elif self.shape == Shapes.elipse:
pygame.draw.ellipse(self.surface, self.color.value, (0, 10, self.width, self.height - 2 * 10), 15)
def draw_blank(self):
self.surface = self.surface_orignal.copy()
pygame.draw.rect(self.surface, (0, 0, 0, 255), ((0, 0), (self.width, self.height)), 1)
| true
|
253fe3c4cebf63d7a8fbc16af75c303db241ca12
|
Python
|
g-ampo/Drone_RL
|
/Source/RL_Agent_old.py
|
UTF-8
| 3,804
| 2.6875
| 3
|
[] |
no_license
|
import numpy as np
from Source.RF_Env import RFBeamEnv, Generate_BeamDir, Gen_RandomBeams
class RL_Agent:
def __init__(self, env, alpha, gamma):
self.env = env # Environment
self.alpha = alpha # learning rate
self.gamma = gamma #discount factor
self.Q = {} # Q_table
def sample_action(self, obs, eps):
assert self.Check_Obs(obs), "%r (%s) obs is invalid" % (obs, type(obs))
str_obs = ConvObs_ToString(obs)
if (np.random.random() < eps) or (not self.Q):
#print("came here")
action = self.env.GenAction_Sample()
#print("new action: {0}".format(action))
str_action = ConvAct_String(action)
#print("new str action: {0}".format(str_action))
self.Q[str_obs][str_action] = 0.0
else:
action = max(self.Q[str_obs], key= self.Q[str_obs].get)
#print("exist str action: {0}".format(action))
eval_action = ConStr_Action(action)
#print("exist action: {0}".format(eval_action))
action = eval_action
return action
def Check_Obs(self, obs):
str_obs = ConvObs_ToString(obs)
if str_obs in self.Q:
pass
else:
self.Q[str_obs] ={}
a = self.env.GenAction_Sample()
#print("check obs action: {0}".format(a))
str_action = ConvAct_String(a)
self.Q[str_obs][str_action] = 0.0
#print("[RL_A] obs:{0}, a: {1}".format(str_obs, self.Q[str_obs]))
return True
def Check_Action(self, obs, action):
str_obs = ConvObs_ToString(obs)
str_action = ConvAct_String(action)
if str_action in self.Q[str_obs]:
#print("ac: {0}".format(str(action)))
#print(self.Q)
pass
else:
self.Q[str_obs][str_action] = 0.0
return True
def Action_Vals(self, obs):
action_vals = []
str_obs = ConvObs_ToString(obs)
for a in self.Q[str_obs]:
action_vals.append(self.Q[str_obs][a])
#print("[RL_A] action_vals: {0}".format(action_vals))
return action_vals
def Update_Q(self, prev_obs, action, obs, rwd):
assert self.Check_Obs(prev_obs), "%r (%s) prev_obs is invalid" % (prev_obs, type(prev_obs))
assert self.Check_Obs(obs), "%r (%s) obs is invalid" % (obs, type(obs))
assert self.Check_Action(prev_obs, action), "%r (%s) action is invalid" % (action, type(action))
#self.Check_Obs(prev_obs) and self.Check_Obs(obs) and self.Check_Action(prev_obs, action):
str_prev_obs = ConvObs_ToString(prev_obs)
str_action = ConvAct_String(action)
self.Q[str_prev_obs][str_action] += self.alpha*(rwd + self.gamma*np.max(self.Action_Vals(obs))- self.Q[str_prev_obs][str_action])
return True
def Best_Action(self, obs):
str_obs = ConvObs_ToString(obs)
assert self.Check_Obs(obs), "%r (%s) obs is invalid" % (obs, type(obs))
best_a = max(self.Q[str_obs], key=self.Q[str_obs].get)
best_val = self.Q[str_obs][best_a]
return ConStr_Action(best_a), best_val
def ConvObs_ToString(obs):
str_obs = " "
obs_list = [str(x) for x in obs]
str_obs = str_obs.join(obs_list)
#print(str_obs)
return str_obs
def ConvAct_String(action):
str_l = ','.join(str(' '.join(str(x) for x in v)) for v in action)
return str_l
def ConStr_Action(str_action):
item_list = str_action.split(',')
action = []
for item in item_list[:-1]:
subitem_list = item.split(' ')
l = []
#print(subitem_list)
for x in subitem_list:
l.append(complex(x))
action.append(l)
action.append([int(item_list[-1])])
return action
| true
|
170e211eadbf90e21eb4a08f5524a1e888a89409
|
Python
|
anish888/python-project2
|
/validate_angrams.py
|
UTF-8
| 411
| 4
| 4
|
[] |
no_license
|
#function for valaditing angrams
def anagram(word1, word2):
word1 = word1.lower()
word2 = word2.lower()
#sorting word1 and word2
#if user word is validate angram it return true otherwise false..
return sorted(word1) == sorted(word2)
#taking user input for valadating angrams
word1=input("enter word1")
word2=input('enter word2')
#calling function
anagram=anagram(word1,word2)
print(anagram)
| true
|
030e589d4b0bbcc12ea5383f6ca624190f0acb35
|
Python
|
eric0890/ITC110
|
/HW3.py
|
UTF-8
| 776
| 4.46875
| 4
|
[] |
no_license
|
#pizzaconverter.py
#this file converts the price and size of a pizza into cost per square inch
#note: I tested using 10" diameter and $8 which equals 78.5 square inches divided by 800 cents = 9.82 (rounded)
from math import pi
def main():
print("This program computes the cost per square inch of pizza. \n")
#these formulas are needed to calcuate the final formula(s)
diameter = int(input("Enter the diameter of the pizza (in inches): "))
price = int(input("Enter the price of the pizza (in dollars): "))
#this equation converts the user inputs and combines it with the formula for area
areaprice = (pi * ((diameter / 2) ** 2) /(price))
print("\nThe cost is", round(areaprice,2), "cents per square inch.")
main()
| true
|
c39f73d378d46a8380e2ed3d50650d0475ee20f8
|
Python
|
DaniilBelousov/Paintings-dataset
|
/picToGray.py
|
UTF-8
| 270
| 2.859375
| 3
|
[] |
no_license
|
import cv2 as cv
import os
# Картинка в серый
def pictureToGray(root, pics):
os.chdir(root)
for pic in pics:
gray = cv.imread(pic, 0)
cv.imwrite(pic, gray)
print("Directory: ", root)
print("Changed into gray --> Success")
| true
|
9a23192c46335044aac4e89c618543c8a6a5df6c
|
Python
|
minhd2/advent-of-code-2020
|
/day8_handheld_halting/day8.py
|
UTF-8
| 828
| 3.078125
| 3
|
[] |
no_license
|
def calculate_acc(filename):
acc = 0
game_on = True
game_steps = dict()
index_set = set()
with open(filename, 'r') as file:
lines = [line.rstrip() for line in file]
#print(lines)
index = 0
while game_on:
if index in index_set:
print(index)
game_on = False
break
elif lines[index][:3] == 'nop':
index_set.add(index)
index += 1
continue
elif lines[index][:3] == 'jmp':
index_set.add(index)
if lines[index][4] == '-':
index -= int(lines[index][5:])
else:
index += int(lines[index][5:])
elif lines[index][:3] == 'acc':
index_set.add(index)
if lines[index][4] == '-':
acc -= int(lines[index][5:])
index += 1
else:
acc += int(lines[index][5:])
index += 1
print(index_set)
print(acc)
print(calculate_acc('data.txt'))
| true
|
4153681171496207027aedbfba05416528cc8b9e
|
Python
|
sven123/auxiliary
|
/aux/protocol/transport.py
|
UTF-8
| 2,934
| 2.78125
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
from socket import ( socket, AF_INET, SOCK_DGRAM,
IPPROTO_TCP, SOCK_STREAM,
SOL_SOCKET, SO_REUSEADDR)
from ssl import wrap_socket, CERT_NONE
TCP_DEFAULT_FRAME_SIZE = 1200
class Transport(object):
def __init__(self, hostname, port):
self.addr = (hostname, port)
self.__connection = None
def connect(self):
raise Exception("Not Implemented Error")
def close(self):
raise Exception("Not Implemented Error")
class UDPTransport(Transport):
def __init__(self, hostname, port):
super(UDPTransport, self).__init__(hostname, port)
self.__connection = socket(AF_INET, SOCK_DGRAM)
def connect(self):
self.__connection.connect(self.addr)
def send(self, message):
self.__connection.sendto(message, self.addr)
def recv(self):
return self.__connection.recv(4096)
def close(self):
self.__connection.close()
class TCPTransport(Transport):
def __init__(self, hostname, port):
super(TCPTransport, self).__init__(hostname, port)
self.__connection = socket(AF_INET, SOCK_STREAM)
self.__connection.setsockopt(SOL_SOCKET,
SO_REUSEADDR,
1)
def connect(self):
self.__connection.connect(self.addr)
def send(self, message):
self.__connection.sendto(message, self.addr)
def recv(self, frame_size=TCP_DEFAULT_FRAME_SIZE):
return self.__connection.recv(frame_size)
def close(self):
self.__connection.close()
class TLS_TCPTransport(TCPTransport):
#TODO: This should just be a wrapper
def __init__(self, hostname, port, timeout=10):
super(TLS_TCPTransport, self).__init__(hostname, port)
#TODO: Should do a better build up of ssl_socket
self.__connection = wrap_socket(socket(AF_INET, SOCK_STREAM),
cert_reqs=CERT_NONE,
do_handshake_on_connect=False)
self.__connection.setsockopt(SOL_SOCKET,
SO_REUSEADDR,
1)
self.__connection.settimeout(1)
self.__connection.settimeout(timeout)
def connect(self):
try:
self.__connection.connect(self.addr)
finally:
pass
def send(self, message):
self.__connection.write(message)
def recv(self, n_of_bytes=TCP_DEFAULT_FRAME_SIZE):
return self.__connection.read(n_of_bytes)
def recv_all(self):
data = self.recv(n_of_bytes=1000)
while data:
print "receiving", data
recv_buffer = data
data = self.recv(n_of_bytes=1000)
return recv_buffer
def close(self):
self.__connection.close()
| true
|
6b9a791d54fee75423af97194a5a9c04ff81b93b
|
Python
|
blitzbutter/MyCode
|
/netCalc.py
|
UTF-8
| 1,718
| 4.03125
| 4
|
[] |
no_license
|
### Jacob Bryant
### 12/8/2018
### Program to calculate the network address
# --- Takes a string to ask a user as input --- #
def calc_bin(user_in):
bin_f = "{0:08d}" # Pads binary numbers with 8 bytes
# --- Formats the input IP address and converts it to binary --- #
ip_in = input(user_in)
ip = ip_in.split('.')
ip_bin = ""
for i in range(0, len(ip)):
ip[i] = bin(int(ip[i])) # Converts it to binary
ip[i] = ip[i].replace('0b','') # Removes the leading '0b'
ip[i] = bin_f.format(int(ip[i])) # Formats the input to pad with eight zeroes
ip_bin += ip[i] # Adds it to the string of binary numbers
return ip_bin
# --- Ask the user for the IP and netmask --- #
ip_str = calc_bin("Enter IP: ")
net_str = calc_bin("Enter netmask: ")
# --- Lets the user know what operation is happening --- #
print("ANDing %s" % ip_str)
print(" %s" % net_str)
network_ip = "" # Network IP variable
# --- And each individual bit in the IP and netmask string of bits, then store in network_ip --- #
for i in range(0, len(ip_str)):
bit = int(ip_str[i]) & int(net_str[i]) # Ands each individual bit
network_ip += str(bit)
# --- Splits the string of bits into 4 parts, to convert back to their decimal counterparts --- #
n = 8
network_ip = [network_ip[i:i+n] for i in range(0, len(network_ip), n)]
# --- Converts back to decimal format and formats the output nicely --- #
network_ip_out = ""
for i in range(0, len(network_ip)):
network_ip_out += str(int(network_ip[i], 2))
if i != len(network_ip)-1:
network_ip_out += '.'
print("Network address is %s" % network_ip_out) # Prints the network IP
| true
|
95d0eb1e30db3e1e72be1ae3562bee3d2b46a801
|
Python
|
DrRamm/mediatek-lte-baseband-re
|
/SoC/common/make_image.py
|
UTF-8
| 9,114
| 2.59375
| 3
|
[] |
no_license
|
#!/usr/bin/env python3
'''\
Create "preloader" images suitable for booting on MediaTek platforms.
Provide an ARMv7-A/ARMv8-A (AArch32-only) binary as an input, and this
tool will convert it into an image that, depending on your selected
options, will be able to be booted from either eMMC flash or an SD card.
For example, to create an eMMC image, run:
./make_image.py -b eMMC -o preloader-emmc.img code.bin
This can be written to the eMMC BOOT0 hardware partition using
MediaTek's SPFT utility, the same way any other preloader is written.
To create an SD image, run:
./make_image.py -b SD -o preloader-sd.img code.bin
To write the image to an SD card, run:
sudo dd if=preloader-sd.img of=/dev/DEVICE bs=2048 seek=1
Where `/dev/DEVICE` is the path to your SD card, e.g., `/dev/sdX` or
`/dev/mmcblkX`.
This command writes the SD preloader to byte offset 2048 (LBA 4,
512-byte blocks) on the card, so if you want to create a partition table
on the card, you MUST you an MBR (DOS) scheme--writing a GPT after
flashing the preloader will likely overwrite the preloader, and writing
the preloader after creating the GPT will likely corrupt the GPT. It is
equally important to ensure that your first partition starts at sector
(LBA) 4096--this will give enough space for the largest possible
preloader size (1 MiB, the size of the L2 SRAM on some higher-end SoCs),
plus it will ensure your partitions are nicely aligned. 4096 is largely
an arbitrary number, since the smallest LBA number to avoid the first
partition overwriting the preloader is 2052 (LBA 4 + 1 MiB / 512 B), so
in theory you could use that (or an even smaller number for devices with
a 256 KiB L2 SRAM), but 4096 is a nice power of 2 so I like that better.
'''
import argparse
import enum
import hashlib
import struct
class code_arch(enum.Enum):
aarch32 = enum.auto()
aarch64 = enum.auto()
class flash_device(enum.Enum):
EMMC = enum.auto()
SD = enum.auto()
class gfh_type(enum.Enum):
FILE_INFO = enum.auto(),
BL_INFO = enum.auto(),
ANTI_CLONE = enum.auto(),
BL_SEC_KEY = enum.auto(),
BROM_CFG = enum.auto(),
BROM_SEC_CFG = enum.auto(),
def gen_gfh_header(type, version):
magic = b'MMM'
size = {
gfh_type.FILE_INFO: 56,
gfh_type.BL_INFO: 12,
gfh_type.ANTI_CLONE: 20,
gfh_type.BL_SEC_KEY: 532,
gfh_type.BROM_CFG: 100,
gfh_type.BROM_SEC_CFG: 48,
}.get(type)
if size == None:
raise ValueError("Unknown gfh_type: {}".format(type))
type = {
gfh_type.FILE_INFO: 0,
gfh_type.BL_INFO: 1,
gfh_type.ANTI_CLONE: 2,
gfh_type.BL_SEC_KEY: 3,
gfh_type.BROM_CFG: 7,
gfh_type.BROM_SEC_CFG: 8,
}.get(type)
h = struct.pack('3s', magic)
h += struct.pack('B', version)
h += struct.pack('<H', size)
h += struct.pack('<H', type)
return h
def gen_gfh_file_info(file_type, flash_dev, offset, base_addr, start_addr, max_size, payload_size):
identifier = b'FILE_INFO'
file_ver = 1
sig_type = 1 # SIG_PHASH
load_addr = base_addr - offset
sig_len = 32 # SHA256
file_len = offset + payload_size + sig_len
jump_offset = start_addr - load_addr
attr = 1
file_info = gen_gfh_header(gfh_type.FILE_INFO, 1)
file_info += struct.pack('12s', identifier)
file_info += struct.pack('<I', file_ver)
file_info += struct.pack('<H', file_type)
file_info += struct.pack('B', flash_dev)
file_info += struct.pack('B', sig_type)
file_info += struct.pack('<I', load_addr)
file_info += struct.pack('<I', file_len)
file_info += struct.pack('<I', max_size)
file_info += struct.pack('<I', offset)
file_info += struct.pack('<I', sig_len)
file_info += struct.pack('<I', jump_offset)
file_info += struct.pack('<I', attr)
return file_info
def gen_gfh_bl_info():
bl_info = gen_gfh_header(gfh_type.BL_INFO, 1)
bl_info += struct.pack('<I', 1)
return bl_info
def gen_gfh_brom_cfg(arch):
brom_cfg = gen_gfh_header(gfh_type.BROM_CFG, 3)
# TODO: Make this configurable.
brom_cfg += bytes.fromhex("9001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000881300000000000000000000")
if arch == code_arch.aarch64:
brom_cfg = bytearray(brom_cfg)
# Set the flag.
flags = struct.unpack_from('<I', brom_cfg, 8)[0]
flags |= 1 << 12
struct.pack_into('<I', brom_cfg, 8, flags)
# Set the magic value.
brom_cfg[0x55] = 0x64
brom_cfg = bytes(brom_cfg)
return brom_cfg
def gen_gfh_bl_sec_key():
bl_sec_key = gen_gfh_header(gfh_type.BL_SEC_KEY, 1)
bl_sec_key += bytes(bytearray(524))
return bl_sec_key
def gen_gfh_anti_clone():
anti_clone = gen_gfh_header(gfh_type.ANTI_CLONE, 1)
anti_clone += bytes(bytearray(12))
return anti_clone
def gen_gfh_brom_sec_cfg():
brom_sec_cfg = gen_gfh_header(gfh_type.BROM_SEC_CFG, 1)
brom_sec_cfg += struct.pack('<I', 3)
brom_sec_cfg += bytes(bytearray(36))
return brom_sec_cfg
def gen_image(boot_device, payload, payload_arch):
# Header
identifier = {
flash_device.EMMC: b'EMMC_BOOT',
flash_device.SD: b'SDMMC_BOOT',
}.get(boot_device)
if identifier == None:
raise ValueError("Unknown boot_device: {}".format(boot_device))
version = 1
dev_rw_unit = {
flash_device.EMMC: 512,
flash_device.SD: 512,
}.get(boot_device)
header = struct.pack('12s', identifier)
header += struct.pack('<I', version)
header += struct.pack('<I', dev_rw_unit)
assert(len(header) <= dev_rw_unit)
padding_length = dev_rw_unit - len(header)
header += bytes(bytearray(padding_length))
# Boot ROM layout
identifier = b'BRLYT'
version = 1
gfh_block_offset = 4
# Must be >=2 to account for the device header and boot ROM layout blocks.
assert(gfh_block_offset >= 2)
boot_region_addr = {
flash_device.EMMC: dev_rw_unit * gfh_block_offset,
flash_device.SD: dev_rw_unit * gfh_block_offset + 2048, # SDMMC_BOOT is flashed to byte offset 2048 on the SD card.
}.get(boot_device)
max_preloader_size = 0x40000 # 0x40000 is the size of the L2 SRAM, so the maximum possible size of the preloader.
main_region_addr = max_preloader_size + boot_region_addr
layout = struct.pack('8s', identifier)
layout += struct.pack('<I', version)
layout += struct.pack('<I', boot_region_addr)
layout += struct.pack('<I', main_region_addr)
# bootloader_descriptors[0]
bl_exist_magic = b'BBBB'
bl_dev = {
flash_device.EMMC: 5,
flash_device.SD: 8,
}.get(boot_device)
bl_type = 1 # ARM_BL
bl_begin_addr = boot_region_addr
bl_boundary_addr = main_region_addr
bl_attribute = 1
layout += struct.pack('4s', bl_exist_magic)
layout += struct.pack('<H', bl_dev)
layout += struct.pack('<H', bl_type)
layout += struct.pack('<I', bl_begin_addr)
layout += struct.pack('<I', bl_boundary_addr)
layout += struct.pack('<I', bl_attribute)
layout_max_size = dev_rw_unit * (gfh_block_offset - 1)
assert(len(layout) <= layout_max_size)
padding_length = layout_max_size - len(layout)
layout += bytes(bytearray(padding_length))
# GFH image
offset = 0x300
base_addr = 0x201000
start_addr = base_addr
image = gen_gfh_file_info(bl_type, bl_dev, offset, base_addr, start_addr, max_preloader_size, len(payload))
image += gen_gfh_bl_info()
image += gen_gfh_brom_cfg(payload_arch)
image += gen_gfh_bl_sec_key()
image += gen_gfh_anti_clone()
image += gen_gfh_brom_sec_cfg()
assert(len(image) <= offset)
padding_length = offset - len(image)
image += bytes(bytearray(padding_length))
image += payload
image += hashlib.sha256(image).digest()
return header + layout + image
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("input", type=str, help="Input binary.")
parser.add_argument("-o", "--output", type=str, default="preloader.img", help="Output image.")
parser.add_argument("-b", "--boot-device", type=str, choices=["eMMC", "SD"], default="eMMC", help="Boot device.")
parser.add_argument("-a", "--arch", type=str, choices=["aarch32", "aarch64"], default="aarch32", help="Code architecture. Choose \"aarch32\" if you're booting 32-bit ARM code, \"aarch64\" for 64-bit ARM code.")
args = parser.parse_args()
binary = open(args.input, 'rb').read()
padding_length = 4 - (len(binary) % 4)
if padding_length != 4:
binary += bytes(bytearray(padding_length))
boot_device = {
"eMMC": flash_device.EMMC,
"SD": flash_device.SD,
}.get(args.boot_device)
arch = {
"aarch32": code_arch.aarch32,
"aarch64": code_arch.aarch64,
}.get(args.arch)
image = gen_image(boot_device, binary, arch)
output = open(args.output, 'wb')
output.write(image)
output.close()
| true
|
ce96543e05919addfeca5d7e3cb1288781e7a8c2
|
Python
|
kinketu/FEM
|
/ElasticProblem/ElasticProblem.py
|
UTF-8
| 5,866
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
# This program is to solve Linear elastic problem using FEM solver.
# Use Triangular Element.
# Asumption plane strain analysis.
# Units of pressure to use MPa
# Units of force to use MN
from numpy import array, zeros, dot
from numpy.linalg import solve
import matplotlib.pyplot as plt
from openacoustics.gmsh import *
import fem
def preprocessor(debug=True):
if debug == True:
# Create nodes and element.
nodes = array([[0., 0.], [0., 1.], [1., 0.], [1., 1.]])
elements = array([[0, 2, 1], [3, 1, 2]])
elif debug == False:
# Create nodes and element.
# Create an instance of class gmsh.
gmsh = GMsh2D()
# Load the .geo file.
geo = 'ElasticProblem.geo'
gmsh.loadGeo(geo, 0.2, order=1)
# Load nodes indices and coordinates.
nodes = gmsh.getNodes()
# Get the sorce node number.
source = gmsh.getPoints("S")
# Load node numbers of triangular elements.
elements = gmsh.getTriangles("", order=1)
return nodes, elements
def element_matrix(node0, node1, node2):
t = 1 # t is thickness.
b01 = node0[1]-node1[1]
b12 = node1[1]-node2[1]
b20 = node2[1]-node0[1]
a10 = node1[0]-node0[0]
a21 = node2[0]-node1[0]
a02 = node0[0]-node2[0]
detA =(a10*b20-b01*a02)
Be = array([[b12, 0., b20, 0., b01, 0.],
[0., a21, 0., a02, 0., a10],
[a21, b12, a02, b20, a10, b01]])/detA
Ke = t*dot(dot(Be.T, D), Be)*detA/2
return Ke, Be
def node_matrix(d, element):
dn = []
for node in element:
de.append([node*2, node*2+1])
dn = array(dn).flatten()
return dn
def createDmatrix(PlaneType="Strain"):
if PlaneType == "Strain":
# Plane Strain
D = array([[1-Poisson, Poisson, 0.],
[Poisson, 1-Poisson, 0.],
[0., 0., (1-2*Poisson)/2.]])\
*Young/((1+Poisson)*(1-2*Poisson))
elif PlaneType == "Stress":
# Plane Stress
D = array([[1., Poisson, 0.],
[Poisson, 1., 0.],
[0., 0., (1-Poisson)/2]])*Young/(1-Poisson**2)
return D
def totalmatrices(nodes, elements):
# Create total matrix.
numberOfNodes = nodes.shape[0]
numberOfElements = elements.shape[0]
K = zeros((numberOfNodes*2, numberOfNodes*2))
B = []
for element in elements:
node0 = nodes[element[0], :]
node1 = nodes[element[1], :]
node2 = nodes[element[2], :]
# Calculate elementary matrices.
Ke, Be = element_matrix(node0, node1, node2)
B.append(Be)
# Assemble global system matrices.
# Convert local number into global number.
list1 = []
list2 = []
for i in range(numberOfNodes):
list1.append([i*2, i*2+1])
for i in element:
list2.append(list1[i])
list2 = array(list2).flatten()
#print list2
for rowIndex in range(Ke.shape[0]):
for columnIndex in range(Ke.shape[1]):
K[list2[rowIndex], list2[columnIndex]]\
+= Ke[rowIndex, columnIndex]
B = array(B)
return K, B
def total_strain():
eps = []
for element in elements:
element_number = list(elements).index(list(element))
dn = node_matrix(d, element)
epse = dot(B[element_number], dn)
eps.append(epse)
eps = array(eps)
return eps
def mizes_stress(stress):
sigx = stress[0]
sigy = stress[1]
sigz = stress[2]
tauxy = stress[3]
tauyz = stress[4]
tauzx = stress[5]
mizes = sqrt(((sigx-sigy)**2+(sigy-sigz)**2+(sigz-sigx)**2\
+6*(tauxy**2+tauyz**2+tauzx**2))/2)
return mizes
def postprocessor(nodes, saveimage=False):
pass
def plot_displacement(old_nodes, new_nodes, saveimage=False):
x1 = old_nodes[:, 0]
y1 = old_nodes[:, 1]
x2 = new_nodes[:, 0]
y2 = new_nodes[:, 1]
plt.figure()
plt.gca().set_aspect('equal')
plt.triplot(x1, y1, elements, 'ko-')
plt.triplot(x2, y2, elements, 'bo--')
plt.title("Elastic Problem")
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(-0.1, 1.1)
plt.ylim(-0.1, 1.1)
if saveimage == True:
plt.savefig("Elastic_Problem.png")
plt.show()
def plot_mizes(nodes, elements, mizes, saveimage=False):
x = nodes[:, 0]
y = nodes[:, 1]
plt.figure()
plt.gca().set_aspect('equal')
plt.tripcolor(x, y, elements, facecolors=mizes, edgecolors='k')
plt.colorbar()
plt.title("von-Mizes stress")
plt.xlabel('x')
plt.ylabel('y')
plt.axis('tight')
if saveimage == True:
plt.savefig("mizes.png")
plt.show()
if __name__ == '__main__':
# Preprocessor
nodes, elements = preprocessor()
# Solver
# Young's modulus and Poisson's ration of soft iron
Young = 200*10**3 # MPa
Poisson = 0.3
D = createDmatrix()
K, B = totalmatrices(nodes, elements)
unval = 100 # unkown value
f = array([unval, unval, unval, 0, 10, unval, 10, 0])
# "discon" is a list of displcement constraint.
# ex) discon = [[index number in the K matrix, value], ...]
discon = [[0, 0], [1, 0], [2, 0], [5, 0]]
K, f = fem.dis_to_force2(discon, K, f)
d = solve(K, f)
d = d.reshape((d.shape[0]/2, 2))
dis_scale = 500 # displacement scale
new_nodes = nodes + d * dis_scale
#eps = total_strain()
# Print Debug
#print "matrixK\n", K
#print "displacement\n", d
# Postprocessor
#plot_displacement(nodes, new_nodes)
print d
| true
|
53fb96c689a745594c62571edfd2104395c7ceb2
|
Python
|
Aasthaengg/IBMdataset
|
/Python_codes/p03439/s110811200.py
|
UTF-8
| 1,334
| 3.03125
| 3
|
[] |
no_license
|
import bisect
import heapq
import sys
import queue
input = sys.stdin.readline
sys.setrecursionlimit(100000)
class V:
def __init__(self, f):
self.f = f
self.v = None
def __str__(self):
return str(self.v)
def ud(self, n):
if self.v is None:
self.v = n
else:
self.v = self.f(self.v, n)
def get(self):
return self.v
def read_values():
return map(int, input().split())
def read_list():
return list(read_values())
def main():
N = int(input())
left = 0
right = N - 1
D = {}
c = 0
for _ in range(21):
if left not in D:
print(left)
sys.stdout.flush()
res = input()
c += 1
if res == "Vacant" or c >= 20:
return
D[left] = res
LD = D[left]
m = (left + right) // 2
if m not in D:
print(m)
sys.stdout.flush()
res = input()
c += 1
if res == "Vacant" and c >= 20:
return
D[m] = res
MD = D[m]
if (m % 2 == left % 2 and MD == LD) or (m % 2 != left % 2 and MD != LD):
left = m if left != m else m + 1
else:
right = m
if __name__ == "__main__":
main()
| true
|
6c38f1ca9636261cab363979cd5c1ab8c46a4a30
|
Python
|
NacerSebtiMS/GAN_MNIST
|
/dataset.py
|
UTF-8
| 3,148
| 2.953125
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
import gzip
import numpy as np
import matplotlib.pyplot as plt
import gzip
test_image_path = 'data/t10k-images-idx3-ubyte.gz'
test_label_path = 'data/t10k-labels-idx1-ubyte.gz'
train_image_path = 'data/train-images-idx3-ubyte.gz'
train_label_path = 'data/train-labels-idx1-ubyte.gz'
#----------------------------------------------------------------------------
# Direct interaction with the dataset
# Getting labels
def get_label(n,train=True):
if train:
file = gzip.open(train_label_path,'r')
else :
file = gzip.open(test_label_path,'r')
file.read(8)
buff = file.read(1 * n)
labels = np.frombuffer(buff, dtype=np.uint8).astype(np.int64)
return labels[-1]
# Getting images
def get_img(n,train=True):
if train:
file = gzip.open(train_image_path,'r')
else :
file = gzip.open(test_image_path,'r')
image_size = 28
file.read(16)
buff = file.read(image_size * image_size * n)
data = np.frombuffer(buff, dtype=np.uint8).astype(np.float32)
data = data.reshape(n, image_size, image_size, 1)
image = np.asarray(data[-1]).squeeze()
return image
# Getting both the image and the label at given index from the dataset
def get_both(n,train=True):
return get_label(n,train),get_img(n,train)
# Returns n iamges with the given label
def get_img_by_lbl(n,label,train=True):
cpt=1
imgs = []
while n>len(imgs):
if get_label(cpt,train) == label:
imgs += [get_img(cpt,train)]
cpt+=1
return imgs
# Returns a complete set in a list
def get_set(train=True,n=0):
if train:
file_lbl = gzip.open(train_label_path,'r')
file_img = gzip.open(train_image_path,'r')
if n == 0 :
n = 60000
else :
file_lbl = gzip.open(test_label_path,'r')
file_img = gzip.open(test_image_path,'r')
if n == 0 :
n = 10000
file_lbl.read(8)
buff = file_lbl.read(1 * n)
labels = np.frombuffer(buff, dtype=np.uint8).astype(np.int64)
image_size = 28
file_img.read(16)
buff = file_img.read(image_size * image_size * n)
data = np.frombuffer(buff, dtype=np.uint8).astype(np.float32)
data = data.reshape(n, image_size, image_size, 1)
return [data,labels]
def save_images(images, size, image_path):
return imsave(inverse_transform(images), size, image_path)
#----------------------------------------------------------------------------
# Functions used to print the results
def show_img(img):
plt.imshow(img)
def show_mult_img(imgs):
n = len(imgs)
l = int(n**(1/2))
if int(n**(1/2)) != n**(1/2):
l+=1
fig = plt.figure(figsize=(l*2,l*2))
for i in range(len(imgs)):
sub = fig.add_subplot(l,l,i+1)
sub.imshow(imgs[i], interpolation='nearest')
#----------------------------------------------------------------------------
# Testing Area
def test():
# n = 15
# lbl,img = get_both(n)
# print(lbl)
# plt.imshow(img)
get_set()
if __name__ == "__main__":
test()
| true
|
fc4daaa789e3fb4b620a82d5949b53a6979d34c1
|
Python
|
liuq4360/recommender_systems_abc
|
/preprocessing/netflix_prize/transform2triple.py
|
UTF-8
| 831
| 2.90625
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# coding=utf-8
# 将training_set转换为三元组(userid,videoid,score)
import os
cwd = os.getcwd() # 获取当前工作目录
f_path = os.path.abspath(os.path.join(cwd, "..")) # 获取上一级目录
all_files = os.listdir(f_path + '/data/mini_training_set')
data = f_path + "/output/data.txt"
fp = open(data, 'w') # 打开文件,如果文件不存在则创建它,该文件是存储最终的三元组
for path in all_files:
with open(f_path+"/data/training_set/"+path, "r") as f: # 设置文件对象
lines = f.readlines()
video_id = lines[0].strip(':\n')
for l in lines[1:]:
user_score_time = l.strip('\n').split(',')
user_id = user_score_time[0]
score = user_score_time[1]
fp.write(user_id+","+video_id+","+score+"\n")
fp.close()
| true
|
5d9dfea2b95dbe3d48e05e6dc93f08237672a948
|
Python
|
adrianosferreira/python-algorithms
|
/study.py
|
UTF-8
| 1,217
| 3.015625
| 3
|
[] |
no_license
|
adjacent_list = {
1: [2, 5],
2: [1, 3],
3: [6, 4, 2],
4: [5, 3],
5: [1, 4],
6: [3, 7],
7: [6, 8, 9],
8: [7],
9: [7],
}
def find_articulation_points():
visited = [False for x in range(len(adjacent_list) + 1)]
dt = [0 for x in range(len(adjacent_list) + 1)]
low_link = [0 for x in range(len(adjacent_list) + 1)]
ap = [False for x in range(len(adjacent_list) + 1)]
helper(1, visited, low_link, dt, -1, ap)
for i in range(len(ap)):
if ap[i]:
print(f"AP: %s" % i)
def helper(node, visited, low_link, dt, parent, ap):
id = max(dt) + 1
dt[node] = low_link[node] = id
visited[node] = True
children = 0
for neighbour in adjacent_list[node]:
if not visited[neighbour]:
children += 1
helper(neighbour, visited, low_link, dt, node, ap)
low_link[node] = min(low_link[node], low_link[neighbour])
if parent != -1 and low_link[neighbour] >= dt[node]:
ap[node] = True
if parent == -1 and children > 1:
ap[node] = True
else:
low_link[node] = min(low_link[node], dt[neighbour])
find_articulation_points()
| true
|
75104a69fcd4c02cf00847e242e5573e1f8907d4
|
Python
|
shawn-hurley/testproject
|
/inventory/models.py
|
UTF-8
| 1,432
| 2.75
| 3
|
[] |
no_license
|
from django.db import models
# Create your models here.
class Category(models.Model):
"""Category for each item."""
name = models.CharField("Category Name", max_length=50)
description = models.TextField("Description")
def save(self):
super(Category, self).save()
def get_category(cate):
return Category.objects.filter(name=cate)
def __unicode__(self):
return self.name
class Item(models.Model):
"""Item, this should never be updated unless by admins
These will only be managed by admins through either
the admin interface or what will eventually be the dashboard
"""
name = models.CharField("Item Name", max_length=150)
category = models.ForeignKey(Category)
min_num = models.PositiveIntegerField("Minumum Number")
def save(self):
super(Item, self).save()
def get_item(item):
return Item.objects.get(name=item)
def __unicode__(self):
return self.name
class InventoryRecord(models.Model):
"""This will record that is manipulated trough the interface.
This will keep track of quantity of that item, and the last
time it was edited
"""
item = models.ForeignKey(Item)
quantity = models.PositiveIntegerField("Quantity")
last_update = models.DateTimeField("Last Update", auto_now_add=True)
def save(self):
super(InventoryRecord, self).save()
def get_inventory_recorded(record):
return InventoryRecord.objects.get(name=record)
def __unicode__(self):
return unicode(self.item)
| true
|
3a267bb21aa82f8e57e754b4a442afc2e9dc7dd1
|
Python
|
ushahamsaraju/sampleproject
|
/EMS/submodules/add.py
|
UTF-8
| 2,045
| 3.25
| 3
|
[] |
no_license
|
import re
from randompwd import id_generator,get_emp_details
import smtplib
class employee():
def add_employee(self):
Eid=raw_input("Enter Employee Number:")
while True:
if Eid in get_emp_details(0):
print "NUmber Already exists"
print "Enter a number once again"
else:
break
Ename=raw_input("Enter Employee Name:")
Designation=raw_input("Enter Employee Designation:")
Deptno=raw_input("Enter Employee Department Number:")
flag=True
while flag:
try:
Salary=int(raw_input("Enter Employee Salary:"))
except Exception as e:
print "Enter only Integer values"
continue
if int(Salary)>0:
flag=False
else:
print "Salary Should be Positive, please enter correctely"
flag = True
while flag:
Email = raw_input("Please Enter Email :")
if re.search('\w+[.|\w]\w+@\w+[.]\w+[.|\w+]\w+',Email):
flag = False
else:
print "Invalid Email, Please try again."
Address=raw_input("Enter Employee Address:")
flag = True
while flag:
try:
Phno = int(raw_input("Please Enter 10 digit Mobile Number :"))
except Exception:
print "Enter only numbers, Please try again."
continue
if len(str(Phno)) == 10:
flag = False
else:
print "Invalid Phone Number, Please try again."
f=open("employee.txt","a")
data="%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n"%(Eid,Ename,Designation,Deptno,Salary,Email,Address,Phno)
f.write(data)
f.close()
s=raw_input("enter y or n")
print "If You want to enter one more employee:",s
if s=='y':
add_employee()
else:
exit()
e=employee()
e.add_employee()
| true
|
2990621417909474964bc9bf6e533fd8ae944164
|
Python
|
mhhennig/spikeforest
|
/spikeforest/forestview/recording_views/currentstateview.py
|
UTF-8
| 670
| 2.734375
| 3
|
[
"Apache-2.0"
] |
permissive
|
import vdomr as vd
import json
class CurrentStateView(vd.Component):
def __init__(self, context):
vd.Component.__init__(self)
self._context = context
self._context.onAnyStateChanged(self.refresh)
self._size = (100, 100)
def tabLabel(self):
return 'Current state'
def setSize(self, size):
if self._size == size:
return
self._size = size
self.refresh()
def size(self):
return self._size
def render(self):
state0 = self._context.stateObject()
return vd.div(
vd.pre(
json.dumps(state0, indent=4)
)
)
| true
|
f310e66f222609ac41b2284ce325a45a984281a5
|
Python
|
giuliano-sider/preparing-for-the-quantum-apocalypse
|
/ntru_implementations/python/ntru_a_new_hope.py
|
UTF-8
| 31,640
| 3.0625
| 3
|
[] |
no_license
|
#!/usr/bin/env python3
"""ntru: a new hope"""
import secrets
import hashlib
import random
import re
import math
import sys
def extended_euclidean_algorithm(a, b):
"""purely iterative version of the extended euclidean algorithm.
compute gcd of integers a and b, as well as integers x and y"""
""" such that ax + by = gcd(x,y). return (x,y,gcd(a,b))."""
assert type(a) is int and type(b) is int
sign_a = 1
sign_b = 1
if a < 0:
sign_a = -1
a = -a
if b < 0:
sign_b = -1
b = -b
# maintain the loop invariant: r_j = s_j * a + t_j * b, for all j > 0
r_j_2 = a; s_j_2 = 1; t_j_2 = 0
r_j_1 = b; s_j_1 = 0; t_j_1 = 1
while r_j_1 > 0:
q_j_1 = r_j_2 // r_j_1
r_j = r_j_2 - q_j_1 * r_j_1
s_j = s_j_2 - q_j_1 * s_j_1
t_j = t_j_2 - q_j_1 * t_j_1
r_j_1, r_j_2 = r_j, r_j_1
s_j_1, s_j_2 = s_j, s_j_1
t_j_1, t_j_2 = t_j, t_j_1
return (sign_a * s_j_2, sign_b * t_j_2, r_j_2)
def mod_inverse(num, m):
"""calculate multiplicative inverse of num, modulo a positive integer m"""
assert(m > 0)
a, b, g = extended_euclidean_algorithm(num, m)
if g != 1:
raise ArithmeticError('the number %d does not have a multiplicative inverse modulo %d'
% (num, m))
return a % m
def str2coefflist(s):
"""convert a string representation of a polynomial to a list of coefficients."""
""" last element of the list (highest degree term) is non zero. the zero polynomial"""
""" is represented by an empty list."""
coefflist = []
degree = -1
s = s.replace('-', '+-')
terms = s.split('+')
for term in terms:
term = term.replace(' ', '')
match = re.fullmatch(r"""(?xi)
(-?\d+)? (?# group 1: coefficient for this term)
(\*? x (?: (?:\^|\*\*) (?# group 2: is there an x?)
(\d+) (?# group 3: exponent)
)?)?""",
term)
if match is None: # match failed
raise SyntaxError('polynomial must be a sum of terms k*x^e')
coeff, xterm, exponent = match.groups()
if coeff is None and xterm is None:
continue
coeff = 1 if coeff is None else int(coeff)
if exponent is None and xterm is None:
exponent = 0
elif exponent is None:
exponent = 1
else:
exponent = int(exponent)
if coeff != 0:
for i in range(degree + 1, exponent + 1):
coefflist.append(0)
degree += 1
coefflist[exponent] += coeff
return coefflist
def coefflist2str(coefflist):
"""convert a coefficient list of a polynomial to a string representation"""
noitems = True
s = ''
for i in range(len(coefflist) - 1, -1, -1):
if coefflist[i] != 0:
if coefflist[i] > 0:
if noitems == False:
sign = '+'
else:
sign = ''
else:
sign = '-'
if abs(coefflist[i]) != 1 or i == 0:
coeff = ' ' + str(abs(coefflist[i]))
else:
coeff = ''
if i > 0:
x = ' x'
else:
x = ''
if i > 1:
exponent = '^%d' % i
else:
exponent = ''
s += ' %s%s%s%s' % (sign, coeff, x, exponent)
noitems = False
if noitems == True:
s = '0'
return s.strip()
class conv_poly():
"""represents polynomials in the ring Z[x]/(x^n - 1) or Z/pZ[x]/(x^n - 1)
invariant: coefficients in [0, self.coeff_mod) if self.coeff_mod is not None. otherwise there is no restriction.
degree is maintained as the highest non-zero term or -1 if equal to the zero polynomial"""
def __init__(self, n, p=None, polynomial=None):
self.coefflist = [0] * (n + 1) # zero polynomial with n coefficients, going from a_0, ..., a_{n - 1} (but we leave space for an extra coefficient)
self.n = n
self.coeff_mod = p # polynomial in Z[x]/(x^n - 1) ring by default
self.degree = -1 # zero polynomial
if polynomial is not None:
lst = str2coefflist(polynomial)
for i, c in enumerate(lst):
self.coefflist[i] = c
if p is not None:
self.coefflist[i] %= p
if self.coefflist[i] != 0:
self.degree = i
def __str__(self):
return coefflist2str(self.coefflist)
def __repr__(self):
return 'conv_poly(polynomial=%s, n=%d, p=%s)' % (self.__str__(), self.n, str(self.coeff_mod))
def leading_coeff(self):
if self.degree == -1:
return 0
else:
return self.coefflist[self.degree]
def get_degree(self):
for i in range(len(self.coefflist) - 1, -1, -1):
if self.coefflist[i] != 0:
return i
return -1
def set_coeff_mod(self, coeff_mod):
"""!!mutates!! the polynomial by taking every coefficient modulo a new value and changing the modulus of the polynomial"""
self.coeff_mod = coeff_mod
for i in range(len(self.coefflist)):
self.coefflist[i] %= coeff_mod
self.degree = self.get_degree()
def lift(self):
"""!!mutates!! the polynomial and """
"""provides a way of mapping polynomials
from Z/pZ[x]/(x^n - 1) to Z[x]/(x^n - 1) that is used in ntru"""
if self.coeff_mod == None:
raise Exception('polynomial already belongs to the Z[x]/(x^n - 1) ring')
for i in range(0, self.degree + 1):
if self.coefflist[i] > self.coeff_mod // 2:
self.coefflist[i] -= self.coeff_mod
self.coeff_mod = None
def copy(self, new_coeff_mod=None):
"""if new_coeff_mod is not None, the modulus for the new polynomial given by this parameter"""
new_poly = conv_poly(self.n, self.coeff_mod)
new_poly.coefflist = self.coefflist.copy()
new_poly.degree = self.degree
if new_coeff_mod is not None and new_coeff_mod != self.coeff_mod:
new_poly.set_coeff_mod(new_coeff_mod)
return new_poly
def __eq__(self, other):
if self.degree != other.degree:
return False
for i in range(self.degree, -1, -1):
if self.coefflist[i] != other.coefflist[i]:
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def __add__(self, other, op='add'):
"""creates a new polynomial that is the sum or difference of the two operands"""
sign = 1 if op == 'add' else -1
assert (self.coeff_mod == other.coeff_mod)
new_poly = conv_poly(self.n, self.coeff_mod)
i = 0
while i <= self.degree or i <= other.degree:
new_poly.coefflist[i] = self.coefflist[i] + sign * other.coefflist[i]
if new_poly.coeff_mod is not None:
new_poly.coefflist[i] %= new_poly.coeff_mod
if new_poly.coefflist[i] != 0:
new_poly.degree = i
i += 1
return new_poly
def __sub__(self, other):
"""creates a new polynomial that is the difference of the two operands"""
return self.__add__(other, 'sub')
def __mul__(self, other):
"""creates a new polynomial that is the product of the two operands"""
assert self.coeff_mod == other.coeff_mod and self.n == other.n
new_poly = conv_poly(self.n, self.coeff_mod)
for i in range(self.n):
for j in range(self.n):
new_poly.coefflist[i] += self.coefflist[j] * other.coefflist[(i - j) % self.n]
if new_poly.coeff_mod is not None:
new_poly.coefflist[i] %= new_poly.coeff_mod
if new_poly.coefflist[i] != 0:
new_poly.degree = i
return new_poly
def mult_by_term(self, coeff, power):
"""this operation multiplies a polynomial by coeff * x^power (a new polynomial is returned).
it assumes that self.degree + power <= self.n, so there is space is the coefflist"""
new_poly = conv_poly(self.n, self.coeff_mod)
for i in range(self.degree, -1, -1):
new_poly.coefflist[power + i] = coeff * self.coefflist[i]
if new_poly.coeff_mod is not None:
new_poly.coefflist[power + i] %= new_poly.coeff_mod
new_poly.degree = new_poly.get_degree()
return new_poly
def make_monic(self):
"""returns a new non-zero polynomial that is monic by dividing through by the leading coefficient"""
if self.degree == -1: # zero polynomial cannot be monic
raise ValueError('tried to make the zero polynomial monic, which is not possible')
else:
return self.mult_by_term(coeff=mod_inverse(self.leading_coeff(), self.coeff_mod), power=0)
def poly_extended_euclidean_algorithm(self, b):
"""iterative version of the extended euclidean algorithm for polynomials
takes 2 polynomials with coefficients in Z_p and returns a gcd for them, as well
as polynomials x and y such that ax + by = gcd"""
a = self
assert a.coeff_mod is not None and a.coeff_mod == b.coeff_mod and a.n == b.n
p = a.coeff_mod
zero_poly = conv_poly(self.n, p=p)
one_poly = conv_poly(self.n, p=p)
one_poly.coefflist[0] = 1
one_poly.degree = 0
# maintain the loop invariant: r_j = s_j * a + t_j * b, for all j > 0
r_j_2 = a; s_j_2 = one_poly; t_j_2 = zero_poly
r_j_1 = b; s_j_1 = zero_poly; t_j_1 = one_poly
while r_j_1.degree != -1: # while r_j_1 is not the zero polynomial
if r_j_2.degree < r_j_1.degree:
# must switch the two
r_j_1, r_j_2 = r_j_2, r_j_1
s_j_1, s_j_2 = s_j_2, s_j_1
t_j_1, t_j_2 = t_j_2, t_j_1
continue
# must compute r_j = r_j_2 - a_n * b_k_inv * x^(n - k) * r_j_1
b_k_inv = mod_inverse(r_j_1.leading_coeff(), p)
a_n = r_j_2.leading_coeff()
n_minus_k = r_j_2.degree - r_j_1.degree
r_j = r_j_2 - r_j_1.mult_by_term(coeff=((b_k_inv * a_n) % p), power=n_minus_k)
s_j = s_j_2 - s_j_1.mult_by_term(coeff=((b_k_inv * a_n) % p), power=n_minus_k)
t_j = t_j_2 - t_j_1.mult_by_term(coeff=((b_k_inv * a_n) % p), power=n_minus_k)
r_j_1, r_j_2 = r_j, r_j_1
s_j_1, s_j_2 = s_j, s_j_1
t_j_1, t_j_2 = t_j, t_j_1
return (s_j_2, t_j_2, r_j_2)
def invert_with_prime_mod_coeffs(self):
"""designed for polynomials with coefficients in Z_p, p prime"""
assert self.coeff_mod is not None
mod_poly = conv_poly(self.n, self.coeff_mod)
mod_poly.coefflist[self.n] = 1
mod_poly.coefflist[0] = self.coeff_mod - 1
mod_poly.degree = self.n
x, y, g = self.poly_extended_euclidean_algorithm(mod_poly)
if g.degree != 0: # if not a constant, non-zero polynomial, the polynomial is not invertible
raise ArithmeticError('the polynomial does not have a multiplicative inverse modulo')
x_adjusted = x.mult_by_term(coeff=mod_inverse(g.leading_coeff(), self.coeff_mod), power=0)
if x_adjusted.coefflist[self.n] != 0:
x_adjusted.coefflist[0] = (x_adjusted.coefflist[0] + x_adjusted.coefflist[self.n]) % self.coeff_mod
x_adjusted.coefflist[self.n] = 0
x_adjusted.degree = x_adjusted.get_degree()
return x_adjusted
def invert_with_prime_power_mod_coeffs(self, q=None, p=None):
"""invert a polynomial in (Z/qZ[x] / x^n - 1), where q = p^k, p being a prime"""
if q is None:
q = self.coeff_mod
if p is None:
p = q
if q is None:
raise Exception('modulus for calculating the inverse polynomial was not specified')
two_poly = conv_poly(self.n)
two_poly.coefflist[0] = 2
two_poly.degree = 0
tmp_poly = self.copy(new_coeff_mod=p)
inv = tmp_poly.invert_with_prime_mod_coeffs()
while p < q:
p = p * p
two_poly.coeff_mod = p
inv.coeff_mod = p
tmp_poly = self.copy(new_coeff_mod=p)
inv = inv * (two_poly - tmp_poly * inv)
inv.set_coeff_mod(q)
return inv
def msgtext_to_msgpoly(msg_text, n, p, secret_generator=secrets.SystemRandom()):
"""converts a string of text, msg_text (considered in UTF-8 encoding),
into an array of bytes with given output_length in bits for delivery to NTRU (zero padded on the right to byte boundary),
or throws an exception if output length is not enough to pack the message"""
bits_per_coefficient = math.floor(math.log(p, 2))
output_length = n * bits_per_coefficient
# 256 is the size of the 160 sha-1 hash field, 16 bit message bit length and 80 bit mandatory padding
HEADER_SIZE = 256
msg_text_bytes = msg_text.encode()
text_bitlength = len(msg_text_bytes) * 8 # text bit length field
if HEADER_SIZE + text_bitlength > output_length:
raise ValueError('the text "%s", with %d bytes in length, is too large;'
' only %d bytes of payload are possible to encode with a message length of %d bits'
% (msg_text, len(msg_text_bytes), (output_length - HEADER_SIZE) // 8, output_length))
msg_bits = bytearray(20) # sha-1 hash field
msg_bits.append((text_bitlength & 0xFF00) >> 8)
msg_bits.append(text_bitlength & 0xFF)
for i in range(10): # mandatory random padding field
msg_bits.append(secret_generator.randrange(0, 256))
for b in msg_text_bytes:
msg_bits.append(b)
bitcount = HEADER_SIZE + text_bitlength
while bitcount < output_length: # fill out extra random padding up to bit output length
b = 0
for i in range(7,-1,-1):
b |= secret_generator.randrange(0, 2) << i
bitcount += 1
if bitcount >= output_length:
break
msg_bits.append(b)
h = hashlib.sha1() # fill out hash field
h.update(msg_bits[20:])
msg_bits[0:20] = h.digest()
#convert a byte like object to a string of bits in a list"""
msg_bitstring = []
for b in msg_bits:
for i in range(7,-1,-1):
msg_bitstring.append((b & (1 << i)) >> i) # copy ith bit
# generate a polynomial from a sequence of message bits (encoded as a list of bits).
# the first n * floor(log(p)) bits in the msg_bits are turned into coefficients, a_0, ..., a_{n - 1}"""
bitindex = 0
poly = conv_poly(n, p)
for c in range(n):
coeff_val = 0
for bit in range(bits_per_coefficient):
coeff_val = 2 * coeff_val + msg_bitstring[bitindex]
bitindex += 1
poly.coefflist[c] = coeff_val
return poly
class decryption_failure(Exception):
pass
def msgpoly_to_msgtext(poly):
bits_per_coefficient = math.floor(math.log(poly.coeff_mod, 2))
maxval = 2 ** bits_per_coefficient
total_bit_count = bits_per_coefficient * poly.n
bitlist = []
for c in poly.coefflist:
if c >= maxval:
raise decryption_failure('encoding error: message polynomial coefficient too large')
for i in range(bits_per_coefficient - 1, -1, -1):
bitlist.append((c & (1 << i)) >> i) # copy ith bit
bitcount = 0
msg_bits = bytearray()
while bitcount < len(bitlist):
v = 0
for i in range(7,-1,-1):
v |= bitlist[bitcount] << i
bitcount += 1
if bitcount >= len(bitlist):
break
msg_bits.append(v)
hasher = hashlib.sha1()
hasher.update(msg_bits[20:])
check_hash = hasher.digest()
hsh = msg_bits[:20]
if hsh != check_hash:
raise decryption_failure('encoding error: hash values in message do not match up')
HEADER_SIZE = 256
msg_size = msg_bits[20] << 8
msg_size += msg_bits[21]
if HEADER_SIZE + msg_size > total_bit_count:
raise decryption_failure('encoding error: msg_size overflowed the end of the transmitted data')
if msg_size % 8 != 0:
raise decryption_failure('encoding error: must be an incorrect msg_size number of bits in the transmitted data')
return msg_bits[32:32 + msg_size // 8].decode()
def bits_to_poly(bits, n, p):
"""generate a polynomial from a sequence of bits (encoded as a byte-like object).
the first n * ceil(log(p)) bits are turned into coefficients, a_0, ..., a_{n - 1}"""
# convert a byte like object to a string of bits in a list
bitstring = []
for b in bits:
for i in range(7,-1,-1):
bitstring.append((b & (1 << i)) >> i) # copy ith bit
bits_per_coefficient = math.ceil(math.log(p, 2))
if len(bitstring) < n * bits_per_coefficient:
raise ValueError('expected at least %d * %d = %d bits in byte sequence to be encoded into a polynomial, '
'but only %d were found\n'
% (n, bits_per_coefficient, n * bits_per_coefficient, len(bitstring)))
bitindex = 0
poly = conv_poly(n, p)
for i in range(n):
coeff_val = 0
for b in range(bits_per_coefficient):
coeff_val = 2 * coeff_val + bitstring[bitindex]
bitindex += 1
if coeff_val >= p:
raise ValueError('encoding error: value of %d for coefficient %d is too large' % (coeff_val, i))
poly.coefflist[i] = coeff_val
if coeff_val != 0:
poly.degree = i
return poly
def poly_to_bits(poly):
"""returns a sequence of bytes having a bit prefix of length n * ceil(log(p))"""
bits_per_coefficient = math.ceil(math.log(poly.coeff_mod, 2))
total_bits = poly.n * bits_per_coefficient
bitlist = []
for c in poly.coefflist:
for i in range(bits_per_coefficient - 1, -1, -1):
bitlist.append((c & (1 << i)) >> i) # copy ith bit
bitcount = 0
msg_bits = bytearray()
while bitcount < len(bitlist):
v = 0
for i in range(7,-1,-1):
v |= bitlist[bitcount] << i
bitcount += 1
if bitcount >= len(bitlist):
break
msg_bits.append(v)
return msg_bits
def generate_random_polynomial(n, ones, minus_ones, secret_generator=secrets.SystemRandom()):
poly_coeff_list = (n + 1) * [0]
ones_filled = 0
minus_ones_filled = 0
degree = -1
while ones_filled < ones:
idx = secret_generator.randrange(0, n)
if poly_coeff_list[idx] == 0:
poly_coeff_list[idx] = 1
ones_filled += 1
if idx > degree:
degree = idx
while minus_ones_filled < minus_ones:
idx = secret_generator.randrange(0, n)
if poly_coeff_list[idx] == 0:
poly_coeff_list[idx] = -1
minus_ones_filled += 1
if idx > degree:
degree = idx
poly = conv_poly(n)
poly.coefflist = poly_coeff_list
poly.degree = degree
return poly
def ntru_keygen(param_set, secret_generator=secrets.SystemRandom()): # by default use high entropy bits obtained from the operating system
"""generate an NTRU key pair,
param_set is a dictionary with keys for parameters n, p, q, d_f, d_g, d_r
return key_info in the format {'f': ____, 'g': ____, 'f_inv_q': ____, 'f_inv_p': ____, 'h': ____, 'params': _____},
where the polynomials are bytearray objects."""
n = param_set['n']
q = param_set['q']
p = param_set['p']
d_f = param_set['d_f']; d_g = param_set['d_g']; d_r = param_set['d_r']
assert 2 * d_f + 1 < n and 2 * d_g < n and 2 * d_r < n
# generate f and its inverses in the large and small convolution rings
valid_f = False
while not valid_f:
f = generate_random_polynomial(n, d_f + 1, d_f, secret_generator)
try:
# q = b^k, information provided in the instance of ntru
f_inv_q = f.invert_with_prime_power_mod_coeffs(q, param_set['prime_factor_q'])
except ArithmeticError as error:
print('%s: could not invert polynomial %s\n%s\n' % (error.args, f, error.args))
continue
try:
# p is assumed to be a prime
f_inv_p = f.copy(new_coeff_mod=param_set['p']).invert_with_prime_mod_coeffs()
except ArithmeticError as error:
print('%s: could not invert polynomial %s\n%s\n' % (error.args, f, error.args))
continue
valid_f = True
g = generate_random_polynomial(n, d_g, d_g, secret_generator)
g.set_coeff_mod(q)
f.set_coeff_mod(q)
h = (f_inv_q * g).mult_by_term(coeff=p, power=0)
return {
'param': param_set,
'f': poly_to_bits(f),
'g': poly_to_bits(g),
'f_inv_q': poly_to_bits(f_inv_q),
'f_inv_p': poly_to_bits(f_inv_p),
'h': poly_to_bits(h)
}
def ntru_encrypt(message, params, h, secret_generator=secrets.SystemRandom()):
msg_poly = msgtext_to_msgpoly(message, params['n'], params['p'])
msg_poly.lift()
msg_poly.set_coeff_mod(params['q'])
r = generate_random_polynomial(params['n'], ones=params['d_r'], minus_ones=params['d_r'], secret_generator=secret_generator)
r.set_coeff_mod(params['q'])
e = bits_to_poly(h, params['n'], params['q']) * r + msg_poly
return poly_to_bits(e)
def ntru_decrypt(encrypted_message, params, key_info):
a = bits_to_poly(key_info['f'], params['n'], params['q']) * bits_to_poly(encrypted_message, params['n'], params['q'])
a.lift()
a.set_coeff_mod(params['p'])
m = bits_to_poly(key_info['f_inv_p'], params['n'], params['p']) * a
return msgpoly_to_msgtext(m)
def test_expr_equality(test_cases):
"""test the equality of the value of a bunch of expressions; input taken in the form
[
(test_expr1, expected_result1),
.
.
.
(test_exprN, expected_resultN)
]
note that the expressions should be strings (or convertible to string),
as they will be executed with eval, and then compared via __eq__"""
successcount = 0
for i in range(len(test_cases)):
result = eval(str(test_cases[i][0]))
expected_result = eval(str(test_cases[i][1]))
if result != expected_result:
print('test %d FAILED!\nexpression "%s"\nyielded value "%s"\nbut we expected value"%s"\n'
% (i, test_cases[i][0], repr(result), repr(expected_result)))
else:
print('test %d PASSED:\nexpression "%s"\nyielded value "%s"\nwhich is what we expected\n'
% (i, test_cases[i][0], repr(result)))
successcount += 1
print('%d out of %d tests passed\n\n' % (successcount, len(test_cases)))
def test_ntru(param_sets, messages):
rand_gen = random.Random(42) # seeded generator for testing
passed = 0; failed = 0
for params in param_sets:
print('testing the parameter set %s\n' % params)
key_info = ntru_keygen(params, rand_gen)
print('take note that \n',
'f = %s\n' % bits_to_poly(key_info['f'], params['n'], params['q']),
'f_inv_q = %s\n' % bits_to_poly(key_info['f_inv_q'], params['n'], params['q']),
'f_inv_p = %s\n' % bits_to_poly(key_info['f_inv_p'], params['n'], params['p']),
'g = %s\n' % bits_to_poly(key_info['g'], params['n'], params['q']),
'h = %s\n' % bits_to_poly(key_info['h'], params['n'], params['q']),
'are the polynomials of the generated key pair\n',
'and\n',
'f = %s\n' % key_info['f'],
'f_inv_q = %s\n' % key_info['f_inv_q'],
'f_inv_p = %s\n' % key_info['f_inv_p'],
'g = %s\n' % key_info['g'],
'h = %s\n' % key_info['h'],
'are the raw encoded bits',
sep='')
for msg in messages:
msg_bytes = bytearray(msg.encode(encoding='utf-8'))
print('testing the message "%s" of length %d bytes\n' % (msg, len(msg_bytes)))
e = ntru_encrypt(msg, params, key_info['h'], rand_gen)
print('take note that the encrypted message is encoded as the polynomial %s\n'
% bits_to_poly(e, params['n'], params['q']),
'and\n',
'%s\n' % e,
'are the raw bytes to transmitted\n',
sep='')
try:
m = ntru_decrypt(e, params, key_info)
except decryption_failure as de:
print('failed to decrypt due to %s, %s\n' % (e.args, e))
print('FAILED')
failed += 1
continue
print('the decrypted message is %s\n' % m)
if m == msg:
print('PASSED')
passed += 1
else:
print('FAILED')
failed += 1
print('results:\npassed %d tests, failed %d' % (passed, failed))
def test_extended_euclidean_algorithm(arglist):
successcount = 0; i = 0
for a, b, correct_g in arglist:
x, y, g = extended_euclidean_algorithm(a, b)
if a * x + b * y != g or g != correct_g:
print('\nFAILED test %d: extended_euclid(%d, %d) returned x = %d, y = %d, g = %d\n'
'where %d * %d + %d * %d = %d, and expected gcd was %d\n'
% (i, a, b, x, y, g, a, x, b, y, g, correct_g))
else:
print('\nPASSED test %d: extended_euclid(%d, %d) returned x = %d, y = %d, g = %d\n'
'where %d * %d + %d * %d = %d, and expected gcd was %d\n'
% (i, a, b, x, y, g, a, x, b, y, g, correct_g))
successcount += 1
i += 1
print('%d out of %d tests passed\n\n' % (successcount, len(arglist)))
def test_poly_extended_euclidean_algorithm(arglist):
successcount = 0; i = 0
for a, b, correct_g in arglist:
x, y, g = conv_poly.poly_extended_euclidean_algorithm(a, b)
if a * x + b * y != g or conv_poly.make_monic(g) != conv_poly.make_monic(correct_g):
print('\nFAILED test %d: poly_extended_extended_euclid(%s, %s) returned x = (%s), y = (%s), g = (%s)\n'
'where (%s) * (%s) + (%s) * (%s) = (%s), and expected gcd was (%s)\n'
% (i, a, b, x, y, g, a, x, b, y, a*x + b*y, correct_g))
else:
print('\nPASSED test %d: poly_extended_extended_euclid(%s, %s) returned x = (%s), y = (%s), g = (%s)\n'
'where (%s) * (%s) + (%s) * (%s) = (%s), and expected gcd was (%s)\n'
% (i, a, b, x, y, g, a, x, b, y, g, correct_g))
successcount += 1
i += 1
print('%d out of %d tests passed\n\n' % (successcount, len(arglist)))
def run_unit_tests():
test_extended_euclidean_algorithm(
# each test case has format: (a, b, gcd(a, b))
[(16, 4, 4), (12, 8, 4), (-12, 8, 4), (1000000007, 15, 1),
(-1, -13, 1)]
)
test_poly_extended_euclidean_algorithm(
# each test case has format: (a, b, gcd(a, b))
[(conv_poly(polynomial='x + 4', p=1000000007, n=107) * conv_poly(polynomial='x + 7', p=1000000007, n=107) * conv_poly(polynomial='x + 4', p=1000000007, n=107),
conv_poly(polynomial='x + 5', p=1000000007, n=107) * conv_poly(polynomial='x + 7', p=1000000007, n=107) * conv_poly(polynomial='x + 4', p=1000000007, n=107),
conv_poly(polynomial='x + 4', p=1000000007, n=107) * conv_poly(polynomial='x + 7', p=1000000007, n=107))]
)
poly_extended_euclidean_algorithm_test_cases = [
("conv_poly.poly_extended_euclidean_algorithm(conv_poly(polynomial='x + 4', p=1000000007, n=107) * conv_poly(polynomial='x + 7', p=1000000007, n=107) * conv_poly(polynomial='x + 4', p=1000000007, n=107), "
"conv_poly(polynomial='x + 5', p=1000000007, n=107) * conv_poly(polynomial='x + 7', p=1000000007, n=107) * conv_poly(polynomial='x + 4', p=1000000007, n=107))[2].make_monic()",
"conv_poly(polynomial='x + 4', p=1000000007, n=107) * conv_poly(polynomial='x + 7', p=1000000007, n=107)")
]
test_expr_equality(poly_extended_euclidean_algorithm_test_cases)
poly_test_cases = [
("conv_poly(polynomial='x^2 + x', p=2, n=107) + conv_poly(polynomial='x + 1', p=2, n=107)",
"conv_poly(polynomial='x^2 + 1', p=2, n=107)"),
]
test_expr_equality(poly_test_cases)
test_ntru([
# parameter sets specified in the IEEE STD 1363.1-2008, "public key cryptography based on hard lattice problems"
# note: q = b^k
# optimized for "size".
{'param_set': 'ees401ep1', 'n': 401, 'p': 3, 'q': 2048, 'prime_factor_q': 2, 'd_f': 113, 'd_g': 133, 'd_r': 113}, # 112-bit security level
{'param_set': 'ees449ep1', 'n': 449, 'p': 3, 'q': 2048, 'prime_factor_q': 2, 'd_f': 134, 'd_g': 149, 'd_r': 134}, # 128-bit security level
{'param_set': 'ees677ep1', 'n': 677, 'p': 3, 'q': 2048, 'prime_factor_q': 2, 'd_f': 157, 'd_g': 225, 'd_r': 157}, # 192-bit security level
{'param_set': 'ees1087ep2', 'n': 1087, 'p': 3, 'q': 2048, 'prime_factor_q': 2, 'd_f': 120, 'd_g': 362, 'd_r': 120}, # 256-bit security level
# optimized for "cost", defined as running_time^2 * size.
{'param_set': 'ees541ep1', 'n': 541, 'p': 3, 'q': 2048, 'prime_factor_q': 2, 'd_f': 49, 'd_g': 180, 'd_r': 49}, # 112-bit decurity level
{'param_set': 'ees613ep1', 'n': 613, 'p': 3, 'q': 2048, 'prime_factor_q': 2, 'd_f': 55, 'd_g': 204, 'd_r': 55}, # 128-bit security level
{'param_set': 'ees887ep1', 'n': 887, 'p': 3, 'q': 2048, 'prime_factor_q': 2, 'd_f': 81, 'd_g': 295, 'd_r': 81}, # 192-bit security level
{'param_set': 'ees1171ep1', 'n': 1171, 'p': 3, 'q': 2048, 'prime_factor_q': 2, 'd_f': 106, 'd_g': 390, 'd_r': 106}, # 256-bit security level
# optimized for running time
{'param_set': 'ees659ep1', 'n': 659, 'p': 3, 'q': 2048, 'prime_factor_q': 2, 'd_f': 38, 'd_g': 219, 'd_r': 38}, # 112-bit decurity level
{'param_set': 'ees761ep1', 'n': 761, 'p': 3, 'q': 2048, 'prime_factor_q': 2, 'd_f': 42, 'd_g': 253, 'd_r': 42}, # 128-bit security level
{'param_set': 'ees1087ep1', 'n': 1087, 'p': 3, 'q': 2048, 'prime_factor_q': 2, 'd_f': 63, 'd_g': 362, 'd_r': 63}, # 192-bit security level
{'param_set': 'ees1499ep1', 'n': 1499, 'p': 3, 'q': 2048, 'prime_factor_q': 2, 'd_f': 79, 'd_g': 499, 'd_r': 79}, # 256-bit security level
],
[
'mc938-2s2017',
'oi',
'tchau',
'99 bottles',
'g4389hg8hg',
'cryptobunda'
]
)
if __name__ == '__main__':
#import ipdb
#ipdb.set_trace()
run_unit_tests()
while 1:
print('enter a line with a message to see it encrypted and decrypted. enter an empty line to quit')
msg = sys.stdin.readline()
if msg == '':
break
test_ntru([{'param_set': 'ees761ep1', 'n': 761, 'p': 3, 'q': 2048, 'prime_factor_q': 2, 'd_f': 42, 'd_g': 253, 'd_r': 42}], # 128-bit security level
[msg])
| true
|
ba1af6eab9b9926669b68beacad631a68be6ec16
|
Python
|
daviddwlee84/LeetCode
|
/Contest/LeetCodeWeeklyContest/WeeklyContest334/3/Sorted3.py
|
UTF-8
| 581
| 2.78125
| 3
|
[] |
no_license
|
from typing import List
class Solution:
def maxNumOfMarkedIndices(self, nums: List[int]) -> int:
nums.sort()
double_nums = [num * 2 for num in nums]
left = len(nums) - 1
right = len(nums) - 1
while double_nums[left] > nums[right]:
left -= 1
right_end = left
temp = 2
while left >= 0 and right > right_end:
if double_nums[left] <= nums[right]:
answer += temp
temp = 0
else:
left -= 1
# Not finished
| true
|
5ea8d6b5ab68f791cb948ebea915f2ec9369ab12
|
Python
|
l-henri/gan-movie-maker
|
/ganMovieMaker.py
|
UTF-8
| 2,235
| 2.546875
| 3
|
[] |
no_license
|
import sys
sys.path.append('./gantools/gantools')
import cli as ganBreederCli
import os
import shutil
import ffmpeg
import json
movieFrameRate = 5
workdir = "output/01_test_global"
outputVideo = "output/test.mp4"
if not os.path.exists(workdir):
os.makedirs(workdir)
########
# An image is caracterized by a vector, labels and a truncation value
########
def main():
print("Starting program")
keysList = ["1664c75e5b4856155775f062", "9556db302ee5a7b2c04907ea"]
durations = [1, 1]
# Calculating frame number from transition duration
frameNumberPerDuration=[]
for duration in durations:
frameNumberPerDuration.append(int(movieFrameRate*duration))
folderNames = []
secretData = loadSecretData()
arguments = ["-u%s" % secretData["username"], "-p%s" % secretData["password"], "--no-loop", "-o"+workdir]
i = 0
# Appel de la fonction sur chaque objet
for key in keysList:
# Creating arguments
# print(frameNumberPerDuration[i])
if i == len(keysList)-1:
# arguments.append("-k '" + key + "' '" + keysList[0] + "'")
arguments.append("-k" + key )
arguments.append("-l" + keysList[0])
arguments.append("-n"+str(frameNumberPerDuration[i]))
# arguments.append("-o"+folderNames[i])
else:
# arguments.append("-k" + key + " " + keysList[i+1])
arguments.append("-k" + key )
arguments.append("-l" + keysList[i+1])
arguments.append("-n"+str(frameNumberPerDuration[i]))
# arguments = ["-o outpout", "-uhenri.lieutaud@gmail.com", "-pAB6hzKSXYBf7", "-k" + key , "-l" + keysList[i+1]]
# arguments.append("-o"+folderNames[i])
arguments.append("-P"+ str(i).zfill(4))
i += 1
# print(arguments)
# # Vérification des arguments
# args = ganBreederCli.handle_args(arguments)
# print(args)
# Appel de la fonction principale
ganBreederCli.main(arguments)
## Saving as movie
stream = ffmpeg.input(workdir+ '/*.png', pattern_type='glob', framerate=movieFrameRate)
#stream = ffmpeg.framerate(24)
stream = ffmpeg.output(stream, outputVideo)
ffmpeg.run(stream)
# ffmpeg
# .input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25)
# .output('movie.mp4')
# .run()
def loadSecretData():
with open("secretData.json") as json_file:
return json.load(json_file)
if __name__ == '__main__':
main()
| true
|
3642063494aa7e39f65b69007a491d1eff2eb925
|
Python
|
roberzguerra/rover
|
/events/auth.py
|
UTF-8
| 446
| 2.515625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
# -*- coding:utf-8 -*-
from django.contrib.auth.decorators import permission_required
def events_permission_required(perm, login_url='/admin/login', raise_exception=False):
"""
Sobrescreve o metodo que exige login para acessar a view
Usar com decorator sobre o metodo que desejar o login:
@method_decorator(events_login_required)
"""
return permission_required(perm, login_url=login_url, raise_exception=raise_exception)
| true
|
e452873f6304a88a7f6c28ac4a5a3deeb6627f51
|
Python
|
NoahViste/Chronon
|
/levels.py
|
UTF-8
| 1,813
| 2.8125
| 3
|
[] |
no_license
|
from tiles import Tile
from textures import Texture
from matrix import Grid
from settings import *
import os
def exporter(grid, name):
with open(name, "w+") as file:
file.write("{0},{1}\n".format(grid.width, grid.height))
for tile in grid.all():
file.write("|,{0}\n".format(int(tile[2].collision)))
for image in tile[2].image:
file.write("{0},{1}\n".format(image.name, image.position))
file.write("/\n")
def importer(name, texture_size):
with open(name, "r") as file:
lines = file.readlines()
size = lines[0].split(",")
size = int(size[0]), int(size[1])
grid = Grid(size)
useless = None
collision = False
x, y = 0, 0
state = "new"
for line in lines[1:]:
if "/" in line:
state = "new"
x += 1
if x >= size[0]:
y += 1
x = 0
continue
if "|" in line:
useless, collision = line.split(",")
continue
if state == "new":
texture, position = line.split(",")
tile = Tile(Texture(texture, int(position), texture_size))
tile.collision = bool(int(collision))
grid.put(x, y, tile)
state = "added"
continue
if state == "added":
texture, position = line.split(",")
grid.get(x, y).add(Texture(texture, int(position), texture_size))
return grid
def list_all(folder):
all_files = os.listdir(folder)
filtered_files = []
for file in all_files:
if G.MAP_EXTENSION in file:
filtered_files.append(file)
return filtered_files
| true
|
0630767b2c23d71a4cd35d7fabf8c860f9c07359
|
Python
|
ivanserendipity/SVM-on-iris
|
/SVM_iris.py
|
UTF-8
| 708
| 2.65625
| 3
|
[] |
no_license
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 12 19:24:50 2017
@author: Serendipity
"""
import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.cross_validation import train_test_split
from sklearn import svm
from sklearn import metrics
iris = datasets.load_iris()
X = iris.data
Y = iris.target
Y = Y.reshape(150,1)
data = np.hstack((X,Y))
train,test = train_test_split(data,test_size = 0.1)
train_X = train[:,0:4]
train_Y = train[:,4]
test_X = test[:,0:4]
test_Y = test[:,4]
model = svm.SVC()
model.fit(train_X,train_Y)
prediction = model.predict(test_X)
accuracy = metrics.accuracy_score(prediction,test_Y)
print 'The accuracy is %f' %accuracy
| true
|
e36e5841261dd929d9f952f24d97f0fd3b5290b5
|
Python
|
DivineJK/Colorful_QM_Program
|
/Spin_Synthesizer.py
|
UTF-8
| 16,743
| 3.015625
| 3
|
[] |
no_license
|
# issquare
# bit_digits, issquare
def bit_digits(n):
tmp = n
cnt = 0
while tmp:
tmp >>= 1
cnt += 1
return cnt
def issquare(n: int):
l, r = 0, n + 1
d = (l + r) // 2
cnt = bit_digits(n+1)
for _ in range(cnt + 1):
if d * d <= n:
l = d
d = (l + r) // 2
else:
r = d
d = (l + r) // 2
return d
# integer operation
# gcd, factorization
def gcd(a, b):
k, l = a, b
while l:
k, l = l, k % l
return k
def factorization(n):
D = {}
p = 2
a = n
while a != 1:
cnt = 0
while a % p == 0:
cnt += 1
a //= p
if cnt:
D[p] = cnt
p += 1
if p * p > n and a != 1:
D[a] = 1
break
return D
# fraction operation
# frac_sum, frac_prod, fracted
def frac_sum(f1, f2, sign=1): # f1[0] / f1[1] + sign * f2[0] / f2[1]
f = [f1[0]*f2[1]+sign*f1[1]*f2[0], f1[1]*f2[1]]
g = gcd(f[0], f[1])
f[0] //= g
f[1] //= g
return f
def frac_prod(f1, f2): # (f1[0] / f1[1]) * (f2[0] / f2[1])
f = [f1[0]*f2[0], f1[1]*f2[1]]
g = gcd(f[0], f[1])
f[0] //= g
f[1] //= g
return f
def fracted(f):
g = gcd(f[0], f[1])
a = f[0] // g
b = f[1] // g
return [a, b]
# sqrt operation
# sqrt_sum, parse_sqrt, sqrt_prod, sqrt_frac, parse_number
# ----- note: 0 is {}, so DO NOT use 0 as sqrt dictionary's key. -----
def sqrt_sum(d1, d2, sign = 1): #d = {s1: c1, s2: c2, ...} => c1*sqrt(s1) + c2*sqrt(s2) + ...
dres = {i: d1[i][:] for i in d1}
for i in d2:
if i in d1:
dres[i] = frac_sum(dres[i][:], frac_prod([sign, 1], d2[i]))
else:
dres[i] = frac_prod([sign, 1], d2[i])
real_dres = {}
for i in dres:
if dres[i][0]:
real_dres[i] = dres[i][:]
return real_dres
def parse_sqrt(n: int): # n -> sqrt(n)
sign = 1
if n < 0:
sign = -1
n = -n
D = factorization(n)
coeff = 1
res = 1
for i in D:
coeff *= i ** (D[i] // 2)
res *= i * (D[i] % 2) + 1 * (1 - D[i] % 2)
return {sign * res: [coeff, 1]}
def sqrt_prod(d1, d2): # d1 * d2
dres = {}
for i in d1:
for j in d2:
coeff = frac_prod(d1[i], d2[j])
res = i * j
if i < 0 and j < 0:
coeff[0] *= -1
light_d = parse_sqrt(res)
light_L = [[i, light_d[i]] for i in light_d]
coeff = frac_prod(coeff, light_L[0][1])
res = light_L[0][0]
if res in dres:
dres[res] = frac_sum(dres[res][:], coeff)
else:
dres[res] = coeff[:]
dres2 = {}
for i in dres:
if dres[i][0]: dres2[i] = dres[i][:]
return dres2
def sqrt_frac(d1, d2): # d1 / d2
upper = {}
downer = {}
for i in d1:
if d1[i][0]: upper[i] = d1[i][:]
for i in d2:
if d2[i][0]: downer[i] = d2[i][:]
if downer == {}:
raise ZeroDivisionError("division by zero")
while len(downer) != 1 or 1 not in downer:
conj_d2 = {}
left = {}
right = {}
k = 0
for j in downer:
if j != 1 and k == 0:
k = j
for j in downer:
if j % k == 0:
right[j] = downer[j][:]
conj_d2[j] = frac_prod([-1, 1], downer[j][:])
else:
left[j] = downer[j][:]
conj_d2[j] = downer[j][:]
left = sqrt_prod(left, left)
right = sqrt_prod(right, right)
downer = sqrt_sum(left, right, -1)
upper = sqrt_prod(upper, conj_d2)
res = {}
for i in upper:
res[i] = frac_prod(upper[i][:], [downer[1][1], downer[1][0]])
return res
def parse_number(d1: dict):
res = 0
for i in d1:
res += d1[i][0] * i**(0.5) / d1[i][1]
return res
# matrix operation
# kronecker_product, mat_sum, mat_prod, identity_matrix
def kronecker_product(mat1, mat2):
n1, m1 = len(mat1), len(mat1[0])
n2, m2 = len(mat2), len(mat2[0])
res = [[{} for _ in range(m1*m2)] for __ in range(n1*n2)]
for i in range(n2*n1):
for j in range(m1*m2):
res[i][j] = sqrt_prod(mat1[i//n2][j//m2], mat2[i%n2][j%m2])
return res
def mat_sum(mat1, mat2, sign=1):
n1, m1 = len(mat1), len(mat1[0])
n2, m2 = len(mat2), len(mat2[0])
if n1 != n2 or m1 != m2:
raise ValueError("matrix size is invalid")
res = [[{} for _ in range(m1)] for __ in range(n1)]
for i in range(n1):
for j in range(m1):
res[i][j] = sqrt_sum(mat1[i][j], mat2[i][j], sign)
return res
def mat_prod(mat1, mat2):
n1, m1 = len(mat1), len(mat1[0])
n2, m2 = len(mat2), len(mat2[0])
if m1 != n2:
raise ValueError("matrix size is invalid")
res = [[{} for _ in range(m2)] for __ in range(n1)]
for i in range(n1):
for j in range(m2):
S = {}
for k in range(m1):
S = sqrt_sum(S, sqrt_prod(mat1[i][k], mat2[k][j]))
res[i][j] = S
return res
def identity_matrix(matrix_size):
res = [[{} for _ in range(matrix_size)] for __ in range(matrix_size)]
for i in range(matrix_size):
res[i][i] = {1: [1, 1]}
return res
# vector operator
def inner_product(vec1, vec2):
n = len(vec1)
m = len(vec2)
res = {}
if n != m:
raise ValueError("vector length is invalid")
for i in range(n):
res = sqrt_sum(res, sqrt_prod(vec1[i], vec2[i]))
return res
def narrow_normalization(vec):
n = len(vec)
res = [vec[i] for i in range(n)]
norm = inner_product(vec, vec)
if norm == {}:
raise ValueError("zero-vector cannot be normalize")
else:
norm = sqrt_frac(parse_sqrt(norm[1][0]), parse_sqrt(norm[1][1]))
for i in range(n):
res[i] = sqrt_frac(res[i], norm)
return res
def scalar_multiplication(c, vec):
n = len(vec)
res = [sqrt_prod(vec[i], c) for i in range(n)]
return res
def vec_sum(vec1, vec2, sign=1):
n = len(vec1)
m = len(vec2)
if n != m:
raise ValueError("invalid vectors")
res = [sqrt_sum(vec1[i], vec2[i], sign) for i in range(n)]
return res
def normalization(vec):
n = len(vec)
norm = 0
for i in range(n):
norm += vec[i]*vec[i]
if norm:
norm = norm**0.5
return [vec[i] / norm for i in range(n)]
else:
raise ValueError("zero-vector cannot be normalize.")
def gramm_schmidt(vecs):
vec_num = len(vecs)
dim_flg = True
for i in range(vec_num-1):
dim_flg *= (len(vecs[i]) == len(vecs[i+1]))
if not dim_flg:
raise ValueError("invalid vectors")
vec_dim = len(vecs[0])
res = [[vecs[i][j] for j in range(vec_dim)] for i in range(vec_num)]
for i in range(vec_num):
for j in range(i):
res[i] = vec_sum(res[i], scalar_multiplication(inner_product(vecs[i], res[j]), res[j]), -1)
res[i] = narrow_normalization(res[i])
return res
# equation solver
# quadratic_equation_int, quadratic_equation_float
def quadratic_equation_int(a: int, b: int, c: int):
if a == 0:
if b == 0:
if c == 0:
return "any number"
return "no solution"
return [{1: frac_sum([0, 1], [-c, b])}]
x = parse_sqrt(b*b - 4*a*c)
y = {}
if b:
y[1] = [-b, 1]
x1 = sqrt_sum(y, x)
x2 = sqrt_sum(y, x, -1)
for i in x1:
x1[i][1] *= 2*a
x1[i] = frac_prod([1, 1], x1[i])
for i in x2:
x2[i][1] *= 2*a
x2[i] = frac_prod([1, 1], x2[i])
return [x1, x2]
def quadratic_equation_float(a, b, c):
if a == 0:
if b == 0:
if c == 0:
return "any number"
return "no solution"
return [-c / b]
x = (b*b - 4*a*c) ** 0.5
y = -b
return [(y + x) / (2*a), (y - x) / (2*a)]
def linear_equation(mat, vec): # type == dict; key: "solution", "subsolution"
n, m = len(mat), len(mat[0])
nv = len(vec)
ext_mat = [[{} for _ in range(m+1)] for __ in range(n)]
if n != nv:
raise ValueError("invalid equation, and there is no solution")
for i in range(n):
for j in range(m):
ext_mat[i][j] = mat[i][j]
for i in range(n):
ext_mat[i][m] = vec[i]
pnt = 0
for i in range(m+1):
row_pnt = pnt
flg = False
while row_pnt < n:
if ext_mat[row_pnt][i] == {}:
row_pnt += 1
else:
flg = True
break
if flg:
for j in range(m+1):
ext_mat[pnt][j], ext_mat[row_pnt][j] = ext_mat[row_pnt][j], ext_mat[pnt][j]
keep = ext_mat[pnt][i]
for j in range(m+1):
ext_mat[pnt][j] = sqrt_frac(ext_mat[pnt][j], keep)
for j in range(pnt+1, n):
raw_keep = ext_mat[j][i]
for k in range(m+1):
ext_mat[j][k] = sqrt_sum(ext_mat[j][k], sqrt_prod(raw_keep, ext_mat[pnt][k]), -1)
pnt += 1
flg = True
for i in range(n):
fflg = True
for j in range(m):
if ext_mat[i][j] != {}:
fflg = False
if fflg and ext_mat[i][m] != {}:
flg = False
if flg:
for i in range(n, 0, -1):
pnt = 0
fflg = False
while pnt <= m:
if ext_mat[i-1][pnt] == {}:
pnt += 1
else:
fflg = True
break
if fflg:
keep = ext_mat[i-1][pnt]
for j in range(i-1):
raw_keep = ext_mat[j][pnt]
for k in range(m+1):
ext_mat[j][k] = sqrt_sum(ext_mat[j][k], sqrt_prod(raw_keep, ext_mat[i-1][k]), -1)
chk = [-1 for _ in range(m)]
D = {}
cnt = 0
for i in range(n):
for j in range(m):
if ext_mat[i][j] != {}:
chk[j] = i
D[i] = j
cnt += 1
break
solution = {"solution": [{} for _ in range(m)], "subspace": [[{} for _ in range(m)] for __ in range(n-cnt)]}
pos = 0
for i in range(m):
if chk[i] == -1:
solution["subspace"][pos][i] = {1: [1, 1]}
for k in D:
solution["subspace"][pos][D[k]] = sqrt_prod({1: [-1, 1]}, ext_mat[k][i])
pos += 1
else:
solution["solution"][i] = ext_mat[chk[i]][m]
for i in range(n-cnt):
keep = {}
for j in range(m):
keep = sqrt_sum(sqrt_prod(solution["subspace"][i][j], solution["subspace"][i][j]), keep)
keep = sqrt_frac(parse_sqrt(keep[1][0]), parse_sqrt(keep[1][1]))
for j in range(m):
solution["subspace"][i][j] = sqrt_frac(solution["subspace"][i][j], keep)
return solution
return "no solution"
# angular momentum algebra
# updown_operator, momentum_x, momentum_y, momentum_z, momentum_synthesis
# J_x = (J_+ + J_-) / 2
# J_y = (J_+ - J_-) / 2i
# J^2 = (J_+J_- + J_+J_-) / 2 + J_z^2
def updown_operator(n, op):
res = [[{} for _ in range(n)] for __ in range(n)]
if op == "upper":
for i in range(n-1):
res[i][i+1] = parse_sqrt((i+1)*(n-i-1))
return res
elif op == "lower":
for i in range(n-1):
res[i+1][i] = parse_sqrt((i+1)*(n-i-1))
return res
else:
raise ValueError("operator valuable (2nd valuable) is not correct. it must be 'upper' or 'lower'.")
def momentum_x(n):
upper = updown_operator(n, "upper")
lower = updown_operator(n, "lower")
res = mat_sum(upper, lower)
for i in range(n):
for j in range(n):
res[i][j] = sqrt_prod(res[i][j], {1: [1, 2]})
return res
def momentum_y(n):
upper = updown_operator(n, "upper")
lower = updown_operator(n, "lower")
res = mat_sum(upper, lower, -1)
for i in range(n):
for j in range(n):
res[i][j] = sqrt_prod(res[i][j], {-1: [-1, 2]})
return res
def momentum_z(n):
val = fracted([n-1, 2])
res = [[{} for _ in range(n)] for __ in range(n)]
for i in range(n):
if val[0]: res[i][i] = {1: val[:]}
val = frac_sum(val, [1, 1], -1)
return res
def momentum_synthesis(n, m): #J_1 + J_2, dim(J_1) = n, dim(J_2) = m
left_x = kronecker_product(momentum_x(n), identity_matrix(m))
left_y = kronecker_product(momentum_y(n), identity_matrix(m))
left_z = kronecker_product(momentum_z(n), identity_matrix(m))
right_x = kronecker_product(identity_matrix(n), momentum_x(m))
right_y = kronecker_product(identity_matrix(n), momentum_y(m))
right_z = kronecker_product(identity_matrix(n), momentum_z(m))
synth_x = mat_sum(left_x, right_x)
synth_y = mat_sum(left_y, right_y)
synth_z = mat_sum(left_z, right_z)
synth_x = mat_prod(synth_x, synth_x)
synth_y = mat_prod(synth_y, synth_y)
synth_z = mat_prod(synth_z, synth_z)
res = [[{} for __ in range(n*m)] for _ in range(n*m)]
res = mat_sum(res, synth_x)
res = mat_sum(res, synth_y)
res = mat_sum(res, synth_z)
return res
# test input / output
N = int(input()) # <- number of spins
A = list(map(int, input().split())) # <- sizes of spins' matrix (0 -> 1, 1/2 -> 2, ...)
dim = 1
ms = [[[[{1: [1, 1]}]] for __ in range(3)] for _ in range(N)]
for i in range(N):
dim *= A[i]
for j in range(N):
if i == j:
ms[j][0] = kronecker_product(ms[j][0], momentum_x(A[i]))
ms[j][1] = kronecker_product(ms[j][1], momentum_y(A[i]))
ms[j][2] = kronecker_product(ms[j][2], momentum_z(A[i]))
else:
for k in range(3):
ms[j][k] = kronecker_product(ms[j][k], identity_matrix(A[i]))
msx = [[{} for _ in range(dim)] for __ in range(dim)]
msy = [[{} for _ in range(dim)] for __ in range(dim)]
msz = [[{} for _ in range(dim)] for __ in range(dim)]
for i in range(N):
msx = mat_sum(msx, ms[i][0])
msy = mat_sum(msy, ms[i][1])
msz = mat_sum(msz, ms[i][2])
mssz = [[{} for _ in range(dim)] for __ in range(dim)]
for i in range(dim):
for j in range(dim):
mssz[i][j] = msz[i][j]
msx = mat_prod(msx, msx)
msy = mat_prod(msy, msy)
msz = mat_prod(msz, msz)
mss = mat_sum(msx, msy)
mss = mat_sum(mss, msz)
spin_size = sum(A) - N
zeros = [{} for _ in range(dim)]
for i in range(spin_size, -1, -2):
SS = {}
if i:
SS = {1: fracted([i*(i+2), 4])}
tmps = [[{} for __ in range(dim)] for _ in range(dim)]
for j in range(dim):
for k in range(dim):
tmps[j][k] = mss[j][k]
if j == k:
tmps[j][k] = sqrt_sum(tmps[j][k], SS, -1)
sol = linear_equation(tmps, zeros)
sstr = ""
if i % 2:
sstr = str(i) + "/" + str(2)
else:
sstr = str(i//2)
if sol["subspace"] != {}:
dictM = {}
for j in sol["subspace"]:
vec = [j[k] for k in range(dim)]
nve = [{} for _ in range(dim)]
for k in range(dim):
SSS = {}
for l in range(dim):
SSS = sqrt_sum(SSS, sqrt_prod(vec[l], mssz[k][l]))
nve[k] = SSS
MM = {}
for k in range(dim):
MM = sqrt_sum(MM, sqrt_prod(vec[k], nve[k]))
mstr = ""
if MM == {}:
mstr = "0"
else:
if MM[1][1] == 1:
mstr = str(MM[1][0])
else:
mstr = str(MM[1][0]) + "/" + str(MM[1][1])
if mstr in dictM:
dictM[mstr][0] += 1
dictM[mstr].append(j)
else:
dictM[mstr] = [1, j[:]]
for j in dictM:
z = gramm_schmidt(dictM[j][1:])
for k in range(dictM[j][0]):
print("|S = {}, M = {}, cnt = {}> =".format(sstr, j, k+1), end = ' ')
ccnt = 0
for l in range(dim):
if z[k][l] != {}:
tmpk = l
tmpt = [0 for _ in range(N)]
for m in range(N, 0, -1):
tmpt[m-1] = tmpk % A[m-1]
tmpk //= A[m-1]
if ccnt:
print(" +", end = '')
print(z[k][l], end = '')
for m in range(N):
print("|{}>".format(tmpt[m]), end = '')
ccnt += 1
print()
| true
|
bfff55e694c7ac494f1b79064bf9a8c8a423769d
|
Python
|
deepakdeedar/translator
|
/Translator/turtle.py
|
UTF-8
| 116
| 2.8125
| 3
|
[] |
no_license
|
from turtle import Turtle, Screen
timmy = Turtle()
timmy.shape("turtle")
timmy.color("coral")
my_screen = Screen()
| true
|
4e97199dc4908ce6d98a2df7a4a9b3b60ac9b296
|
Python
|
Valerii9123/Python111
|
/Lessons5/random_gen.py
|
UTF-8
| 276
| 3.140625
| 3
|
[] |
no_license
|
import random
# randrange
for _ in range(15):
print(random.randrange(1, 10 , 1), end=', ')
print()
# randint
for _ in range(15):
print(random.redint(1, 10), end=', ')
print()
# random
for _ in range(15):
print(random.random(1, 10), end=', ')
print()
# uniform
| true
|
eaec74c4849283fe1934825624484630db7a4473
|
Python
|
surajshrestha-0/python-Basic-II
|
/Question3.py
|
UTF-8
| 822
| 4.34375
| 4
|
[] |
no_license
|
"""
Write code that will print out the anagrams (words that use the same letters) from a paragraph of text.
"""
from collections import defaultdict
def anagramsWord(input_paragraph):
words = list(set(input_paragraph.split()))
grouped_words = defaultdict(list)
# Put all anagram words together in a dictionary
# where key is sorted word
for word in words:
grouped_words["".join(sorted(word))].append(word)
for group in grouped_words.values():
# if length of group is greater than 1 than anagram words exist
if len(group) > 1:
print("Anagram words in the given paragraph are as follows : ")
print(" ".join(group))
if __name__ == "__main__":
paragraph = """
A cat was made to act as if it eats a rat.
"""
anagramsWord(paragraph)
| true
|
e2ce552a024dff712e2b568b3daa9bab64eb00f1
|
Python
|
charu11/opencv
|
/demo10.py
|
UTF-8
| 1,271
| 2.78125
| 3
|
[] |
no_license
|
import numpy as np
import cv2 as cv
def val_change(x):
pass;
cv.namedWindow('tracking')
cv.createTrackbar('LH', 'tracking', 0, 255, val_change) # LH- lower hue
cv.createTrackbar('LS', 'tracking', 0, 255, val_change) # LS- lower saturation
cv.createTrackbar('LV', 'tracking', 0, 255, val_change) # LV- lower value
cv.createTrackbar('UH', 'tracking', 255, 255, val_change)
cv.createTrackbar('US', 'tracking', 255, 255, val_change)
cv.createTrackbar('UV', 'tracking', 255, 255, val_change)
while True :
frame = cv.imread('smarties.png')
hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
low_hue = cv.getTrackbarPos('LH', 'tracking')
low_sat = cv.getTrackbarPos('LS', 'tracking')
low_val = cv.getTrackbarPos('LV', 'tracking')
up_hue = cv.getTrackbarPos('UH', 'tracking')
up_sat = cv.getTrackbarPos('US', 'tracking')
up_val = cv.getTrackbarPos('UV', 'tracking')
low_bound = np.array([low_hue, low_sat, low_val])
up_bound = np.array([up_hue, up_sat, up_val])
mask = cv.inRange(hsv, low_bound, up_bound)
res = cv.bitwise_and(frame, frame, mask = mask)
cv.imshow('frame', frame)
cv.imshow('mask', mask)
cv.imshow('res', res)
key = cv.waitKey(1)
if key == 27:
break
cv.destroyAllWindows()
| true
|
c3b56db7f9dbc015436523f3dc52ba32f9889f51
|
Python
|
shark1033/Python-Stepik
|
/list_summ.py
|
UTF-8
| 258
| 2.78125
| 3
|
[] |
no_license
|
for i in range(0,len(s)):
if len(s)==1:
print(s[0])
break
elif i==0:
l.insert(i, s[1]+s[len(s)-1])
elif i==len(s)-1:
l.insert(i, s[0]+s[i-1])
else:
l.insert(i, s[i-1]+s[i+1])
print(l[i], '',end='')
| true
|