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
f093f05a9903def3a5760f3cfa30b11ed524ba3a
Python
Diorski/CP164
/dann4440_l05/src/t04.py
UTF-8
369
2.609375
3
[]
no_license
""" ------------------------------------------------------- [program description] ------------------------------------------------------- Author: Max Dann ID: 190274440 Email: dann4440@mylaurier.ca __updated__ = "2020-02-11" ------------------------------------------------------- """ from functions import to_power base = 2 power = -2 print(to_power(base, power))
true
2a128310a67a5a6ab662942fdcb2df828ea90282
Python
santosh-code/lasso_ridge
/toyota.py
UTF-8
1,362
2.9375
3
[]
no_license
import pandas as pd import matplotlib.pylab as plt import numpy as np toyota=pd.read_csv('C:/Users/USER/Desktop/ToyotaCorolla.csv',encoding= 'unicode_escape') toyota1=toyota.iloc[:,[2,3,6,8,12,13,14,15,16,17]] x=toyota1.iloc[:,1:] y=toyota1.iloc[:,0] from sklearn.linear_model import Lasso lasso=Lasso(alpha=1,normalize=True) lasso.fit(x,y) lasso.coef_ lasso.intercept_ plt.bar(height=pd.Series(lasso.coef_),x=pd.Series(toyota1.columns[1:])) pred_lasso=lasso.predict(x) lasso.score(x,y) np.sqrt(np.mean((pred_lasso-y)**2)) ###### from sklearn.model_selection import GridSearchCV parameters={'alpha':[1e-15,1e-10,1e-8,1e-4,1e-3,1e-2,1,5,10,20]} cv_lasso=GridSearchCV(lasso,parameters,scoring='r2',cv=5) cv_lasso.fit(x,y) cv_lasso.best_params_ cv_lasso.best_score_ ###########ridge_reg from sklearn.linear_model import Ridge ridge=Ridge(alpha=1,normalize=True) ridge.fit(x,y) ridge.coef_ ridge.intercept_ plt.bar(height=pd.Series(ridge.coef_),x=pd.Series(toyota1.columns[1:])) pred_ridge=ridge.predict(x) ridge.score(x,y) np.sqrt(np.mean((pred_ridge-y)**2)) ########optimal lambda value from sklearn.model_selection import GridSearchCV parameters={'alpha':[1e-15,1e-10,1e-8,1e-4,1e-3,1e-2,1,5,10,20]} cv_ridge=GridSearchCV(ridge,parameters,scoring='r2',cv=5) cv_ridge.fit(x,y) cv_lasso.best_params_ cv_lasso.best_score_
true
faf5f44e6baa25e137621ea5a4644f5f5d022090
Python
resgroup/mini-wake
/demo.py
UTF-8
1,376
2.546875
3
[ "MIT" ]
permissive
from miniwake import SingleWake from miniwake.turbine import Turbine from miniwake.turbine import FixedThrustCurve import numpy as np import matplotlib.pyplot as plt upwind_turbine = Turbine(name="T1", x=0.0, y=0.0, hub_height=80.0, diameter=76.0, rotational_speed_rpm=17.0, thrust_curve=FixedThrustCurve(0.4)) upwind_velocity = 9. amient_turbulence_intensity = 0.1 upwind_local_turbulence_intensity = amient_turbulence_intensity single_wake = SingleWake(ambient_turbulence_intensity=amient_turbulence_intensity, upwind_turbine=upwind_turbine, upwind_velocity=upwind_velocity, upwind_local_turbulence_intensity=upwind_local_turbulence_intensity, apply_meander=True) wake = single_wake.calculate(upwind_turbine.diameter * 4.0) x = [] yv = [] yt = [] for normalised_distance in np.linspace(-2.0, 2.0, num=100): distance = normalised_distance * upwind_turbine.diameter x.append(normalised_distance) yv.append(wake.velocity_deficit(lateral_distance=distance)) yt.append(wake.added_turbulence(lateral_distance=distance)) plt.scatter(x, yv, s=20, marker='o') plt.scatter(x, yt, s=20, marker='^') plt.show()
true
91a3e6aa19daa1b647413a8a5a0fa5e8b51552e9
Python
milesmackenzie/dataquest
/step_3/command_line_beginner/Guided Project_ Working With Data Downloads/exploration.py
UTF-8
630
3.109375
3
[]
no_license
# Reading in data and using Series.value_counts() to count # JJ (Juvenile justice facility) and SCH_STATUS_MAGNET (magnet school). # Generating pivot tables for total enrollment by gender for a JJ facility and # magnet school import pandas as pd if __name__ == "__main__": data = pd.read_csv("data/CRDC2013_14.csv", encoding="Latin-1") jj = data["JJ"].value_counts() magnet = data["SCH_STATUS_MAGNET"].value_counts() p1 = pd.pivot_table(data, values=["TOT_ENR_M", "TOT_ENR_F"], index="JJ", aggfunc="sum") p2 = pd.pivot_table(data, values=["TOT_ENR_M", "TOT_ENR_F"], index="SCH_STATUS_MAGNET", aggfunc="sum")
true
858bb2e258474bacb210ca30acf3659ec99d978a
Python
Jhonattanln/Ibov-vs-SPX
/Ibov vs SPX/Ibov_vs_SPX.py
UTF-8
1,167
3.109375
3
[ "MIT" ]
permissive
#### Importando bibliotecas import pandas as pd import matplotlib.pyplot as plt import seaborn as sns ##### Manipulando dados df = pd.read_excel(r'C:\Users\Jhona\OneDrive - Grupo Marista\Clube de Finanças\Clube\Dados\SPX.xlsx', index_col=0, parse_dates=True) df = df.rename(columns={'S&P 500': 'SP_500'}) dados = df[df.IBOV != '-'] dados = dados[dados.SP_500 != '-'] ### Obtendo retornos dados_pct = dados.pct_change().dropna() obsv = len(dados_pct) ### Obtendo retornos iguais obs = dados_pct[dados_pct.IBOV < 0] obs = obs[obs.SP_500 < 0] total = len(obs) print(obsv) print(total) ### Gráfico de correlação por janelas n = 60 roll_correl = dados_pct['IBOV'].rolling(n).corr(dados_pct['SP_500']).dropna() #### Gráfico de correlação plt.style.use('ggplot') fig, ax = plt.subplots() ax.plot(roll_correl.index, roll_correl) ax.set_xlabel('Data') ax.set_ylabel('Correlação') ax.set_title('Correlação IBOV x S&P 500 (janela de ' + str(n) + ' dias)') ax.legend(['Correlação']) plt.show() #### Gráfico seaborn plt.style.use('ggplot') g = sns.JointGrid(data=dados_pct, x='SP_500', y='IBOV') g.plot(sns.regplot, sns.distplot) plt.show()
true
22ff94800140870122a401c7047e2e8caeabaa09
Python
daunjeong824/Practice_Algorithm
/Binary_Search/10816.py
UTF-8
481
3.0625
3
[]
no_license
# https://infinitt.tistory.com/288 # 이분 탐색 => 단일 target일 경우 효율이 좋음! 여러 원소가 존재하고 중복이 있다면 dict 쓰는게 훨씬 효율적!! n = int(input()) cards = list(map(int, input().split())) m = int(input()) find_ = list(map(int, input().split())) dic = dict() for i in cards: try: dic[i] += 1 except: dic[i] = 1 for j in find_: try: print( dic[j],end=' ') except: print(0, end=' ')
true
50955bd03fd509420960d9f422f31d2f49a3b84d
Python
palisadoes/pattoo
/pattoo/db/table/user.py
UTF-8
2,353
2.703125
3
[ "GPL-3.0-only" ]
permissive
#!/usr/bin/env python3 """Pattoo classes querying the User table.""" # Import project libraries from pattoo_shared.constants import MAX_KEYPAIR_LENGTH from pattoo_shared import log from pattoo.db import db from pattoo.db.models import User from pattoo.constants import DbRowUser def idx_exists(idx): """Determine whether primary key exists. Args: idx: idx_user Returns: result: True if exists """ # Initialize key variables result = False rows = [] # Get the result with db.db_query(20096) as session: rows = session.query(User.idx_user).filter( User.idx_user == idx) # Return for _ in rows: result = True break return bool(result) def exists(username): """Determine whether name exists in the User table. Args: username: user name Returns: result: User.idx_user value """ # Initialize key variables result = False rows = [] # Lowercase the name username = username.lower().strip() # Get name from database with db.db_query(20031) as session: rows = session.query(User.idx_user).filter( User.username == username.encode()) # Return for row in rows: result = row.idx_user break return result def insert_row(row): """Create a User table entry. Args: row: DbRowUser object Returns: None """ # Verify values if bool(row) is False or isinstance(row, DbRowUser) is False: log_message = 'Invalid user type being inserted' log.log2die(20070, log_message) # Lowercase the name username = row.username.strip()[:MAX_KEYPAIR_LENGTH] password = row.password[:MAX_KEYPAIR_LENGTH] first_name = row.first_name.strip()[:MAX_KEYPAIR_LENGTH] last_name = row.last_name.strip()[:MAX_KEYPAIR_LENGTH] user_type = int(row.user_type) change_password = int(row.change_password) enabled = int(bool(row.enabled)) # Insert row = User( username=username.encode(), password=password.encode(), first_name=first_name.encode(), last_name=last_name.encode(), user_type=user_type, change_password=change_password, enabled=enabled ) with db.db_modify(20054, die=True) as session: session.add(row)
true
105da253cd151fa220131a182695ff2bac94b740
Python
Librechain/subcrawl
/crawler/storage/console_storage.py
UTF-8
1,655
2.578125
3
[ "MIT" ]
permissive
# © Copyright 2021 HP Development Company, L.P. import json import pprint from re import subn from utils import SubCrawlColors from .default_storage import DefaultStorage class ConsoleStorage(DefaultStorage): cfg = None logger = None def __init__(self, config, logger): self.cfg = config self.logger = logger def load_scraped_domains(self): return [] def store_result(self, result_data): total_urls = 0 print(SubCrawlColors.PURPLE + "\n" + "*" * 25 + " CONSOLE STORAGE - SUMMARY " + "*" * 26 + "\n" + SubCrawlColors.RESET) for domain in result_data: results = dict() total_urls += len(result_data[domain]) for url_content in result_data[domain]: for module in url_content["modules"]: if url_content["modules"][module]: if len(url_content["modules"][module]) > 0: results.setdefault(module, []).append(url_content["modules"][module]) if len(results) > 0: print(SubCrawlColors.CYAN + "<===== " + str(domain) + " =====>"+SubCrawlColors.RESET) for payload_module in results: for result in results[payload_module]: print("\t[" + payload_module + "] " + str(result['matches']) + "( " + result['url'] + " )" + SubCrawlColors.RESET) print("\t\t[SHA256] " + result['hash']) print("") return True
true
c262b1c11bfc781fe05ba3d1f1f277d8a7493d53
Python
ashishlamsal/cryptopals
/set1/challenge5.py
UTF-8
320
3.03125
3
[]
no_license
def repeating_key_xor(key : bytes, input: bytes) -> bytes: return bytes(input[i] ^ key[i % len(key)] for i in range(len(input))) if __name__=='__main__': data = b'''Burning 'em, if you ain't quick and nimble I go crazy when I hear a cymbal''' key = b"ICE" print(repeating_key_xor(key,data).hex())
true
592316ea2b0400a3ac9b83b0d2ddac47e5548366
Python
sohamghosh121/natural-parameter-networks
/npn.py
UTF-8
5,139
2.953125
3
[]
no_license
""" Defines implementation for NPNs """ import torch import numpy as np import torch.nn as nn import torch.optim as O import torch.autograd as autograd import torch.nn.functional as F PI = float(np.pi) ETA_SQ = float(np.pi / 8.0) # for sigmoid ALPHA = float(4.0 - 2.0 * np.sqrt(2)) ALPHA_SQ = float(ALPHA ** 2.0) BETA = - float(np.log(np.sqrt(2) + 1)) # for tanh ALPHA_2 = float(8.0 - 4.0 * np.sqrt(2)) ALPHA_2_SQ = float(ALPHA ** 2.0) BETA_2 = - float(0.5 * np.log(np.sqrt(2) + 1)) def kappa(x, const=1.0, alphasq= 1.0): return 1 / torch.sqrt(const + x * alphasq * ETA_SQ) class GaussianNPNKLDivergence(autograd.Function): """ Implements KL Divergence loss for output layer KL(N(o_m, o_s) || N(y_m, diag(eps)) https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Kullback%E2%80%93Leibler_divergence """ @staticmethod def forward(ctx, o_m, o_s, y, eps): ctx.save_for_backward(o_m, o_s, y) k = torch.Tensor([y.size(1)]) det_ratio = torch.prod(o_s / eps, 1) KL = (torch.sum(o_s/eps, 1) + torch.sum(torch.pow(o_m - y, 2) / eps, 1) - k + torch.log(det_ratio)) * 0.5 return torch.Tensor([torch.mean(KL)]) return torch.mean @staticmethod def backward(ctx, grad_output): raise NotImplementedError() class GaussianNPNLinearLayer(nn.Module): def __init__(self, input_features, output_features): super(GaussianNPNLinearLayer, self).__init__() self.W_m, self.M_s = self.get_init_W(input_features, output_features) self.b_m, self.p_s = self.get_init_b(output_features) def get_init_W(self, _in, _out): # obtained from the original paper W_m = 2 * np.sqrt(6)/ np.sqrt(_in + _out) * (np.random.rand(_in, _out) - 0.5) W_s = 1 * np.sqrt(6)/ np.sqrt(_in + _out) * (np.random.rand(_in, _out)) M_s = np.log(np.exp(W_s) - 1) return nn.Parameter(torch.FloatTensor(W_m)), nn.Parameter(torch.FloatTensor(M_s)) def get_init_b(self, _out): b_m = np.zeros((_out)) # instead of bias_s, parametrize as log(1+exp(pias_s)) p_s = np.exp(-1 * np.ones((_out))) return nn.Parameter(torch.Tensor(b_m)), nn.Parameter(torch.Tensor(p_s)) def forward(self, input): if isinstance(input, tuple): input_m, input_s = input elif isinstance(input, torch.Tensor): input_m = input input_s = autograd.Variable(input.new().zero_()) else: raise ValueError('input was not a tuple or torch.Tensor (%s)' % type(input)) # do this to ensure positivity of W_s, b_s b_s = torch.log(1 + torch.exp(self.p_s)) W_s = torch.log(1 + torch.exp(self.M_s)) o_m = self.b_m + torch.matmul(input_m, self.W_m) o_s = b_s + torch.matmul(input_s, W_s) + \ torch.matmul(input_s, torch.pow(self.W_m, 2)) + \ torch.matmul(torch.pow(input_m, 2), W_s) return o_m, o_s class GaussianNPNNonLinearity(nn.Module): # TODO: does it help to define this in a function instead? def __init__(self, activation): super(GaussianNPNNonLinearity, self).__init__() self.activation = activation def forward(self, o): o_m, o_s = o if self.activation == 'sigmoid': a_m = torch.sigmoid(o_m * kappa(o_s)) a_s = torch.sigmoid(((o_m + BETA) * ALPHA) * kappa(o_s, alphasq=ALPHA_SQ)) - torch.pow(a_m, 2) return a_m, a_s elif self.activation == 'tanh': a_m = 2.0 * torch.sigmoid(o_m * kappa(o_s, const=0.25)) - 1 a_s = 4.0 * torch.sigmoid(((o_m + BETA_2) * ALPHA_2) * kappa(o_s, alphasq=ALPHA_2_SQ)) - torch.pow(a_m, 2) - 2.0 * a_m - 1.0 return a_m, a_s else: return o_m, o_s class GaussianNPN(nn.Module): def __init__(self, input_features, output_classes, hidden_sizes, activation='sigmoid'): super(GaussianNPN, self).__init__() assert(len(hidden_sizes) >= 0) self.num_classes = output_classes self.layers = [] for i, h_sz in enumerate(hidden_sizes): if i == 0 : h = GaussianNPNLinearLayer(input_features, hidden_sizes[i]) else: h = GaussianNPNLinearLayer(hidden_sizes[i-1], hidden_sizes[i]) self.layers.append(h) self.layers.append(GaussianNPNNonLinearity(activation)) if len(hidden_sizes) > 0: self.layers.append(GaussianNPNLinearLayer(hidden_sizes[-1], output_classes)) else: self.layers.append(GaussianNPNLinearLayer(input_features, output_classes)) self.layers.append(GaussianNPNNonLinearity('sigmoid')) # last one needs to be sigmoid self.net = nn.Sequential(*list(self.layers)) # just to make model.parameters() work self.lossfn = nn.BCELoss(size_average=False) def forward(self, a): for L in self.layers: a = L(a) a_m, a_s = a return a_m, a_s def loss(self, x_m, x_s, y): a_m, a_s = self.forward((x_m, x_s)) return self.lossfn(a_m, y)
true
835273419d0836695073cbaba40829ae08fd54c9
Python
Colaplusice/algorithm_and_data_structure
/LeetCode/week_40/111_二叉树的最小深度栈实现.py
UTF-8
1,090
3.734375
4
[]
no_license
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 node_stack = [root] depth = 1 while node_stack: temp_stack = [] for no in node_stack: if not no or (not no.left and not no.right): return depth if no.left: temp_stack.append(no.left) if no.right: temp_stack.append(no.right) node_stack = temp_stack depth += 1 return depth if __name__ == "__main__": atree = TreeNode(1) btree = TreeNode(2) ctree = TreeNode(3) dtree = TreeNode(4) etree = TreeNode(5) atree.left = btree btree.left = dtree btree.right = etree atree.right = ctree sol = Solution() value = sol.minDepth(atree) print(value)
true
76b0198b7dbb04f530f0a98de4490175c9d93d0b
Python
Vsevolod-IT/python_projects
/algorithms_and_data_structure/lesson_2/task_8.py
UTF-8
1,034
3.90625
4
[]
no_license
'''Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел. Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры.''' def sep(data): m = int(data) num = str(m // 10 ** 0 % 10) data = str(m // 10) return num, data def func(data): res = '' checked = '' for i in data: num,data = sep(data) if (num in data) and (num not in checked): count = 1 for _,k in enumerate(data): if num == k: count += 1 res += f'число {num} : встречается {count} раз \n' checked += f'{num}' return print(res) data = input('введите число, программа подсчитает цифры которые будут повторяться --> ') print(func(data))
true
bd9a858111819c240ef71070bf0106a32dda9a2a
Python
kjford/tapmapper
/tapmapper/helpers/similaritymat.py
UTF-8
4,668
2.96875
3
[]
no_license
""" Compute cosine similarity between regions from TFIDF scores across beers """ from tapmapper.database import session_scope from tapmapper import models as m import pandas as pd import numpy as np def read_tfidf(): # import data from database # to do: this should really be stashed with session_scope() as s: q = s.query(m.Tfidf) data = [{'beerid': x.beerid, 'locbinid': x.locbinid, 'TFIDF': x.TFIDF} for x in q] df = pd.DataFrame(data) return df def cosinesim(v1, v2): # cosine similarity between 2 vectors cs=v1.dot(v2.T) / (np.sqrt(v1.dot(v1.T)) * np.sqrt(v2.dot(v2.T))) return cs def make_sim_mat(df): """ make similarity matrix using cosine similarity between pairs of TFIDF scores first make N (regions) by B (unique beerids) set of features from TFIDF scores """ B=df['beerid'].unique() N=df['locbinid'].unique() featvec=np.zeros((len(N),len(B))) # go through data frame and add TFIDF to feature vectors for _,rowdata in df.iterrows(): beer=rowdata['beerid'] region=rowdata['locbinid'] score=rowdata['TFIDF'] beerind=np.where(B==beer)[0][0] regind=np.where(N==region)[0][0] featvec[regind,beerind]=score S = np.zeros((len(N),len(N))) # compute similarity matrix for r in xrange(len(N)): rvec=featvec[r,:]/featvec[r,:].sum() for r2 in xrange(0,r): s=cosinesim(rvec,featvec[r2,:]/(featvec[r2,:].sum())) S[r,r2]=s S[r2,r]=s # waste of space to store twice, but this won't ever be that big # return along with unique indices of regions return S,N def make_sim_vec(df, regid): # rather than make the entire similarity matrix, just get similarity vector for # region of interest B = df['beerid'].unique() N = df['locbinid'].unique() featvec = np.zeros((len(N),len(B))) # go through data frame and add TFIDF to feature vectors for _, rowdata in df.iterrows(): beer = rowdata['beerid'] region = rowdata['locbinid'] score = rowdata['TFIDF'] beerind = np.where(B == beer)[0][0] regind = np.where(N == region)[0][0] featvec[regind, beerind] = score S = np.zeros((len(N))) roi = np.where(N == regid)[0][0] # compute similarity scores roivec = featvec[roi, :]/featvec[roi, :].sum() for r in xrange(len(N)): S[r] = cosinesim(featvec[r, :] / featvec[r,:].sum(), roivec) return S, N def get_region_example(): # look up in database the city with most tweets in region with session_scope() as s: q = s.query(m.RegionReps) data = [{'locbinid': x.region_id, 'cityid': x.city_id, 'beercount': x.beercount, 'fullname': x.fullname, 'lat': x.lat, 'lng': x.lng} for x in q] df = pd.DataFrame(data) return df def output_region_points(): # output in json like formate the region id's, names, and lat+lon df = get_region_example() df = df.set_index('locbinid') #index by region inds = list(df.index) bc = df.beercount.tolist() fn = df.fullname.tolist() lats = df.lat.tolist() lngs = df.lng.tolist() output = [] for i in xrange(len(df)): output.append({'regionid': inds[i], 'beercount': bc[i], 'fullname': fn[i], 'lat': lats[i], 'lng': lngs[i], 'similarity': bc[i]}) return output def get_simdata(regid): # get tf-idf similarity scores tfidf = read_tfidf() S, N = make_sim_vec(tfidf, regid) # get labels and coordinates for region ids rtitles = get_region_example() # turn into a dictionary a = rtitles.set_index('locbinid') # index by region b = pd.DataFrame({'similarity': S}, index=N) combdf_raw=a.join(b) # joined on index so now combdf.ix[regid] has all combdf = combdf_raw.sort_values('similarity', ascending=False) inds=list(combdf.index) bc = combdf.beercount.tolist() fn = combdf.fullname.tolist() lats = combdf.lat.tolist() lngs = combdf.lng.tolist() sim = combdf.similarity.tolist() output = [] taketop = np.minimum(len(N),20) for i in xrange(taketop): output.append({'regionid': inds[i], 'beercount': bc[i], 'fullname': fn[i], 'lat': lats[i], 'lng': lngs[i], 'similarity': sim[i]}) return output
true
25f0f9904777dc72515c3bd070e3bf37d9230584
Python
mtn/rcade-falldown
/main.py
UTF-8
10,341
2.671875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#!/usr/bin/env python3 """The RCade Ball Game!""" import sys import sdl2 import sdl2.ext import random import math BACKGROUND = sdl2.ext.Color(0, 0, 0) RC_GREEN = sdl2.ext.Color(61, 192, 108) WHITE = sdl2.ext.Color(255, 255, 255) P_HEIGHT = 10 W_HEIGHT = 750 W_WIDTH = 600 G_HEIGHT = 300 G_WIDTH = 400 width_shift = 100 height_shift = 100 static_components = [] UPRATE = -1 DOWNRATE = 3 HORIZ_SPEED = 2 class MovementSystem(sdl2.ext.Applicator): def __init__(self, minx, miny, maxx, maxy, player=None, rects=[]): super(MovementSystem, self).__init__() self.componenttypes = Velocity, sdl2.ext.Sprite self.minx = minx self.miny = miny self.maxx = maxx self.maxy = maxy self.player = player self.rects = rects def will_collide(self, velocity): pleft, ptop, pright, pbottom = self.player.sprite.area for rect in self.rects: left, top, right, bottom = rect.sprite.area if ( pleft + velocity.vx < right and pright + velocity.vx > left and ptop + velocity.vy < bottom and pbottom + velocity.vy > top ): return rect return None def process(self, world, componentsets): for comp in componentsets: velocity, sprite = comp swidth, sheight = sprite.size _, posy = sprite.position if not sprite == self.player.sprite: sprite.x += velocity.vx sprite.y += velocity.vy else: velocity.vy = DOWNRATE if not self.will_collide(velocity): sprite.x += velocity.vx sprite.y += velocity.vy else: velocity.vy = UPRATE if not self.will_collide(velocity): for y in reversed(range(UPRATE, DOWNRATE)): velocity.vy = y if not self.will_collide(velocity): sprite.y += velocity.vy sprite.x += velocity.vx break else: vx = velocity.vx velocity.vx = 0 if not self.will_collide(velocity): sprite.y += velocity.vy if sprite not in static_components: sprite.x = max(self.minx, sprite.x) sprite.y = max(self.miny, sprite.y) if sprite.x + swidth > self.maxx: sprite.x = self.maxx - swidth if not sprite == self.player.sprite: if sprite.y + sheight > self.maxy: sprite.y = self.maxy - sheight else: if sprite.y + sheight > (self.maxy - 10): sprite.y = self.maxy - 10 - sheight class SoftwareRenderSystem(sdl2.ext.SoftwareSpriteRenderSystem): def __init__(self, window): super(SoftwareRenderSystem, self).__init__(window) def render(self, components): sdl2.ext.fill(self.surface, BACKGROUND) super(SoftwareRenderSystem, self).render(reversed(components)) class TextureRenderSystem(sdl2.ext.TextureSpriteRenderSystem): def __init__(self, renderer): super(TextureRenderSystem, self).__init__(renderer) self.renderer = renderer def render(self, components): tmp = self.renderer.color self.renderer.color = BACKGROUND self.renderer.clear() self.renderer.color = tmp super(TextureRenderSystem, self).render(reversed(components)) class Velocity(object): def __init__(self): super(Velocity, self).__init__() self.vx = 0 self.vy = 0 class Player(sdl2.ext.Entity): def __init__(self, world, sprite, posx=0, posy=0, score=0): self.sprite = sprite self.sprite.position = posx, posy self.playerscore = score self.velocity = Velocity() class Rect(sdl2.ext.Entity): def __init__(self, world, sprite, posx=0, posy=0): self.sprite = sprite self.sprite.position = posx, posy self.velocity = Velocity() def generate_row(movement, world, factory, y=G_HEIGHT // 100): num_gaps = random.randint(1, 5) r_width = 0 for j in range(0, num_gaps): min_x = j * G_WIDTH // num_gaps gap_width = 20 + random.randint(0, 10) l_padding = random.randint(1, G_WIDTH // num_gaps - gap_width - 1) movement.rects.append( Rect( world, factory.from_color(RC_GREEN, size=(l_padding + r_width, P_HEIGHT)), min_x + width_shift - r_width, y * 100 + height_shift + 50, ) ) r_width = G_WIDTH // num_gaps - l_padding - gap_width if j == num_gaps - 1: movement.rects.append( Rect( world, factory.from_color(RC_GREEN, size=(r_width, P_HEIGHT)), min_x + l_padding + gap_width + width_shift, y * 100 + height_shift + 50, ) ) def run(): sdl2.ext.init() window = sdl2.ext.Window("RCade Falldown!", size=(W_WIDTH, W_HEIGHT)) window.show() if "-software" in sys.argv: print("Using software rendering") factory = sdl2.ext.SpriteFactory(sdl2.ext.SOFTWARE) else: print("(Default) Using hardware acceleration") renderer = sdl2.ext.Renderer(window) factory = sdl2.ext.SpriteFactory(sdl2.ext.TEXTURE, renderer=renderer) world = sdl2.ext.World() movement = MovementSystem( width_shift, -10 + height_shift, 400 + width_shift, 310 + height_shift ) if factory.sprite_type == sdl2.ext.SOFTWARE: spriterenderer = SoftwareRenderSystem(window) else: spriterenderer = TextureRenderSystem(renderer) world.add_system(movement) world.add_system(spriterenderer) outer_top = Rect(world, factory.from_color(WHITE, size=(600, 10)), 0, 0) static_components.append(outer_top.sprite) outer_bottom = Rect(world, factory.from_color(WHITE, size=(600, 10)), 0, 740) static_components.append(outer_bottom.sprite) outer_left = Rect(world, factory.from_color(WHITE, size=(10, 750)), 0, 0) static_components.append(outer_left.sprite) outer_right = Rect(world, factory.from_color(WHITE, size=(10, 750)), 590, 0) static_components.append(outer_right.sprite) border_rect_top = Rect(world, factory.from_color(WHITE, size=(500, 50)), 50, 50) static_components.append(border_rect_top.sprite) border_rect_bottom = Rect(world, factory.from_color(WHITE, size=(500, 50)), 50, 400) static_components.append(border_rect_bottom.sprite) border_rect_left = Rect(world, factory.from_color(WHITE, size=(50, 300)), 50, 100) static_components.append(border_rect_left.sprite) border_rect_right = Rect(world, factory.from_color(WHITE, size=(50, 300)), 500, 100) static_components.append(border_rect_right.sprite) base_mid_left = Rect(world, factory.from_color(WHITE, size=(175, 50)), 0, 500) static_components.append(base_mid_left.sprite) base_mid_right = Rect(world, factory.from_color(WHITE, size=(175, 50)), 425, 500) static_components.append(base_mid_right.sprite) base_mid_left2 = Rect(world, factory.from_color(WHITE, size=(50, 50)), 550, 550) static_components.append(base_mid_left2.sprite) base_mid_right2 = Rect(world, factory.from_color(WHITE, size=(50, 50)), 0, 550) static_components.append(base_mid_right2.sprite) letter0 = Rect(world, factory.from_color(WHITE, size=(45, 45)), 150, 605) static_components.append(letter0.sprite) letter1 = Rect(world, factory.from_color(WHITE, size=(45, 45)), 240, 605) static_components.append(letter1.sprite) letter2 = Rect(world, factory.from_color(WHITE, size=(45, 45)), 330, 605) static_components.append(letter2.sprite) letter3 = Rect(world, factory.from_color(WHITE, size=(45, 45)), 420, 605) static_components.append(letter3.sprite) letter4 = Rect(world, factory.from_color(WHITE, size=(45, 45)), 105, 650) static_components.append(letter4.sprite) letter5 = Rect(world, factory.from_color(WHITE, size=(45, 45)), 195, 650) static_components.append(letter5.sprite) letter6 = Rect(world, factory.from_color(WHITE, size=(45, 45)), 285, 650) static_components.append(letter6.sprite) letter7 = Rect(world, factory.from_color(WHITE, size=(45, 45)), 375, 650) static_components.append(letter7.sprite) player = Player( world, factory.from_color(WHITE, size=(10, 10)), 200 + width_shift, 300 + height_shift, ) movement.player = player for y in range(0, (G_HEIGHT) // 100): generate_row(movement, world, factory, y) running = True time = 0 last_score = 0 while running: for event in sdl2.ext.get_events(): if event.type == sdl2.SDL_QUIT: running = False break if event.type == sdl2.SDL_KEYDOWN: if event.key.keysym.sym == sdl2.SDLK_LEFT: player.velocity.vx = -HORIZ_SPEED elif event.key.keysym.sym == sdl2.SDLK_RIGHT: player.velocity.vx = HORIZ_SPEED elif event.type == sdl2.SDL_KEYUP: if event.key.keysym.sym in (sdl2.SDLK_LEFT, sdl2.SDLK_RIGHT): player.velocity.vx = 0 for rect in movement.rects: rect.velocity.vy = UPRATE _, posy = rect.sprite.position if posy == height_shift - 10: world.delete(rect) movement.rects.remove(rect) time += 1 if time % 50 == 0: generate_row(movement, world, factory) if not last_score == time // 10: print("Score: {}".format(last_score)) last_score = time // 10 if player.sprite.position[1] == height_shift: running = False print("You graduated :(") sdl2.SDL_Delay(10) world.process() if __name__ == "__main__": sys.exit(run())
true
0e070aab480b345618e3d77d9187bbf0fb14fc7d
Python
NITRO-AI/NitroFE
/NitroFE/time_based_features/moving_average_features/moving_average_features.py
UTF-8
28,234
2.875
3
[ "Apache-2.0" ]
permissive
import pandas as pd import numpy as np from typing import Union, Callable from NitroFE.time_based_features.weighted_window_features.weighted_window_features import ( weighted_window_features, ) from NitroFE.time_based_features.weighted_window_features.weighted_windows import ( _equal_window, _identity_window, ) class ExponentialMovingFeature: """ Provided dataframe must be in ascending order. """ def __init__( self, alpha: float = None, operation: str = "mean", initialize_using_operation: bool = False, initialize_span: int = None, com: float = None, span: int = None, halflife: float = None, min_periods: int = 0, ignore_na: bool = False, axis: int = 0, times: str = None, ): """ Parameters ---------- alpha : float, optional Specify smoothing factor directly, by default None operation : str, {'mean','var','std'} operation to be performed for the moving feature,available operations are 'mean','var','std', by default 'mean' initialize_using_operation : bool, optional If True, then specified 'operation' is performed on the first 'initialize_span' values, and then the exponential moving average is calculated, by default False initialize_span : int, optional the span over which 'operation' would be performed for initialization, by default None com : float, optional Specify decay in terms of center of mass, by default None span : float, optional specify decay in terms of span , by default None halflife : float, optional Specify decay in terms of half-life, by default None min_periods : int, optional Minimum number of observations in window required to have a value (otherwise result is NA), by default 0 ignore_na : bool, optional Ignore missing values when calculating weights; specify True to reproduce pre-0.15.0 behavior, by default False axis : int, optional The axis to use. The value 0 identifies the rows, and 1 identifies the columns, by default 0 times : str, optional Times corresponding to the observations. Must be monotonically increasing and datetime64[ns] dtype, by default None """ self.com = com self.span = span self.halflife = halflife self.alpha = alpha self.min_periods = min_periods if min_periods != None else 0 self.adjust = False self.ignore_na = ignore_na self.axis = axis self.times = times self.operation = operation self.last_values_from_previous_run = None self.initialize_using_operation = initialize_using_operation self.initialize_span = initialize_span def _perform_temp_operation(self, x): if self.operation == "mean": _return = x.mean() elif self.operation == "var": _return = x.var() elif self.operation == "std": _return = x.std() else: raise ValueError(f"Operation {self.operation} not supported") return _return def fit(self, dataframe: Union[pd.DataFrame, pd.Series], first_fit: bool = True): """ For your training/initial fit phase (very first fit) use fit_first=True, and for any production/test implementation pass fit_first=False Parameters ---------- dataframe : Union[pd.DataFrame, pd.Series] dataframe containing column values to create exponential moving feature over first_fit : bool, optional Moving features require past values for calculation. Use True, when calculating for training data (very first fit) Use False, when calculating for subsequent testing/production data { in which case the values, which were saved during the last phase, will be utilized for calculation }, by default True """ if not first_fit: if self.last_values_from_previous_run is None: raise ValueError( "First fit has not occured before. Kindly run first_fit=True for first fit instance," "and then proceed with first_fit=False for subsequent fits " ) self.adjust = False dataframe = pd.concat( [self.last_values_from_previous_run, dataframe], axis=0 ) else: if self.initialize_using_operation: self.min_periods = 0 if (self.initialize_span is None) and (self.span is None): raise ValueError( "For initialize_using_operation=True," "either initialize_span or span value is required" ) elif (self.initialize_span is None) and (self.span is not None): self.initialize_span = self.span first_frame = self._perform_temp_operation( dataframe[: self.initialize_span].rolling( window=self.initialize_span ) ) dataframe = pd.concat([first_frame, dataframe[self.initialize_span :]]) else: if self.initialize_span is not None: raise ValueError( "In order to use initialize_span, initialize_using_operation must be True" ) _dataframe = dataframe.ewm( com=self.com, span=self.span, halflife=self.halflife, alpha=self.alpha, min_periods=self.min_periods, adjust=self.adjust, ignore_na=self.ignore_na, axis=self.axis, times=self.times, ) _return = self._perform_temp_operation(_dataframe) if not first_fit: _return = _return.iloc[1:] self.last_values_from_previous_run = _return.iloc[-1:] return _return class HullMovingFeature: """ Provided dataframe must be in ascending order. """ def __init__( self, window: int = 4, min_periods: int = 1, operation: Callable = None ): """ Parameters ---------- window : int, optional Size of the rolling window, by default 3 min_periods : int, optional Minimum number of observations in window required to have a value, by default 1 operation : Callable, optional operation to perform over the weighted rolling window values, when None is passed, np.mean is used """ self.window = window self.min_periods = min_periods operation = np.mean if operation == None else operation self.operation = operation if self.window <= 1: raise ValueError(f"window size less than equal to 1 not supported") self.window_by_two, self.window_square_root = int( np.ceil(self.window / 2) ), int(np.ceil(np.sqrt(self.window))) def fit(self, dataframe: Union[pd.DataFrame, pd.Series], first_fit: bool = True): """ For your training/initial fit phase (very first fit) use fit_first=True, and for any production/test implementation pass fit_first=False Parameters ---------- dataframe : Union[pd.DataFrame,pd.Series] dataframe/series over which feature is to be constructed first_fit : bool, optional Moving features require past values for calculation. Use True, when calculating for training data (very first fit) Use False, when calculating for any subsequent testing/production data { in which case the values, which were saved during the last phase, will be utilized for calculation }, by default True """ if first_fit: self._window_size_weighted_moving_average_object = ( weighted_window_features() ) self._window_by_two_size_weighted_moving_average_object = ( weighted_window_features() ) self._hma_object = weighted_window_features() window_size_weighted_moving_average = self._window_size_weighted_moving_average_object.caluclate_weighted_moving_window_feature( dataframe=dataframe, first_fit=first_fit, window=self.window, min_periods=self.min_periods, operation=self.operation, ) window_by_two_size_weighted_moving_average = self._window_by_two_size_weighted_moving_average_object.caluclate_weighted_moving_window_feature( dataframe=dataframe, first_fit=first_fit, window=self.window_by_two, min_periods=self.min_periods, operation=self.operation, ) raw_hma = ( 2 * window_by_two_size_weighted_moving_average - window_size_weighted_moving_average ) hma = self._hma_object.caluclate_weighted_moving_window_feature( dataframe=raw_hma, first_fit=first_fit, window=self.window_square_root, min_periods=self.min_periods, operation=self.operation, ) return hma class _a_kaufman_efficiency: def __init__(self): pass def _calculate_kaufman_efficiency(self, x): up = np.abs(x.iloc[-1] - x.iloc[0]) down = np.abs(x.diff().fillna(0)).sum() if down == 0: return 0 else: return up / down def fit( self, dataframe: Union[pd.DataFrame, pd.Series], first_fit: bool = True, lookback_period: int = 4, min_periods: int = None, ): if first_fit: self._kaufman_efficiency_object = weighted_window_features() self.lookback_period = lookback_period self.min_periods = min_periods _kaufman_efficiency = ( self._kaufman_efficiency_object._template_feature_calculation( function_name="kaufman_efficiency", win_function=_identity_window, first_fit=first_fit, dataframe=dataframe, window=self.lookback_period, min_periods=self.min_periods, symmetric=None, operation=self._calculate_kaufman_efficiency, operation_args=(), ) ) return _kaufman_efficiency class KaufmanAdaptiveMovingAverage: """ Provided dataframe must be in ascending order. """ def __init__( self, kaufman_efficiency_lookback_period: int = 4, kaufman_efficiency_min_periods: int = None, fast_ema_span: int = 2, slow_ema_span: int = 5, ): """ Parameters ---------- kaufman_efficiency_lookback_period : int, optional Size of the rolling window of lookback for the caluculation of kaufman efficiency ratio , by default 4 kaufman_efficiency_min_periods : int, optional Minimum number of observations in window required to have a value for kaufman efficiency ratio, by default 1 fast_ema_span : int, optional fast span length, by default 2 slow_ema_span : int, optional slow span length, by default 5 """ self.kaufman_efficiency_lookback_period = kaufman_efficiency_lookback_period self.kaufman_efficiency_min_periods = kaufman_efficiency_min_periods self.fast_ema_span = fast_ema_span self.slow_ema_span = slow_ema_span def fit(self, dataframe: Union[pd.DataFrame, pd.Series], first_fit: bool = True): """ For your training/initial fit phase (very first fit) use fit_first=True, and for any production/test implementation pass fit_first=False Parameters ---------- dataframe : Union[pd.DataFrame, pd.Series] dataframe containing column values to create feature over first_fit : bool, optional Moving features require past values for calculation. Use True, when calculating for training data (very first fit) Use False, when calculating for subsequent testing/production data { in which case the values, which were saved during the last phase, will be utilized for calculation }, by default True """ if first_fit: self._kaufman_object = _a_kaufman_efficiency() if isinstance(dataframe, pd.Series): dataframe = dataframe.to_frame() kma = pd.DataFrame( np.zeros(dataframe.shape), columns=dataframe.columns, index=dataframe.index ) if first_fit: kma = pd.concat( [pd.DataFrame(np.zeros((1, kma.shape[1])), columns=kma.columns), kma] ) if self.kaufman_efficiency_min_periods == None: _first_pervious = self.kaufman_efficiency_lookback_period - 2 elif self.kaufman_efficiency_min_periods > 1: _first_pervious = self.kaufman_efficiency_min_periods - 2 else: _first_pervious = 0 else: kma = pd.concat([self.values_from_last_run, kma]) _first_pervious = -1 kma["_iloc"] = np.arange(len(kma)) _kaufman_efficiency = self._kaufman_object.fit( dataframe=dataframe, first_fit=first_fit, lookback_period=self.kaufman_efficiency_lookback_period, min_periods=self.kaufman_efficiency_min_periods, ) ll = [x for x in kma.columns if x != "_iloc"] SC = ( _kaufman_efficiency.copy() * (2 / (self.fast_ema_span + 1) - 2 / (self.slow_ema_span + 1)) + 2 / (self.slow_ema_span + 1) ) ** 2 if first_fit: SC.iloc[_first_pervious] = [0] * SC.shape[1] for r1, r2, r3 in zip( dataframe[(_first_pervious + 1) :].iterrows(), kma[(1 + _first_pervious + 1) :].iterrows(), SC[(_first_pervious + 1) :].iterrows(), ): previous_kama = kma[kma["_iloc"] == (r2[1]["_iloc"] - 1)][ll] kma.loc[kma["_iloc"] == r2[1]["_iloc"], ll] = ( previous_kama + np.multiply(r3[1].values, (r1[1].values - previous_kama.values)) ).values[0] res = kma.iloc[1:][ll] self.values_from_last_run = res.iloc[-1:] return res class FractalAdaptiveMovingAverage: """ Provided dataframe must be in ascending order. """ def __init__(self, lookback_period: int = 8, min_periods: int = 1): """ Parameters ---------- lookback_period : int, optional Size of the rolling window of lookback , by default 8 min_periods : int, optional Minimum number of observations in window required to have a value, by default 1 """ self.lookback_period = lookback_period self.min_periods = min_periods def _first_lb(self, x, first_len): return (np.max(x) - np.min(x)) / first_len def _second_lb(self, x, first_len): half = int((first_len) / 2) return (np.max(x.iloc[:half]) - np.min(x.iloc[:half])) / half def fit(self, dataframe: Union[pd.DataFrame, pd.Series], first_fit: bool = True): """ For your training/initial fit phase (very first fit) use fit_first=True, and for any production/test implementation pass fit_first=False Parameters ---------- dataframe : Union[pd.DataFrame, pd.Series] dataframe containing column values to create feature over first_fit : bool, optional Moving features require past values for calculation. Use True, when calculating for training data (very first fit) Use False, when calculating for subsequent testing/production data { in which case the values, which were saved during the last phase, will be utilized for calculation }, by default True """ if first_fit: self._first_object = weighted_window_features() self._second_object = weighted_window_features() self._third_object = weighted_window_features() if isinstance(dataframe, pd.Series): dataframe = dataframe.to_frame() fama = pd.DataFrame( np.zeros(dataframe.shape), columns=dataframe.columns, index=dataframe.index ) if first_fit: fama = pd.concat( [pd.DataFrame(np.zeros((1, fama.shape[1])), columns=fama.columns), fama] ) else: fama = pd.concat([self.values_from_last_run, fama]) fama["_iloc"] = np.arange(len(fama)) ll = [x for x in fama.columns if x != "_iloc"] first_res = self._first_object._template_feature_calculation( function_name="_first_object", win_function=_identity_window, first_fit=first_fit, dataframe=dataframe, window=int((self.lookback_period) / 2), min_periods=self.min_periods, symmetric=None, operation=self._first_lb, operation_args=(int((self.lookback_period) / 2)), ) second_res = self._second_object._template_feature_calculation( function_name="_second_object", win_function=_identity_window, first_fit=first_fit, dataframe=dataframe, window=self.lookback_period, min_periods=self.min_periods, symmetric=None, operation=self._second_lb, operation_args=(self.lookback_period), ) third_res = self._third_object._template_feature_calculation( function_name="_third_object", win_function=_identity_window, first_fit=first_fit, dataframe=dataframe, window=self.lookback_period, min_periods=self.min_periods, symmetric=None, operation=self._first_lb, operation_args=(self.lookback_period), ) fractal_dimension = ( np.log(second_res + first_res) - np.log(third_res) ) / np.log(2) a_value = np.exp(-4.6 * (fractal_dimension - 1)).fillna(0) a_value = pd.DataFrame( np.where(a_value < 0.01, 0.01, a_value), columns=a_value.columns ) FC = (self.lookback_period) / 2 SC = self.lookback_period oldN = (2 - a_value) / a_value newN = ((SC - FC) * (oldN - 1) / (SC - 1)) + FC a_value = 2 / (newN + 1) for r1, r2, r3 in zip( dataframe.iterrows(), fama[1:].iterrows(), a_value.iterrows() ): previous_kama = fama[fama["_iloc"] == (r2[1]["_iloc"] - 1)][ll] fama.loc[fama["_iloc"] == r2[1]["_iloc"], ll] = ( np.multiply(previous_kama.values, (1 - r3[1].values)) + np.multiply(r1[1].values, r3[1].values) )[0] res = fama.iloc[1:][ll] self.values_from_last_run = res.iloc[-1:] return res class TripleExponentialMovingFeature: """ Provided dataframe must be in ascending order. """ def __init__( self, alpha: float = None, operation: str = "mean", initialize_using_operation: bool = False, initialize_span: int = None, com: float = None, span: float = None, halflife: float = None, min_periods: int = 0, ignore_na: bool = False, axis: int = 0, times: str = None, ): """ Parameters ---------- alpha : float, optional Specify smoothing factor directly, by default None operation : str, {'mean','var','std'} operation to be performed for the moving feature,available operations are 'mean','var','std', by default 'mean' initialize_using_operation : bool, optional If True, then specified 'operation' is performed on the first 'initialize_span' values, and then the exponential moving average is calculated, by default False initialize_span : int, optional the span over which 'operation' would be performed for initialization, by default None com : float, optional Specify decay in terms of center of mass, by default None span : float, optional pecify decay in terms of span , by default None halflife : float, optional Specify decay in terms of half-life, by default None min_periods : int, optional Minimum number of observations in window required to have a value (otherwise result is NA)., by default 0 ignore_na : bool, optional Ignore missing values when calculating weights; specify True to reproduce pre-0.15.0 behavior, by default False axis : int, optional The axis to use. The value 0 identifies the rows, and 1 identifies the columns, by default 0 times : str, optional Times corresponding to the observations. Must be monotonically increasing and datetime64[ns] dtype, by default None """ self.com = com self.span = span self.halflife = halflife self.alpha = alpha self.min_periods = min_periods self.ignore_na = ignore_na self.axis = axis self.times = times self.operation = operation self.initialize_using_operation = initialize_using_operation self.initialize_span = initialize_span def fit(self, dataframe: Union[pd.DataFrame, pd.Series], first_fit: bool = True): """ For your training/initial fit phase (very first fit) use fit_first=True, and for any production/test/subsequent implementation pass fit_first=False Parameters ---------- dataframe : Union[pd.DataFrame, pd.Series] dataframe containing column values to create feature over first_fit : bool, optional Moving features require past values for calculation. Use True, when calculating for training data (very first fit) Use False, when calculating for subsequent testing/production data { in which case the values, which were saved during the last phase, will be utilized for calculation }, by default True """ if first_fit: self._first_exponential_average_object = ExponentialMovingFeature( initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, com=self.com, span=self.span, halflife=self.halflife, alpha=self.alpha, min_periods=self.min_periods, ignore_na=self.ignore_na, axis=self.axis, times=self.times, operation=self.operation, ) self._second_exponential_average_object = ExponentialMovingFeature( initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, com=self.com, span=self.span, halflife=self.halflife, alpha=self.alpha, min_periods=self.min_periods, ignore_na=self.ignore_na, axis=self.axis, times=self.times, operation=self.operation, ) self._third_exponential_average_object = ExponentialMovingFeature( initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, com=self.com, span=self.span, halflife=self.halflife, alpha=self.alpha, min_periods=self.min_periods, ignore_na=self.ignore_na, axis=self.axis, times=self.times, operation=self.operation, ) first_exponential_average = self._first_exponential_average_object.fit( dataframe=dataframe, first_fit=first_fit ) second_exponential_average = self._second_exponential_average_object.fit( dataframe=first_exponential_average, first_fit=first_fit ) third_exponential_average = self._third_exponential_average_object.fit( dataframe=second_exponential_average, first_fit=first_fit ) triple_exponential_average = ( 3 * first_exponential_average - 3 * second_exponential_average + third_exponential_average ) return triple_exponential_average class SmoothedMovingAverage: """ Provided dataframe must be in ascending order. """ def __init__(self, lookback_period: int = 4): """ Parameters ---------- lookback_period : int, optional Size of the rolling window of lookback , by default 4 """ self.lookback_period = lookback_period def fit( self, dataframe: Union[pd.DataFrame, pd.Series], first_fit: bool = True, ): """ For your training/initial fit phase (very first fit) use fit_first=True, and for any production/test implementation pass fit_first=False Parameters ---------- dataframe : Union[pd.DataFrame, pd.Series] dataframe containing column values to create feature over first_fit : bool, optional Moving features require past values for calculation. Use True, when calculating for training data (very first fit) Use False, when calculating for subsequent testing/production data { in which case the values, which were saved during the last phase, will be utilized for calculation }, by default True """ if first_fit: self._first_object = weighted_window_features() if isinstance(dataframe, pd.Series): dataframe = dataframe.to_frame() sma = pd.DataFrame( np.zeros(dataframe.shape), columns=dataframe.columns, index=dataframe.index ) if first_fit: sma.iloc[self.lookback_period - 1] = ( dataframe.iloc[: (self.lookback_period)].sum() / self.lookback_period ) else: sma = pd.concat([self.values_from_last_run, sma]) sma["_iloc"] = np.arange(len(sma)) ll = [x for x in sma.columns if x != "_iloc"] _start_frame = self.lookback_period if first_fit else 0 _start_sma = self.lookback_period if first_fit else 1 for r1, r2 in zip( dataframe[_start_frame:].iterrows(), sma[_start_sma:].iterrows() ): previous_kama = sma[sma["_iloc"] == (r2[1]["_iloc"] - 1)][ll] sma.loc[sma["_iloc"] == r2[1]["_iloc"], ll] = ( (previous_kama * (self.lookback_period - 1) + r1[1]) / self.lookback_period ).values[0] res = sma[ll] if first_fit else sma.iloc[1:][ll] self.values_from_last_run = res.iloc[-1:] return res
true
2bdfe25e344caa4e7dcbf525a23c99ce96b651a9
Python
nikrdc/outsider
/models.py
UTF-8
3,603
2.671875
3
[]
no_license
from flask_login import UserMixin from flask_sqlalchemy import SQLAlchemy from sqlalchemy.ext.hybrid import hybrid_method prices = ['Below $5', '$5 to $13', '$13 to $19', '$19 to $27', 'Over $27'] db = SQLAlchemy() class User(UserMixin, db.Model): __tablename__ = 'users' __searchable__ = ['name', 'username'] id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) username = db.Column(db.String(16)) email = db.Column(db.String(64), unique=True) confirmed = db.Column(db.Boolean, default=False) time_joined = db.Column(db.DateTime) places = db.relationship('Place', backref='creator', lazy='dynamic') password_hash = db.Column(db.String(128)) @property def password(self): raise AttributeError('password is not a readable attribute') @password.setter def password(self, password): self.password_hash = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.password_hash, password) def __repr__(self): return '<User %r>' % self.username def generate_confirmation_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id}) def confirm(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False if data.get('confirm') != self.id: return False self.confirmed = True db.session.add(self) return True def generate_reset_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'reset': self.id}) def reset_password(self, token, new_password): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False if data.get('reset') != self.id: return False self.password = new_password db.session.add(self) return True class Region(db.Model): __tablename__ = 'regions' __searchable__ = ['name', 'shortname'] id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) shortname = db.Column(db.String(64), unique=True) timezone = db.Column(db.String(32)) longitude = db.Column(db.Float) latitude = db.Column(db.Float) zoom = db.Column(db.SmallInteger()) places = db.relationship('Place', backref='region', lazy='dynamic') def __repr__(self): return '<Region %r>' % self.name class Place(db.Model): __tablename__ = 'places' __searchable__ = ['name', 'description'] id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) description = db.Column(db.Text()) price_index = db.Column(db.SmallInteger()) time_created = db.Column(db.DateTime) halfhours = db.Column(db.String(336)) region_id = db.Column(db.Integer, db.ForeignKey('regions.id')) user_id = db.Column(db.Integer, db.ForeignKey('users.id')) @hybrid_method def open_at(self, local_time): index = (local_time.day * 48) + (local_time.hour * 2) minute = local_time.minute if minute > 20: index += 1 if minute > 50: index += 1 if self.halfhours[index] == '1' and self.halfhours[index+1] == '1': return True else: return False def __repr__(self): return '<Place %r>' % self.name
true
b1566fda7f3aaa1bd656001bc64230daef596746
Python
kbalasub78/Python-CS1
/checkpoint2/monkey_trouble.py
UTF-8
1,906
4.6875
5
[]
no_license
## monkey_trouble.py ## We have two monkeys, a and b. Accept the input telling if each is smiling. ## We are in trouble if they are both smiling or if neither of them is smiling. ## Return True if we are in trouble. ## import sys module for graceful data input handling import sys def monkey_trouble(monkeyA_smile, monkeyB_smile): ## Check if both monkeys are smiling or if both monkeys are not smiling ## If so, print 'we are in trouble' ##if( (monkeyA_smile == 'true' and monkeyB_smile == 'true') or \ ## (monkeyA_smile == 'false' and monkeyB_smile == 'false') ) : ## Below line simplifies the if check if( monkeyA_smile == monkeyB_smile): return True else: return False ## Get user input telling if monkeys are smiling while True: try: monkeyA_smiling = input("Is monkey A smiling (True or False): ").title() monkeyB_smiling = input("Is monkey B smiling (True or False): ").title() if( (monkeyA_smiling != 'True' and monkeyA_smiling != 'False') or \ (monkeyB_smiling != 'True' and monkeyB_smiling != 'False')) : raise ValueError() if(monkeyA_smiling == 'True'): monkeyA_smiling = True elif(monkeyA_smiling == 'False'): monkeyA_smiling = False if(monkeyB_smiling == 'True'): monkeyB_smiling = True elif(monkeyB_smiling == 'False'): monkeyB_smiling = False break except: print("Error in data entered") if( monkey_trouble(monkeyA_smiling, monkeyB_smiling) ): print("We are in trouble.. Returning True") else: print("We are out of trouble. One of the monkey is not smiling..") ## Following is to check the function with different input values print( monkey_trouble(True, True) ) ## True print( monkey_trouble(False, False) ) ## True print( monkey_trouble(True, False) ) ## False print( monkey_trouble(False, True) ) ## False
true
86fe2b14e40c4c9915d0c64ee59fe4ced8b6fb73
Python
thomaswebster/neural-net-wargame
/ann.py
UTF-8
1,791
3.421875
3
[]
no_license
'''Neural network class, only supporting feed forward networks however any activation function is supported''' from random import random import numpy as np class Neuron(object): def __init__(self, weights, bias, activation_func): self.weights = weights self.bias = bias self.activation_func = activation_func @staticmethod def Always(z): return True @staticmethod def Perceptron(z): return z>0 @staticmethod def Sigmoid(z): return 1.0/(1.0+np.exp(-z)) def get_output(self, inp): return self.activation_func(np.dot(self.weights,inp) + self.bias) class ANN(object): def __init__(self, sizes, neurontype = None): self.layers = len(sizes) self.sizes = sizes self.neurontype = neurontype self.neurons = [[Neuron([0]*self.sizes[i-1], 0, neurontype) for j in range(self.sizes[i])] for i in range(1, self.layers)] def seed_network(self, seedrange): for o in range(self.layers-1): #for each layer of neurons for m in range(self.sizes[o+1]): #for each neuron in the layer self.seed_neuron(o, m, seedrange) def seed_neuron(self, layer, index, seedrange, weightindex = 0): self.neurons[layer][index].weights = [random()*(seedrange[1]-seedrange[0]) - seedrange[0] for i in range(self.sizes[layer])] self.neurons[layer][index].bias = random()*(seedrange[1]-seedrange[0]) - seedrange[0] def run(self, inputs): prev_outputs = np.array(inputs) for k in range(self.layers-1): prev_outputs = np.array([self.neurons[k][l].get_output(prev_outputs) for l in range(self.sizes[k+1])]) return prev_outputs
true
809c913e64aa66fb46175421d95f883d6ce5e571
Python
AbdullahUK/BugImpactRequirements
/main.py
UTF-8
4,462
2.796875
3
[]
no_license
"""Authors:Abdullah Alsaeedi and Sultan Almaghdhui Copyright (c) 2021 TU-CS Software Engineering Research Group (SERG), Date: 22/03/2021 Name: Software Bug Severity using Machine Learning and Deep Learning Version: 1.1 """ # Import required libraries from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import KFold, GridSearchCV from LoadingData import * from Preprocessing import * import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import os from nltk.corpus import stopwords from Learners import * os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/' def PreprocessBugsDescription(X_train, X_test): stop_words = set(stopwords.words('english')) X_train = [stem(preprocessTexts(text, stop_words)) for text in X_train] X_test = [stem(preprocessTexts(text, stop_words)) for text in X_test] return X_train, X_test # Press the green button in the gutter to run the script. if __name__ == '__main__': for Dataset in ['mongo-db']: print(Dataset) X, y = ReadBugSeverityDataset(Dataset) X = pd.np.asarray(X) y = pd.np.asarray(y) total_Accuracy_score_array = dict() total_Precision_score_array = dict() total_Recall_score_array = dict() total_Fscore_score_array = dict() kf = KFold(n_splits=5, shuffle=True) # 5 fold similar to (Arabic Sentiment Analysis:Lexicon-based and Corpus-based) paper for train_index, test_index in kf.split(X): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] X_train, X_test = PreprocessBugsDescription(X_train, X_test) vec = TfidfVectorizer(ngram_range=(1, 3)) X_train_tf_idf = vec.fit_transform(X_train, y_train) print(X_train_tf_idf) X_test_tf_idf = vec.transform(X_test) n_features = X_train_tf_idf.shape[1] for cls in ['RF', 'DS', 'SVM', 'LR']: # Accuracy_score_array = [] # Precision_score_array = [] # Recall_score_array = [] # Fscore_score_array = [] # AUC_score_array = [] print("-----------------------------------------------------------") print('CurrentClassifier= ' + cls) if cls == 'RF': accuracy, precision, recall, fscore = RandomForestLearner(X_train_tf_idf, X_test_tf_idf, y_train,y_test) elif cls == 'DS': accuracy, precision, recall, fscore = DecisionTreeLearner(X_train_tf_idf, X_test_tf_idf,y_train,y_test) elif cls == 'SVM': accuracy, precision, recall, fscore = SVMLearner(X_train_tf_idf, X_test_tf_idf, y_train,y_test) elif cls == 'MNB': accuracy, precision, recall, fscore = MultinomialNBLearner(X_train_tf_idf, X_test_tf_idf, y_train,y_test) elif cls == 'LR': accuracy, precision, recall, fscore = LogisticRegressionLearner(X_train_tf_idf, X_test_tf_idf, y_train,y_test) elif cls == 'BNB': accuracy, precision, recall, fscore = BernoulliNBLearner(X_train_tf_idf, X_test_tf_idf, y_train,y_test) elif cls == 'AdaBoost': accuracy, precision, recall, fscore = AdaBoostLearner(X_train_tf_idf, X_test_tf_idf, y_train,y_test,n_features) print('accuracy= ', accuracy) total_Accuracy_score_array.setdefault(cls, []).append(accuracy) total_Precision_score_array.setdefault(cls, []).append(precision) total_Recall_score_array.setdefault(cls, []).append(recall) total_Fscore_score_array.setdefault(cls, []).append(fscore) for cls in ['RF', 'DS', 'SVM', 'LR']: print("AccuracyScore for " + cls + " classifier= ", pd.np.mean(total_Accuracy_score_array.get(cls), axis=0)) print("PrecisionScore for " + cls + " classifier= ", pd.np.mean(total_Precision_score_array.get(cls), axis=0)) print("RecallScore for " + cls + " classifier= ", pd.np.mean(total_Recall_score_array.get(cls), axis=0)) print("FscoreScore for " + cls + " classifier= ", pd.np.mean(total_Fscore_score_array.get(cls), axis=0))
true
4e8f7e83bb32b1a1c6109e0c732e27b337873786
Python
YuriCat/test
/pytorch/repeat.py
UTF-8
195
2.703125
3
[]
no_license
import numpy as np import torch a = np.array([[1, 2], [3, 4]]) b = np.tile(np.reshape(a, [2, 1, 2]), [1, 3, 1]) print(b) c = torch.FloatTensor(a) d = c.view(2, 1, 2).repeat(1, 3, 1) print(d)
true
d6c788b641eb2bbd5b8f6d75ac82031dc9dd74d8
Python
mycicle/yamlval
/yamlval/BaseType.py
UTF-8
537
2.71875
3
[ "MIT" ]
permissive
from abc import ABCMeta, abstractmethod from typing import Any, Tuple, List, Optional class BaseType(metaclass=ABCMeta): """ In retrospect this class may not even be necesarry, but I will leave it in case there is a use for it """ def __init__(self): pass @abstractmethod def matches(self, inp: Any) -> Tuple[bool, Optional[List[str]]]: pass @property @abstractmethod def __type__(self): pass @property @abstractmethod def __children__(self): pass
true
dcaa45067b6625296902f26adaeb74a4ce2ed61d
Python
joeyshi12/totally-accurate-physics
/Main.py
UTF-8
1,519
3.234375
3
[]
no_license
import pygame from PendulumMass import * pygame.init() clock = pygame.time.Clock() display_width = 800 display_height = 500 display = pygame.display.set_mode((display_width, display_height)) m1 = PendulumMass(2, 0, (int(display_width / 2), int(display_height / 2)), 100) m2 = PendulumMass(-1, 0, m1.get_pos(), 100) dt = 0.02 g = 10 def draw_mass(m: PendulumMass): pygame.draw.line(display, (0, 0, 0), m.origin, m.get_pos()) pygame.draw.circle(display, (255, 0, 0), m.get_pos(), 10) def main(): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() display.fill((255, 255, 255)) alpha1 = (-3 * g * sin(m1.theta) - g * sin(m1.theta - 2 * m2.theta) - 2 * sin(m1.theta - m2.theta) * ( m2.omega ** 2 * m2.length - m1.omega ** 2 * m1.length * cos(m1.theta - m2.theta))) \ / (m1.length * (3 - cos(2 * m1.theta - 2 * m2.theta))) - 0.01 * m1.omega m1.update(dt, alpha1) alpha2 = (2 * sin(m1.theta - m2.theta) * ( m1.omega ** 2 * m1.length * 2 + g * 2 * cos(m1.theta) + m2.omega ** 2 * m2.length * cos( m1.theta - m2.theta))) \ / (m2.length * (3 - cos(2 * m1.theta - 2 * m2.theta))) - 0.01 * m2.omega m2.update(dt, alpha2) draw_mass(m1) draw_mass(m2) m2.origin = m1.get_pos() pygame.display.update() clock.tick(1000) if __name__ == '__main__': main()
true
6975d749655ab6448c4b5c2605c49d4a718e2d61
Python
doa-elizabeth-roys/CP1404_practicals
/prac_3/broken_score.py
UTF-8
691
3.96875
4
[]
no_license
import random def main(): score = float(input("Enter score: ")) print(level_of_score(score)) def level_of_score(score): """Determine level of score""" if 0<= score< 50: return "Bad score" elif 50<= score <90: return "Passable" elif 90<= score <=100: return "Excellent" else: return "Invalid score" main() def main(): random_score = randint(0,101) print(level_of_score2(random_score)) def level_of_score2(score) : """Determine level of score""" if 0 <= score < 50 : return "Bad score" elif 50 <= score < 90 : return "Passable" elif 90 <= score <= 100 : return "Excellent" else : return "Invalid score"
true
9cc6f48958c2b4b23543f61b5fd173561b45d388
Python
guanguanboy/TestPytorch
/repeat_demo2.py
UTF-8
850
3.4375
3
[]
no_license
import torch def get_noise(n_samples, input_dim, device='cpu'): ''' Function for creating noise vectors: Given the dimensions (n_samples, input_dim) creates a tensor of that shape filled with random numbers from the normal distribution. Parameters: n_samples: the number of samples to generate, a scalar input_dim: the dimension of the input vector, a scalar device: the device type ''' return torch.randn(n_samples, input_dim, device=device) device = 'cuda' z_dim = 64 n_interpolation = 9 # Choose the interpolation: how many intermediate images you want + 2 (for the start and end image) interpolation_noise = get_noise(1, z_dim, device=device).repeat(n_interpolation, 1) print(get_noise(1, z_dim, device=device).shape) print(interpolation_noise.shape) print(interpolation_noise)
true
35a9083d81856950316399afe308c1ba9a915fb8
Python
PCloherty/project_eular
/problem6/sum_square_diff.py
UTF-8
1,621
4.8125
5
[]
no_license
#The sum of the squares of the first ten natural numbers is, #1²+2²+...+10²=385 #The square of the sum of the first ten natural numbers is, #(1+2+...+10)²=55²=3025 #Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is . #3025-385=2640 #Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. def main(): #make an integer and list variable for both the sum of squares(sumSquares) and square of sums(squaredSum) sumSquares=0 sumSquaresList=[] squaredSum=0 squaredSumList=[] #for each number up to 100 do 3 things #1 square the number #2 populate the list of sumSquaresList with the squared number #3 populate the list of squaredSumList with the normal number for i in range(1,101): sumSquares=i*i sumSquaresList.append(sumSquares) squaredSumList.append(i) #getting the answer for the sum of squares sumSquares=sum(sumSquaresList) #getting the answer for the square of sums squaredSum=sum(squaredSumList) squaredSum=squaredSum*squaredSum print('The sum of squares is:') print(sumSquares) print('The square of sums is:') print(squaredSum) print('The difference is:') if (sumSquares > squaredSum): print(sumSquares-squaredSum) else: print(squaredSum-sumSquares) main()
true
9475a15873b8133b9df3c1c27e8bae9906f3dec7
Python
simonwu53/Class-attendance-solution
/voice_recog/funcs_voice.py
UTF-8
3,769
3.015625
3
[]
no_license
""" 25.05.2018 version 2 abandon function play_sound """ # import import os import pyaudio import numpy as np import librosa import wave # static variables FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 CHUNK = 1024 # static funcs def wav_file_in_folder(path): """ make a list of wave file in the folder :param path: folder want to search :return: a list of wav file, None if no wav file """ file_list = [] for file in os.listdir(path): if os.path.splitext(file)[1] == '.wav': file_list.append(file) if len(file_list) == 0: return None else: return file_list def extract_features(wav): """ function to extract wav features :param wav: path to wav file :return: beat-synchronous features """ # Set the hop length; at 22050 Hz, 512 samples ~= 23ms hop_length = 512 y, sr = librosa.load(wav, mono=True) mfcc = librosa.feature.mfcc(y=y, sr=sr, hop_length=hop_length, n_mfcc=13) mfcc_delta = librosa.feature.delta(mfcc) return np.concatenate((mfcc, mfcc_delta), axis=1) # # Load the example clip # y, sr = librosa.load(wav) # # # Set the hop length; at 22050 Hz, 512 samples ~= 23ms # hop_length = 512 # # # Separate harmonics and percussives into two waveforms # y_harmonic, y_percussive = librosa.effects.hpss(y) # # # Beat track on the percussive signal # tempo, beat_frames = librosa.beat.beat_track(y=y_percussive, sr=sr) # # # Compute MFCC features from the raw signal # mfcc = librosa.feature.mfcc(y=y, sr=sr, hop_length=hop_length, n_mfcc=13) # # # And the first-order differences (delta features) # mfcc_delta = librosa.feature.delta(mfcc) # # # Stack and synchronize between beat events # # This time, we'll use the mean value (default) instead of median # beat_mfcc_delta = librosa.util.sync(np.vstack([mfcc, mfcc_delta]), # beat_frames) # # # Compute chroma features from the harmonic signal # chromagram = librosa.feature.chroma_cqt(y=y_harmonic, # sr=sr) # # # Aggregate chroma features between beat events # # We'll use the median value of each feature between beat frames # beat_chroma = librosa.util.sync(chromagram, # beat_frames, # aggregate=np.median) # # # Finally, stack all beat-synchronous features together # beat_features = np.vstack([beat_chroma, beat_mfcc_delta]) # return beat_features def play_sound(audio, path): # use audio object from an instance # length of data to read. chunk = 1024 # open the file for reading. wf = wave.open(path, 'rb') # create an audio object # p = pyaudio.PyAudio() # open stream based on the wave object which has been input. stream = audio.open(format= audio.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) # read data (based on the chunk size) data = wf.readframes(chunk) # play stream (looping from beginning of file to the end) while len(data) > 0: # writing to the stream is what *actually* plays the sound. stream.write(data) data = wf.readframes(chunk) # cleanup stuff. stream.stop_stream() stream.close() if __name__ == '__main__': wav_file_in_folder('/Users/simonwu/PycharmProjects/PR/Class-attendance-solution/voice_recog') wav_file_in_folder('/Users/simonwu/PycharmProjects/PR/Class-attendance-solution/train/Stella') # play_sound()
true
eec41fc6f89d0fdf5e8fe2841ff938fd16a70f9d
Python
BrianHicks/elasticsearch-py
/test_elasticsearch/test_serializer.py
UTF-8
1,238
2.515625
3
[ "Apache-2.0" ]
permissive
# -*- coding: utf-8 -*- import sys from datetime import datetime from decimal import Decimal from elasticsearch.serializer import JSONSerializer from elasticsearch.exceptions import SerializationError from .test_cases import TestCase, SkipTest class TestJSONSerializer(TestCase): def test_datetime_serialization(self): self.assertEquals(u'{"d": "2010-10-01T02:30:00"}', JSONSerializer().dumps({'d': datetime(2010, 10, 1, 2, 30)})) def test_decimal_serialization(self): if sys.version_info[:2] == (2, 6): raise SkipTest("Float rounding is broken in 2.6.") self.assertEquals(u'{"d": 3.8}', JSONSerializer().dumps({'d': Decimal('3.8')})) def test_raises_serialization_error_on_dump_error(self): self.assertRaises(SerializationError, JSONSerializer().dumps, object()) def test_raises_serialization_error_on_load_error(self): self.assertRaises(SerializationError, JSONSerializer().loads, object()) self.assertRaises(SerializationError, JSONSerializer().loads, '') self.assertRaises(SerializationError, JSONSerializer().loads, '{{') def test_strings_are_left_untouched(self): self.assertEquals(u"你好", JSONSerializer().dumps(u"你好"))
true
1c85225943990a8c046ce1c4a0532f149653f79d
Python
mazdanoff/joblooker
/runner/context_object.py
UTF-8
282
2.609375
3
[]
no_license
class ContextObject: def __init__(self): self.driver = None self.url = '' self.offers = set() @property def offer_list(self): return [", ".join(offer) for offer in self.offers] def offer_list_data(self): return self.offers
true
c3d1b3994cd5eb002c1a686cc42c30871d54e72c
Python
wlady2906/WLDE-Phyton-Exercises
/String Length/String length.py
UTF-8
295
3.6875
4
[]
no_license
print ('By not using the reserved function len(). Declare a function (def) that execute the same logic') def longitud(adv): cont = 0 for i in adv: cont +=1 return cont '''acum the range from the for loop''' string = input("Write a string --> ") print(longitud(string))
true
de3a9512ec9c7a2e2d9a8a4eb878ee27f36ea044
Python
caioalmeida97/Project-Euler
/Python/Problem024.py
UTF-8
165
3.46875
3
[]
no_license
from itertools import * def comb(nums): for a in combinations(nums, 3): # Tentando fazer a combinatória dos números 1, 2 e 3 print a comb([1, 2, 3])
true
856a95ff91cfc3b3a37da939255e096b41a42db5
Python
JennyLawrance/IgniteDemos
/twitterapp/application.py
UTF-8
3,076
2.890625
3
[]
no_license
import json import re import operator from collections import Counter import nltk nltk.download('stopwords') from nltk.corpus import stopwords import string from nltk import bigrams emoticons_str = r""" (?: [:=;] # Eyes [oO\-]? # Nose (optional) [D\)\]\(\]/\\OpP] # Mouth )""" regex_str = [ emoticons_str, r'<[^>]+>', # HTML tags r'(?:@[\w_]+)', # @-mentions r"(?:\#+[\w_]+[\w\'_\-]*[\w_]+)", # hash-tags r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+', # URLs r'(?:(?:\d+,?)+(?:\.?\d+)?)', # numbers r"(?:[a-z][a-z'\-_]+[a-z])", # words with - and ' r'(?:[\w_]+)', # other words r'(?:\S)' # anything else ] from flask import Flask app = Flask(__name__) @app.route("/") def hello(): tokens_re = re.compile(r'('+'|'.join(regex_str)+')', re.VERBOSE | re.IGNORECASE) emoticon_re = re.compile(r'^'+emoticons_str+'$', re.VERBOSE | re.IGNORECASE) def tokenize(s): return tokens_re.findall(s) def preprocess(s, lowercase=False): tokens = tokenize(s) if lowercase: tokens = [token if emoticon_re.search(token) else token.lower() for token in tokens] return tokens punctuation = list(string.punctuation) #stop = stopwords.words('english') + punctuation + ['rt', 'via', 'RT', '\'', 'session', '#MSIgnite', 'Microsoft', '#msignite', 'The', 'I', 'because', '’', '…', '2019', 'This', 'A'] stop = stopwords.words('english') + punctuation + ['rt', 'via', 'RT', '\'', 'session', '#MSIgnite', 'Microsoft', '#msignite', 'The', 'I', 'because', '’', '…', '2019', 'This', 'A'] with open('python.json', 'r') as f: count_all = Counter() count_filtered = Counter() count_bigrams = Counter() for line in f: if len(line.strip()) > 0: tweet = json.loads(line) #tokens = preprocess(tweet['text']) terms_all = [term for term in preprocess(tweet['text'])] terms_stop = [term for term in preprocess(tweet['text']) if term not in stop] # Update the counter count_all.update(terms_all) if len(terms_stop) > 0: count_filtered.update(terms_stop) terms_bigram = bigrams(terms_stop) listitems = list(terms_bigram) count_bigrams.update(listitems) result = '<html><body>' result += '<b>Most common words: </b><br><br>' for x in count_filtered.most_common(10)[:]: #if len(x)==3: result += str(x) result += '<br>' result += '<br><br><b>Most common word pairs: </b><br>' #print(count_filtered.most_common(10)) for x in count_bigrams.most_common(10)[:]: #if len(x)==3: result += str(x) result += '<br>' #return str(count_bigrams.most_common(10)) result += '</body></html>' return result
true
f553a09c61a3cd24b1b3142eff304ac90287b511
Python
Arnabsaha6/Snakify
/Reversethefragment.py
UTF-8
127
3.34375
3
[ "MIT" ]
permissive
Code: s = input() a = s[:s.find('h')] b = s[s.find('h'):s.rfind('h') + 1] c = s[s.rfind('h') + 1:] s = a + b[::-1] + c print(s)
true
43c3fe76665abb6975153726a71538bad41914b5
Python
ChangxingJiang/LeetCode
/0901-1000/0968/0968_Python_2.py
UTF-8
2,171
3.46875
3
[]
no_license
from toolkit import TreeNode from toolkit import build_TreeNode class Solution: def __init__(self): self.root = None self.ans = 0 def dfs(self, node): # 贪心算法:每个节点在选择装监控的方案时,都尽可能让装的监控更靠近根节点 # 返回值:1. 当前节点下安装监控的最小数量 # 2. 当前节点的父节点是否必须安装监控:1=距离最近监控为1个单位距离;2=距离当前最近监控为2个单位距离;3=距离当前最近监控为3个单位距离 # 处理节点不存在的情况 if not node: return 2 # 处理当前节点不是叶节点的情况 left = self.dfs(node.left) right = self.dfs(node.right) # dd = [1,3] or [2,3] or [3,3] or [3,2] or [3,1] # 情况:左节点或右节点中至少有一个的所有子节点都没有安装监控 if left == 3 or right == 3: self.ans += 1 return 1 # dd = [1,1] or [1,2] or [2,1] # 情况:左节点或右节点有一个已经安装监控,且另外一个子结点的至少一个子节点也已经安装监控 elif left == 1 or right == 1: return 2 # dd = [2,2] # 情况A:左节点和右节点都没有安装监控,但是它们都至少有一个子节点安装了监控 # 情况B:当前节点为叶节点 else: if node == self.root: self.ans += 1 return 1 else: return 3 def minCameraCover(self, root: TreeNode) -> int: self.root = root self.dfs(root) return self.ans if __name__ == "__main__": print(Solution().minCameraCover(build_TreeNode([0, 0, None, 0, 0]))) # 1 print(Solution().minCameraCover(build_TreeNode([0, 0, None, 0, None, 0, None, None, 0]))) # 2 print(Solution().minCameraCover(build_TreeNode([0]))) # 1 print(Solution().minCameraCover(build_TreeNode([0, None, 0, None, 0, None, 0]))) # 2 print(Solution().minCameraCover(build_TreeNode([0, 0, 0, None, 0, 0, None, None, 0]))) # 2
true
9a343cb982a96c3ba4129e293476e671fda5a0d4
Python
lucasgsa/pygame-tutorial
/aula2.py
UTF-8
2,155
2.75
3
[]
no_license
# coding: utf-8 # AULA 1 - PYGAME # LUCAS KPNZ import pygame from pygame.locals import * pygame.init() pygame.font.init() cor_preta = (0,0,0) tela = pygame.display.set_mode((1280,720)) pygame.display.set_caption("Teste") player1_x = 100 player1_y = 100 player1_velocidade = 10 player2_x = 1180 player2_y = 100 player2_velocidade = 10 bola_x = 640 bola_y = 360 bola_velocidade = 5 bola_direcaox = 1 bola_direcaoy = 1 player1 = pygame.Surface((25,100)) player2 = pygame.Surface((25,100)) bola = pygame.Surface((25,25)) player1.fill(cor_preta) player2.fill(cor_preta) bola.fill((255,0,0)) fonteVencedor = pygame.font.SysFont('Comic Sans MS', 50) fonteVencedor2 = fonteVencedor.render("Vencedor eh o jogador 2", 1, (38,255,0)) fonteVencedor1 = fonteVencedor.render("Vencedor eh o jogador 1", 1, (38,255,0)) relogio = pygame.time.Clock() while True: relogio.tick(30) tela.fill((255,255,255)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() quit() bola_x += bola_velocidade*bola_direcaox bola_y += bola_velocidade*bola_direcaoy # Sistema de limitação do mapa if (bola_y >= 720-25): bola_direcaoy = bola_direcaoy*-1 if (bola_y <= 0+25): bola_direcaoy = bola_direcaoy*-1 # Sistema de colisão if ((player1_y <= bola_y <= player1_y+125)and(player1_x <= bola_x <= player1_x+25)): bola_direcaox = bola_direcaox*-1 if ((player2_y <= bola_y <= player2_y+125)and(player2_x <= bola_x+25 <= player2_x+25)): bola_direcaox = bola_direcaox*-1 if (bola_x < 90): tela.blit(fonteVencedor2, (0,0)) print ("Vencedor jogador numero 2") if (bola_x > 1190): tela.blit(fonteVencedor1, (0,0)) print ("Vencedor jogador numero 2") key = pygame.key.get_pressed() if key[K_w] and player1_y > 0: player1_y -= player1_velocidade if key[K_s] and player1_y+100 < 720: player1_y += player1_velocidade if key[K_UP] and player2_y > 0: player2_y -= player2_velocidade if key[K_DOWN] and player2_y+100 < 720: player2_y += player2_velocidade tela.blit(player1, (player1_x,player1_y)) tela.blit(player2, (player2_x,player2_y)) tela.blit(bola, (bola_x, bola_y)) pygame.display.update()
true
a271beab807d0b8c04d3c76261b3c1a9e6d55b3b
Python
pythoncanarias/eoi
/10-iot/A04b_salida_entrada-analogica/main.py
UTF-8
1,488
3.234375
3
[]
no_license
import machine import utime # Creado por Daniel Alvarez (danidask@gmail.com) para curso de Python de EOI (eoi.es) # Ampliado por Victor Suarez (suarez.garcia.victor@gmail.com) para curso de Python EOI (eoi.es) # Para ESP32 usar los GPIO disponibles # Para ATomLite usar GPIO33 # Para Raspberry Pi usar GPIO28 por ejemplo led = machine.Pin(12, machine.Pin.OUT) led_pwm = machine.PWM(led, freq=1000) # led_pwm.freq(1000) # la frecuencia se puede cambiar en cualquier momento, aunque solemos dejarla fija (cambiamos el duty) led_pwm.duty(511) # La resolucion del PWM del ESP32 es de 10 bits, lo que significa que va desde 0 (0%) hasta 1023 (100%) utime.sleep_ms(1000) adc = machine.ADC(machine.Pin(13)) adc.atten(machine.ADC.ATTN_11DB) # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v) # ver https://docs.micropython.org/en/latest/esp32/quickref.html?highlight=timer#adc-analog-to-digital-conversion def remapear(x, in_min, in_max, out_min, out_max): # esto es la implementacion de la funcion "map" de arduino # https://www.arduino.cc/reference/en/language/functions/math/map/ return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min while True: valor = adc.read() # NOTA: el conversor ADC del ESP32 es de 12bits, lo que significa que devolvera un numero entre 0 y 4095 salida = remapear(valor, 0, 4095, 0, 511) # Se remapea para que tenga los valores debido al DAC que tiene 8 bits led_pwm.duty(int(salida)) # se manda la salida ya remapeada utime.sleep_ms(100)
true
b9e522bfab40f9374761bd753109aea245b99a37
Python
MiguelTeixeiraUFPB/PythonM2
/algoritmos/PythonM2/viagem43.py
UTF-8
641
3.265625
3
[ "MIT" ]
permissive
buenosairesdia=220 santiagodia=307 montevideodia=280.6 viagembuenosaires=810 viagemsantiago=900.50 viagemmontevideo=780 dias=int(input('quantidade de dias:')) lugar=(input('qual lugar deseja ir:')).upper() if lugar=='BUENOS AIRES': print('o valor a ser pago pela hospedagem é {}R$ e a passagem é {}R$'.format(buenosairesdia*dias,viagembuenosaires*2)) elif lugar=='MONTEVIDEO': print('o valor a ser pago pela hospedagem é {}R$ e a passagem é {}R$'.format(montevideodia*dias,viagemmontevideo*2)) else: print('o valor a ser pago pela hospedagem é {}R$ e a passagem é {}R$'.format(santiagodia*dias,viagemsantiago*2)) print()
true
72968fce1db8b3bed512579b4212c72a39adf61d
Python
anton-khimich/HashTables
/hash_tasks.py
UTF-8
1,580
3.21875
3
[]
no_license
from hash_table import * from linked_list import * from records import * def default_reader(list, hashtable): """default_reader(list, HashTable) --> None A function that takes a list and inserts each key(str) as Records into the given HashTable.""" for i in list: if hashtable.retrieve(i) == None: hashtable.insert(i) def word_reader(filename, hashtable): """word_reader(str, HashTable) --> None A function that takes the given filename and inserts each key(word) and their count as Word_Records into the given HashTable.""" string = open(r"{}".format(filename)) temp = [] for line in string: temp += line.split() for i in temp: wr = Word_Record(i) if hashtable.retrieve(wr) == None: hashtable.insert(wr) else: hashtable.retrieve(wr).add_one() def ip_reader(filename, hashtable): """ip_reader(str, HashTable) --> None A function that takes the given filename and inserts each key(IP address) and their pages visited as IP_Records into the given HashTable.""" string = open(r"{}".format(filename)) for line in string: ir = IP_Record(line.split()[0].strip(":")) if hashtable.retrieve(ir) == None: ir.add_pages(line.split()[1]) hashtable.insert(ir) else: hashtable.retrieve(ir).add_pages(line.split()[1]) #if __name__ == "__main__": #ht = HashTable(11000, False) #ip_reader("ip_clicks.txt", ht) #word_reader("wordy_file.txt", ht) #print(ht)
true
d39a6391e28507d50f6233d55536c28606c8819e
Python
hungry-me/Project-Euler
/Prog6.py
UTF-8
253
3.46875
3
[]
no_license
def getSum(n): res=0; for i in range(1,n+1): res+=i*i; return res; def getSumSq(n): res=(n*(n+1))//2; return res*res; def sumSquare(): s1=getSum(100); s2=getSumSq(100); print(s2-s1); sumSquare();
true
9c8ed4cb1f8aefe14265becb4be63c3c022a9a5d
Python
egemen-candir/github-test
/Toronto Clustering and Segmenting.py
UTF-8
3,678
3.25
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # # Clustering and Segmenting the Neighborhoods in Toronto # In[1]: get_ipython().system('conda install -c conda-forge geopy --yes') get_ipython().system('conda install -c conda-forge folium=0.5.0 --yes') # In[2]: conda install -c anaconda beautifulsoup4 # In[16]: import pandas as pd import numpy as np import matplotlib.cm as cm import matplotlib.colors as colors from sklearn.cluster import KMeans from geopy.geocoders import Nominatim import folium import requests from bs4 import BeautifulSoup pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) # In[42]: #recursive function for geopy timeouts but didn't have to use from geopy.exc import GeocoderTimedOut def do_geocode(address): try: return geopy.geocode(address) except GeocoderTimedOut: return do_geocode(address) # ## TASK1: Scrape data from wikipedia clone wikizero page using BeautifulSoup and create Toronto neighborhoods dataframe # In[2]: # Normally, I'd use the Wikipedia link but since Wikipedia is blocked by government in Turkey I need to use its close, Wikizero # This would be the normal code: # wiki = requests.get("https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M") # Instead the one below with different link but same data is used wiki = requests.get("https://www.wikizeroo.org/index.php?q=aHR0cHM6Ly9lbi53aWtpcGVkaWEub3JnL3dpa2kvTGlzdF9vZl9wb3N0YWxfY29kZXNfb2ZfQ2FuYWRhOl9N") soup = BeautifulSoup(wiki.content, 'html.parser') # In[3]: #read the table from scraped data table = soup.find('tbody') rows = table.select('tr') row = [r.get_text() for r in rows] # In[4]: #creating and cleaning the dataframe df = pd.DataFrame(row) df = df[0].str.split('\n', expand=True) df = df.rename(columns=df.iloc[0]) df = df.drop(df.index[0]) df = df[df.Borough != 'Not assigned'] df = df.groupby(['Postcode', 'Borough'], sort = False).agg(','.join) df.reset_index(inplace = True) df = df.replace("Not assigned", "Queen's Park") df.head() # ## TASK2: Find coordinates by postcode and merge with the main dataframe # In[7]: #reading geospatial data and creating its dataframe url = "http://cocl.us/Geospatial_data" df_coord = pd.read_csv(url) df_coord.rename(columns={'Postal Code': 'Postcode'}, inplace=True) df_coord.head() # In[9]: #merge two dataframes df_GTA = pd.merge(df, df_coord, on='Postcode') df_GTA.head() # ## TASK3: Explore and cluster neighborhoods in Toronto # In[11]: #number of neighborhoods print('There are {} boroughs and {} neighbourhoods.'.format( len(df_GTA['Borough'].unique()), df_GTA.shape[0] ) ) # In[33]: # Create a new dataframe with boroughs that contain the word Toronto Toronto_df = df_GTA[df_GTA['Borough'].str.contains('Toronto')] Toronto_df.head() # In[44]: # Visualize the boroughs on the map address = 'Toronto' geolocator = Nominatim(user_agent="Ege_Toronto") location = geolocator.geocode(address, timeout=15) latitude = location.latitude longitude = location.longitude map_Toronto = folium.Map(location=[latitude, longitude], zoom_start=10) for lat, lng, borough, neighborhood in zip(Toronto_df['Latitude'], Toronto_df['Longitude'], Toronto_df['Borough'], Toronto_df['Neighbourhood']): label = '{}, {}'.format(neighborhood, borough) label = folium.Popup(label, parse_html=True) folium.CircleMarker( [lat, lng], radius=5, popup=label, color='blue', fill=True, fill_color='#3186cc', fill_opacity=0.7, parse_html=False).add_to(map_Toronto) map_Toronto # In[ ]:
true
4bcb50b8124d5a78cd24ac047cf3e03017118626
Python
gomsvicky/PythonAssignmentCaseStudy1
/Program5.py
UTF-8
394
2.890625
3
[]
no_license
import sys print(sys.argv) print("length of arguments ", len(sys.argv)) for i in sys.argv: print("arugment is ", i) if sys.argv[3] > sys.argv[1] and sys.argv[3] > sys.argv[2]: print("biggest number is ", sys.argv[3]) elif sys.argv[2] > sys.argv[1] and sys.argv[2] > sys.argv[3]: print("biggest number is ", sys.argv[2]) else: print("biggest number is ", sys.argv[1])
true
fc68933b95f3b6088cd7552af8c016537854850f
Python
rfhits/Data-Structure-BUAA
/0-OnlineJudge/00-热身练习题/2-打印对角矩阵.py
UTF-8
477
4.3125
4
[]
no_license
# 现在请你打印一个n阶单位矩阵。 # 【输入形式】 # 一行整数n (0 < n <= 10) # 【输出形式】 # 输出该n阶单位矩阵,每个元素之间用空格分隔 # 【样例输入】 # 3 # 【样例输出】 # 1 0 0 # 0 1 0 # 0 0 1 s = int(input()) def prilin(s, j): for i in range(s): if i == j: print('1', end=' ') else: print('0', end=' ') print('') return for i in range(s): prilin(s, i)
true
0784e018e0b7fed4318dffa7255781232a596c63
Python
NVIDIA/DeepLearningExamples
/PyTorch/SpeechSynthesis/HiFiGAN/common/text/cleaners.py
UTF-8
2,894
3.171875
3
[ "Apache-2.0", "MIT" ]
permissive
""" adapted from https://github.com/keithito/tacotron """ ''' Cleaners are transformations that run over the input text at both training and eval time. Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners" hyperparameter. Some cleaners are English-specific. You'll typically want to use: 1. "english_cleaners" for English text 2. "transliteration_cleaners" for non-English text that can be transliterated to ASCII using the Unidecode library (https://pypi.python.org/pypi/Unidecode) 3. "basic_cleaners" if you do not want to transliterate (in this case, you should also update the symbols in symbols.py to match your data). ''' import re from .abbreviations import normalize_abbreviations from .acronyms import normalize_acronyms, spell_acronyms from .datestime import normalize_datestime from .letters_and_numbers import normalize_letters_and_numbers from .numerical import normalize_numbers from .unidecoder import unidecoder # Regular expression matching whitespace: _whitespace_re = re.compile(r'\s+') def expand_abbreviations(text): return normalize_abbreviations(text) def expand_numbers(text): return normalize_numbers(text) def expand_acronyms(text): return normalize_acronyms(text) def expand_datestime(text): return normalize_datestime(text) def expand_letters_and_numbers(text): return normalize_letters_and_numbers(text) def lowercase(text): return text.lower() def collapse_whitespace(text): return re.sub(_whitespace_re, ' ', text) def separate_acronyms(text): text = re.sub(r"([0-9]+)([a-zA-Z]+)", r"\1 \2", text) text = re.sub(r"([a-zA-Z]+)([0-9]+)", r"\1 \2", text) return text def convert_to_ascii(text): return unidecoder(text) def basic_cleaners(text): '''Basic pipeline that collapses whitespace without transliteration.''' text = lowercase(text) text = collapse_whitespace(text) return text def transliteration_cleaners(text): '''Pipeline for non-English text that transliterates to ASCII.''' text = convert_to_ascii(text) text = lowercase(text) text = collapse_whitespace(text) return text def english_cleaners(text): '''Pipeline for English text, with number and abbreviation expansion.''' text = convert_to_ascii(text) text = lowercase(text) text = expand_numbers(text) text = expand_abbreviations(text) text = collapse_whitespace(text) return text def english_cleaners_v2(text): text = convert_to_ascii(text) text = expand_datestime(text) text = expand_letters_and_numbers(text) text = expand_numbers(text) text = expand_abbreviations(text) text = spell_acronyms(text) text = lowercase(text) text = collapse_whitespace(text) # compatibility with basic_english symbol set text = re.sub(r'/+', ' ', text) return text
true
fe9ebda7c08715c0c86e9b8deb99219c387309ab
Python
fine-structure/fine-structure
/fine_structure/language_models/models.py
UTF-8
1,450
2.578125
3
[]
no_license
from tensorflow.keras import optimizers from tensorflow.keras.layers import (GRU, LSTM, Dense, Embedding, Input, SpatialDropout1D, TimeDistributed) from tensorflow.keras.models import Model def rnn_lm(input_len, vocab_size, rnn_type='GRU', embedding_size=None, num_rnn_layers=1, num_cells=16, spatial_dropout=0, optimizer='Adam', optimizer_params={'lr': 1e-3}, loss='categorical_crossentropy', metrics=['accuracy']): rnn_layer = get_rnn_layer(rnn_type) if embedding_size is None: inputs = Input(shape=(input_len, vocab_size), dtype='float32') x = inputs else: inputs = Input(shape=(input_len,), dtype='int32') x = Embedding(input_dim=vocab_size, output_dim=embedding_size, input_length=input_len, trainable=True)(inputs) if spatial_dropout > 0: x = SpatialDropout1D(spatial_dropout)(x) for i in range(num_rnn_layers): x = rnn_layer(num_cells, return_sequences=True)(x) output = TimeDistributed(Dense(vocab_size, activation='softmax'))(x) model = Model(inputs=inputs, outputs=output) optimizer = getattr(optimizers, optimizer)(**optimizer_params) model.compile(loss=loss, optimizer=optimizer, metrics=metrics) return model def get_rnn_layer(rnn_type): if rnn_type == 'GRU': return GRU elif rnn_type == 'LSTM': return LSTM
true
f4df74e598e6910f9433d1a2d265ccd4e49c72c3
Python
dzakub77/my-first-blog
/blog/forms.py
UTF-8
453
2.546875
3
[]
no_license
from django import forms from .models import Post class PostForm(forms.ModelForm): #nazwa naszego formularza, i informujermy ze ten formularz #jest formularzem module "ModelForm" class Meta: # tutaj przekazujemy informacje o tym jaki model powinien byc wykorzystany do # stworzzenia tego formularza (model=Post) model = Post fields = ('title', 'text',) # wskazujemy które pola powinny pojawic sie w naszym formularzu
true
0a6c265a46d6aa9df3442bb79f878a087100c013
Python
Go-Maun/COMP_1510_labs
/Lab06/sparse_vector.py
UTF-8
1,562
3.734375
4
[]
no_license
import doctest """ The reason we cannot get the length of a sparse vector is because they can have a large amount of 0's padding the size by a large amount. I need to ask them if storing those sparse vectors in dictionaries will work for the way they are implementing their code. """ def sparse_add(dictionary_one, dictionary_two): """creates new dictionary :param dictionary_one: the first dictionary :param dictionary_two: the second dictionary :return: the sorted list >>> sparse_add({1:8, 3:1, 4:2}, {1:1, 4:1, 6:4}) {1: 9, 3: 1, 4: 3, 6: 4} >>> sparse_add({1:2, 4:3, 9:6}, {1:-2, 5:2, 8:10}) {4: 3, 5: 2, 8: 10, 9: 6} >>> sparse_add({}, {1:5, 4:1, 5:8}) {1: 5, 4: 1, 5: 8} """ dict_output = {} for key in dictionary_one: if key in dictionary_two: dict_output[key] = dictionary_one[key] + dictionary_two[key] elif key not in dictionary_two: dict_output[key] = dictionary_one[key] for key in dictionary_two: if key not in dictionary_one: dict_output[key] = dictionary_two[key] sort = sorted(dict_output) sorted_dictionary = {} for item in sort: if dict_output[item] == 0: continue sorted_dictionary[item] = dict_output[item] return sorted_dictionary def main(): dict_one = {2: -2, 4: 4, 15: 5} dict_two = {2: 2, 5: 1, 7: 6, 13: 2} completed_dictionary = sparse_add(dict_one, dict_two) print(completed_dictionary) if __name__ == "__main__": doctest.testmod() main()
true
ade159980337c30b61cf662106bcca38c7926993
Python
itsdddaniel/POO
/II Parcial/main2.py
UTF-8
176
3.296875
3
[]
no_license
#-*- coding: utf-8 -*- import rep number = input("") number = re.sub(r"\D+","",number) if len(number)==0: number=1 else: number = int(number) print("Hola Mundo\n"*number)
true
8eba28c725a89cde39711814cd0905fef38cdacb
Python
cn5036518/xq_py
/python16/day1-21/day012 生成器/01 pdf要点总结/03 生成器表达式.py
UTF-8
584
3.015625
3
[]
no_license
#!/usr/bin/env python #-*- coding:utf-8 -*- #@time: 2019/10/7 16:17 #@author:wangtongpei '''''' ''' 1、生成器表达式:(结果 for循环 if条件) 2、惰性机制(类比:弹夹没子弹了,不能将同一个值,生成2次) 生成器是记录在内存中的一段代码,产生的时候,没有执行 生成器表达式和列表推导式的区别类比: 1、买100个鸡蛋,列表推导式:是一次性把100个鸡蛋买回来,需要地方存储 2、 生成器表达式:是买一只母鸡,需要鸡蛋就给下蛋 '''
true
675dbdb0b82d7a5cd681df3a47f1b47686ee2e35
Python
Aasthaengg/IBMdataset
/Python_codes/p02886/s982311385.py
UTF-8
212
3.09375
3
[]
no_license
n = int(input()) d = list(map(int, input().split())) recover = 0 for i in range(n): for j in range(n): if i==j: pass else: recover += d[i]*d[j] print(int(recover/2))
true
7733d1b8fe40c26dd6b36ce60153ee06aae5e180
Python
mattarroz/megamodesty
/core/dummy.py
UTF-8
145
2.59375
3
[]
no_license
import time def dummyAnalysis(): print "Hallo Welt" print "---" print "Starte DummyAnalyse..." time.sleep(5) print "Ergebnis: 42" return 42
true
fd6dbeff49cff83f7b5e8595f7d813e1592e822e
Python
UKParlDataSheets/UKParlDataSheets-Scripts
/tests.py
UTF-8
18,960
2.625
3
[]
permissive
import unittest from funcs import * # # License 3 clause BSD # https://github.com/UKParlDataSheets/UKParlDataSheets-Scripts # class TestTwitter(unittest.TestCase): def test_no_crash_on_none_1(self): """If person has an empty adddress record, test no crashes.""" person = ModelBase() address1 = ModelAddressBase() person.addresses.append(address1) self.assertEqual(person.get_twitter(), None) self.assertEqual(person.get_facebook(), None) self.assertEqual(person.get_email(), None) def test_twitter_1(self): """Tests getting Twitter when URL in Address1.""" person = ModelBase() address1 = ModelAddressBase() address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.address_1 = 'https://twitter.com/LizBarkerLords' person.addresses.append(address2) self.assertEqual(person.get_twitter(), 'LizBarkerLords') def test_twitter_2(self): """Test getting Twitter when it's in a note in one format.""" person = ModelBase() address1 = ModelAddressBase() address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.note = 'Twitter: TariqBt1' person.addresses.append(address2) self.assertEqual(person.get_twitter(), 'TariqBt1') def test_twitter_3(self): """Test getting Twitter when it's in a note in one format.""" person = ModelBase() address1 = ModelAddressBase() address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.note = 'Twitter: @lordphilofbrum' person.addresses.append(address2) self.assertEqual(person.get_twitter(), 'lordphilofbrum') def test_twitter_4(self): """Tests getting Twitter when URL in Address1, with extra params.""" person = ModelBase() address1 = ModelAddressBase() address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.address_1 = 'https://twitter.com/LordRoyKennedy?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor' person.addresses.append(address2) self.assertEqual(person.get_twitter(), 'LordRoyKennedy') def test_twitter_5(self): """Test getting Twitter when it's in a note in one format.""" person = ModelBase() address1 = ModelAddressBase() address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.note = 'Twitter - @delythjmorgan' person.addresses.append(address2) self.assertEqual(person.get_twitter(), 'delythjmorgan') def test_facebook_1(self): """Tests getting Facebook when HTTPS URL in Address1.""" person = ModelBase() address1 = ModelAddressBase() address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.address_1 = 'https://www.facebook.com/marycreaghwakefield' person.addresses.append(address2) self.assertEqual(person.get_facebook(), 'https://www.facebook.com/marycreaghwakefield') def test_facebook_2(self): """Tests getting Facebook when HTTP URL in Address1.""" person = ModelBase() address1 = ModelAddressBase() address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.address_1 = 'http://www.facebook.com/JeremyCorbynMP/' person.addresses.append(address2) self.assertEqual(person.get_facebook(), 'http://www.facebook.com/JeremyCorbynMP/') def test_facebook_3(self): """Tests getting Facebook when HTTPS URL with country/lang in Address1.""" person = ModelBase() address1 = ModelAddressBase() address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.address_1 = 'https://en-gb.facebook.com/LordAltonofLiverpool/' person.addresses.append(address2) self.assertEqual(person.get_facebook(), 'https://en-gb.facebook.com/LordAltonofLiverpool/') def test_twitter_and_facebook_1(self): """Tests getting Twitter and Facebook when combined in one note in one format.""" person = ModelBase() address1 = ModelAddressBase() address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.note = 'Twitter: @chiefrabbi, Facebook: www.facebook.com/lordsacks' person.addresses.append(address2) self.assertEqual(person.get_twitter(), 'chiefrabbi') self.assertEqual(person.get_facebook(), 'https://www.facebook.com/lordsacks') def test_twitter_and_facebook_2(self): """Tests getting Twitter and Facebook when combined in one note in one format.""" person = ModelBase() address1 = ModelAddressBase() address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.note = 'Twitter: @johnsentamu ; www.facebook.com/pages/John-Sentamu/25396296321' person.addresses.append(address2) self.assertEqual(person.get_twitter(), 'johnsentamu') self.assertEqual(person.get_facebook(), 'https://www.facebook.com/pages/John-Sentamu/25396296321') def test_email_1(self): """Tests not getting an email when a postcode is supplied instead.""" person = ModelBase() address1 = ModelAddressBase() address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() # this is some real data :-( address2.email = 'FK10 3SA' person.addresses.append(address2) self.assertEqual(person.get_email(), None) def test_email_2(self): """Test getting email when in email field.""" person = ModelBase() address1 = ModelAddressBase() address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.email = 'tas.mp@parliament.uk' person.addresses.append(address2) self.assertEqual(person.get_email(), 'tas.mp@parliament.uk') def test_email_3(self): """Test getting one email when multiple set, in one format.""" person = ModelBase() address1 = ModelAddressBase() address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.email = 'raj@loomba.com / pritti@theloombafoundation.org' person.addresses.append(address2) self.assertEqual(person.get_email(), 'raj@loomba.com') def test_email_4(self): """Test getting one email when multiple set, in one format.""" person = ModelBase() address1 = ModelAddressBase() address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.email = 'charles.allen@parliament.uk PA: gill.sharp@thisisglobal.com' person.addresses.append(address2) self.assertEqual(person.get_email(), 'charles.allen@parliament.uk') def test_email_5(self): """Test getting one email when multiple set, in one format.""" person = ModelBase() address1 = ModelAddressBase() address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.email = 'damian.gannon@parliament.uk carole.wise@parliament.uk' person.addresses.append(address2) self.assertEqual(person.get_email(), 'damian.gannon@parliament.uk') def test_email_6(self): """Test getting a email when semi colon at end https://github.com/UKParlDataSheets/UKParlDataSheets-Scripts/issues/5 """ person = ModelBase() address1 = ModelAddressBase() address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.email = 'damian.gannon@parliament.uk;' person.addresses.append(address2) self.assertEqual(person.get_email(), 'damian.gannon@parliament.uk') def test_email_peer_1(self): """Test getting an email for a Peer and ignoring contactholmember@parliament.uk.""" person = ModelPeer() address1 = ModelPeerAddress() address1.email = 'contactholmember@parliament.uk' person.addresses.append(address1) address2 = ModelPeerAddress() address2.email = 'victor@leadershipinmind.co.uk' person.addresses.append(address2) self.assertEqual(person.get_email(), 'victor@leadershipinmind.co.uk') def test_email_peer_2(self): """Test getting an email for a Peer and ignoring contactholmember@parliament.uk when extra padding in input.""" person = ModelPeer() address1 = ModelPeerAddress() # note space at end - real data address1.email = 'contactholmember@parliament.uk ' person.addresses.append(address1) address2 = ModelPeerAddress() address2.email = 'victor@leadershipinmind.co.uk' person.addresses.append(address2) self.assertEqual(person.get_email(), 'victor@leadershipinmind.co.uk') def test_get_parliamentary_phone_and_fax_1(self): """Get Phone or Fax from Phone and Fax fields.""" person = ModelBase() address1 = ModelAddressBase() address1.type = 'External/Private Office' address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.type = 'Parliamentary' address2.phone = '0207 219 2807' address2.fax = '020 7219 5979' person.addresses.append(address2) self.assertEqual(person.get_parliamentary_phone(), '0207 219 2807') self.assertEqual(person.get_parliamentary_fax(), '020 7219 5979') def test_get_parliamentary_phone_and_fax_2(self): """Get Phone or Fax when both in Phone field, in one format.""" person = ModelBase() address1 = ModelAddressBase() address1.type = 'External/Private Office' address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.type = 'Parliamentary' address2.phone = '020 7219 1041 Fax: 0207 219 2405' person.addresses.append(address2) self.assertEqual(person.get_parliamentary_phone(), '020 7219 1041') self.assertEqual(person.get_parliamentary_fax(), '0207 219 2405') def test_get_parliamentary_phone_and_fax_3(self): """Get Phone or Fax when several phone numbers in input, in one format.""" person = ModelBase() address1 = ModelAddressBase() address1.type = 'External/Private Office' address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.type = 'Parliamentary' address2.phone = '020 7219 3547, 020 7219 5099' address2.fax = '020 7219 4614' person.addresses.append(address2) self.assertEqual(person.get_parliamentary_phone(), '020 7219 3547') self.assertEqual(person.get_parliamentary_fax(), '020 7219 4614') def test_get_parliamentary_phone_and_fax_4(self): """Get Phone or Fax when several phone numbers in input, in one format.""" person = ModelBase() address1 = ModelAddressBase() address1.type = 'External/Private Office' address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.type = 'Parliamentary' address2.phone = '020 7219 4432; 020 7219 6306' address2.fax = '020 7219 5952' person.addresses.append(address2) self.assertEqual(person.get_parliamentary_phone(), '020 7219 4432') self.assertEqual(person.get_parliamentary_fax(), '020 7219 5952') def test_get_parliamentary_phone_and_fax_5(self): """Get Phone or Fax when Fax in Phone field and several phone numbers in input, in one format.""" person = ModelBase() address1 = ModelAddressBase() address1.type = 'External/Private Office' address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.type = 'Parliamentary' address2.phone = '020 7219 5135; 020 7219 2088; Fax 020 7219 4780' address2.fax = '' person.addresses.append(address2) self.assertEqual(person.get_parliamentary_phone(), '020 7219 5135') self.assertEqual(person.get_parliamentary_fax(), '020 7219 4780') def test_get_parliamentary_phone_and_fax_6(self): """Test not getting Phone when Phone not in London and multiple phones.""" person = ModelBase() address1 = ModelAddressBase() address1.type = 'External/Private Office' address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.type = 'Parliamentary' address2.phone = '01709 331035/331036' address2.fax = '' person.addresses.append(address2) self.assertEqual(person.get_parliamentary_phone(), None) self.assertEqual(person.get_parliamentary_fax(), None) def test_get_parliamentary_phone_and_fax_7(self): """Test getting phone with extra data in input.""" person = ModelBase() address1 = ModelAddressBase() address1.type = 'External/Private Office' address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.type = 'Parliamentary' address2.phone = '020 7219 4936 (Office contact)' address2.fax = '' person.addresses.append(address2) self.assertEqual(person.get_parliamentary_phone(), '020 7219 4936') self.assertEqual(person.get_parliamentary_fax(), None) def test_get_parliamentary_phone_and_fax_8(self): """Test not getting Phone when Phone not in London.""" person = ModelBase() address1 = ModelAddressBase() address1.type = 'External/Private Office' address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.type = 'Parliamentary' address2.phone = '01308 456891' address2.fax = '' person.addresses.append(address2) self.assertEqual(person.get_parliamentary_phone(), None) self.assertEqual(person.get_parliamentary_fax(), None) def test_get_parliamentary_phone_and_fax_9(self): """Test getting London Phone when other phone specified first.""" person = ModelBase() address1 = ModelAddressBase() address1.type = 'External/Private Office' address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.type = 'Parliamentary' address2.phone = '0777 556 2776 / 020 7219 5353' address2.fax = '' person.addresses.append(address2) self.assertEqual(person.get_parliamentary_phone(), '020 7219 5353') self.assertEqual(person.get_parliamentary_fax(), None) def test_get_parliamentary_phone_and_fax_10(self): """Get Phone or Fax when both in Phone field, in one format.""" person = ModelBase() address1 = ModelAddressBase() address1.type = 'External/Private Office' address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.type = 'Parliamentary' address2.phone = '020 7219 5480 Fax. 020 7219 5979' address2.fax = '' person.addresses.append(address2) self.assertEqual(person.get_parliamentary_phone(), '020 7219 5480') self.assertEqual(person.get_parliamentary_fax(), '020 7219 5979') def test_get_parliamentary_phone_and_fax_11(self): """Test getting phone with extra data in input.""" person = ModelBase() address1 = ModelAddressBase() address1.type = 'External/Private Office' address1.address_1 = 'My House' address1.address_2 = 'My Street' person.addresses.append(address1) address2 = ModelAddressBase() address2.type = 'Parliamentary' address2.phone = 'Tel: 020 7219 5353' address2.fax = '' person.addresses.append(address2) self.assertEqual(person.get_parliamentary_phone(), '020 7219 5353') self.assertEqual(person.get_parliamentary_fax(), None) def test_get_constituency_postal_address_1(self): """Test getting Constituency address when address set.""" person = ModelMP() address1 = ModelMPAddress() address1.type = 'Parliamentary' address1.address_1 = 'House of Commons' person.addresses.append(address1) address2 = ModelMPAddress() address2.type = 'Constituency' address2.address_1 = '94A Town Street' address2.address_2 = 'Horsforth' person.addresses.append(address2) self.assertEquals(person.get_constituency_postal_address().address_1, '94A Town Street') def test_get_constituency_postal_address_2(self): """Test not getting Constituency address when it is not publicised.""" person = ModelMP() address1 = ModelMPAddress() address1.type = 'Parliamentary' address1.address_1 = 'House of Commons' person.addresses.append(address1) address2 = ModelMPAddress() address2.type = 'Constituency' address2.address_1 = 'No constituency office publicised' person.addresses.append(address2) self.assertEquals(person.get_constituency_postal_address(), None) if __name__ == '__main__': unittest.main()
true
9f0853658af5264a07fb83877601417581d3c35a
Python
bac1986/botTenderRevising
/python_serial_test.py
UTF-8
1,644
2.6875
3
[]
no_license
import time import serial arduino = serial.Serial() arduino.port = 'COM5' arduino.baudrate = 9600 arduino.timeout = 0.1 arduino.setRTS(False) arduino.open() arduino.flush() #outgoing = "Hi\n" #arduino.write(outgoing.encode()) #print(outgoing) #arduino.flush() #while True: # print("Hello from Raspberry Pi!") # arduino.write(b"Hello from Raspberry Pi!\n") # line = arduino.readline().decode('utf-8').rstrip() # print(line) # time.sleep(1) # #if arduino.in_waiting > 0: # #line = arduino.readline().decode('utf-8').rstrip() # #print(line) while True: incoming = arduino.read() print(int.from_bytes(incoming, byteorder='big')) if incoming != b'': if int.from_bytes(incoming, byteorder='big') == 10: arduino.write(b"bay1\n") print("bay 1") elif int.from_bytes(incoming, byteorder='big') == 1: arduino.write(b"bay2\n") elif int.from_bytes(incoming, byteorder='big') == 2: arduino.write(b"bay3\n") elif int.from_bytes(incoming, byteorder='big') == 3: arduino.write(b"bay4\n") elif int.from_bytes(incoming, byteorder='big') == 4: arduino.write(b"bay5\n") elif int.from_bytes(incoming, byteorder='big') == 5: arduino.write(b"bay6\n") elif int.from_bytes(incoming, byteorder='big') == 6: arduino.write(b"Good Talk!\n") print("Complete!") arduino.flush() elif int.from_bytes(incoming, byteorder='big') == 16: print("Arduino Waiting!") else: arduino.write(b"listen\n") print("calling")
true
77bfc2c8df6145ef8116e9a6f0334788ed7ebc26
Python
prathamtandon/g4gproblems
/Sorting and Searching/min_length_unsorted_subarray.py
UTF-8
2,085
4.84375
5
[ "MIT" ]
permissive
import unittest """ Given an unsorted array arr[0...n-1] of size n, find the minimum length subarray arr[s...e] such that sorting this subarray makes the whole array sorted. Input: 10 12 20 30 25 40 32 31 35 50 60 Output: subarray starting index 3 and ending index 8. """ """ Approach: 1. Scan from left to right and find the first element which is out of place (ie element is smaller than its predecessor). Note its index. 2. Scan from right to left and find the first element which is out of place (ie element is larger than its predecessor). Note its index. 3. This gives us a candidate subarray. Now, we need to find if this is minimum length or not. 4. Find minimum and maximum values in candidate subarray. 5. Scan from start of subarray towards left, if there is an element which is larger than minimum, then set start of subarray at this element. 6. Similarly, scan from end of subarray towards right, if there is an element which is smaller than maximum, then set end of subarray at this element. """ def min_length_unsorted_subarray(arr): n = len(arr) start = 0 end = n-1 while start < n-1 and arr[start] <= arr[start+1]: start += 1 while end > 0 and arr[end] >= arr[end-1]: end -= 1 if start == n-1 and end == 0: return None min_ele = min(arr[start:end+1]) max_ele = max(arr[start:end+1]) i = 0 while i < start: if arr[i] > min_ele: break i += 1 if i != start: start = i j = n-1 while j > end: if arr[j] < max_ele: break j -= 1 if j != end: end = j return start, end class TestMinLength(unittest.TestCase): def test_min_length(self): arr = [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60] start, end = min_length_unsorted_subarray(arr) self.assertEqual(start, 3) self.assertEqual(end, 8) arr = [0, 1, 15, 25, 6, 7, 30, 40, 50] start, end = min_length_unsorted_subarray(arr) self.assertEqual(start, 2) self.assertEqual(end, 5)
true
365560be63d63dc05df0c4cf2067cf8e0b0cd58c
Python
mikebwin/Android-RPi-Wifi
/raspberry-pi-code/lock.py
UTF-8
299
3.09375
3
[]
no_license
import RPi.GPIO as GPIO import time servoPIN = 23 GPIO.setmode(GPIO.BCM) GPIO.setup(servoPIN, GPIO.OUT) p = GPIO.PWM(servoPIN, 50) # GPIO 23 for PWM with 50Hz p.start(7.5) # Initialization time.sleep(0.5) # 90 degrees p.ChangeDutyCycle(2.5) print(2.5) time.sleep(2) p.stop() GPIO.cleanup()
true
536fb3944bb8bae179345705336a19f47b3130b7
Python
yoongi0428/dmlab_torch_tutorial
/3. Recommender System/utils/data_utils.py
UTF-8
1,780
2.984375
3
[ "Apache-2.0" ]
permissive
import numpy as np import torch def load_data(data_path, implicit=False, train_ratio=0.8, shuffle=True): # x = np.loadtxt(data_path, skiprows=0, delimiter=',') raw = [s.split(',') for s in open(data_path, 'rt', encoding='utf-8').read().strip().split('\n')] columns = raw[0] data = raw[1:] process_func = [int, int, float, int] data = np.array([[f(x) for x, f in zip(row, process_func)] for row in data]) users, items, ratings, timestamps = [np.array(data[:, i], dtype=process_func[i]) for i in range(len(columns))] if implicit: idx = np.where(ratings > 0) ratings[idx] = 1 num_users = int(max(users)) num_items = int(max(items)) users -= 1 items -= 1 train, test = _split(users, items, ratings, timestamps, train_ratio, shuffle) return train, test, num_users, num_items def _split(u, i, r, t, train_ratio, shuffle): data_len = len(u) if shuffle: perm = np.random.permutation(data_len) else: perm = np.arange(data_len) train_len = int(data_len*train_ratio) train_idx = perm[:train_len] test_idx = perm[train_len:] train_data = (u[train_idx], i[train_idx], r[train_idx], t[train_idx]) test_data = (u[test_idx], i[test_idx], r[test_idx], t[test_idx]) return train_data, test_data def build_matrix(users, items, ratings, num_users, num_items): full_matrix = torch.zeros((num_users, num_items), dtype=torch.float32) for u, i, r in zip(users, items, ratings): full_matrix[u, i] = r return full_matrix if __name__ == "__main__": train, test, num_users, num_items = load_data('../data/ratings_sm.csv', implicit=True) print('%d Users, %d Items, %d Ratings loaded' % (num_users, num_items, len(train[0]) + len(test[0])))
true
b0d34face58703d8bb8bfe3d0b5a5b7021bdaf8c
Python
Taylor-Yang1992/Algorithm
/leetcode/Palindrome Number.py
UTF-8
262
3.046875
3
[]
no_license
class Solution: def isPalindrome(self,x): if x == 0: return True elif x < 0 or x% 10 == 0: return False t = 0 while t <= x: if t == x or t == int(x / 10): return True mode = x % 10 t = t * 10 + mode x = int(x / 10) return False
true
5ecf0341c9e174f17b0fc91cd7f6aa7742b6fb6d
Python
yurimalheiros/IP-2019-2
/lista3/ighor/questao4.py
UTF-8
173
3.640625
4
[]
no_license
numero = int(input("Digite um número")) acumulador = 0 while numero != 0: acumulador += numero numero = int(input("Digite um número")) print(acumulador)
true
ef9ce2e4367ab569093e2397dfbdce93e3960618
Python
richnakasato/ctci-py
/min_coins.py
UTF-8
1,174
3.453125
3
[]
no_license
import random def min_coins(coins, val): memo = dict() for coin in coins: memo[coin] = 1 memo[0] = 0 return min_coins_helper(coins, val, memo) def min_coins_helper(coins, val, memo): if val in memo: return memo[val] else: min_count = float('inf') for coin in coins: if val - coin >= 0: curr_count = 1 + min_coins_helper(coins, val-coin, memo) if curr_count < min_count: min_count = curr_count memo[val] = min_count return min_count def n_ways(coins, val): memo = dict() memo[0] = 1 memo[1] = 1 memo[5] = 2 memo[10] = 4 memo[25] = 13 return n_ways_helper(coins, val, memo) def n_ways_helper(coins, val, memo): if val in memo: return memo[val] else: count = 0 for coin in coins: if val - coin >= 0: count += n_ways_helper(coins, val-coin, memo) memo[val] = count return count def main(): coins = [1, 5, 10, 25] val = 7 print(min_coins(coins, val)) print(n_ways(coins, val)) if __name__ == "__main__": main()
true
7dd4299c6020b8e2b1913181a0f32f0cad561b2f
Python
ZubritskiyAlex/Python-Tasks
/HW_10/task 10_02.py
UTF-8
1,348
3.65625
4
[]
no_license
"""Создать csv файл с данными о ежедневной погоде. Структура: Дата, Место, Градусы, Скорость ветра. Найти среднюю погоду(скорость ветра и градусы) для Минск за последние 7 дней.""" import csv list_of_speed = [] list_of_degr = [] def print_csv_file(filename): with open(f"{filename}.csv") as my_file: for line in my_file.readlines(): print(line) def open_file_for_read_and_data_collection(filename:str, list_of_speed, list_of_degr:list): with open(f"{filename}.csv") as my_file: csvreader = csv.reader(my_file) for line in csvreader: list_of_degr.append(line[2]) list_of_speed.append(line[3]) result_of_speed = list(map(int, list_of_speed)) result_of_degr = list(map(int, list_of_degr)) return result_of_speed, result_of_degr def calculate_average(value:list) -> str: return f"The average value is {sum(value) / len(value)}" result_of_speed, result_of_degr = open_file_for_read_and_data_collection("10_02", list_of_speed, list_of_degr) print_csv_file("10_02") open_file_for_read_and_data_collection("10_02", list_of_speed, list_of_degr) print(calculate_average(result_of_speed), calculate_average(result_of_degr))
true
147d9c6c42cdd9b9cca333f3cd78612f6e80f075
Python
dimitrovs/comp598
/load_training_data.py
UTF-8
832
3.03125
3
[]
no_license
import numpy as np import csv # Load all training inputs to a python list train_inputs = [] with open('train_inputs.csv', 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',') next(reader, None) # skip the header for train_input in reader: train_input_no_id = [] for pixel in train_input[1:]: # Start at index 1 to skip the Id train_input_no_id.append(float(pixel)) train_inputs.append(train_input_no_id) # Load all training ouputs to a python list train_outputs = [] with open('train_outputs.csv', 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',') next(reader, None) # skip the header for train_output in reader: train_output_no_id = int(train_output[1]) train_outputs.append(train_output_no_id) print "Finished succesfully!"
true
8b391e0b4674cee2a408fe4c82eef90aa9cb6585
Python
roy19-meet/meet2017y1lab6
/funturtle.py
UTF-8
511
3.65625
4
[ "MIT" ]
permissive
import turtle turtle.shape('turtle') square=turtle.clone() square.shape('square') square.goto(0,100) square.goto(100,100) square.goto(100,0) square.goto(0,0) triangle=turtle.clone() triangle.shape('classic') triangle.penup() triangle.goto(100,200) triangle.pendown() triangle.goto(0,200) triangle.goto(50,250) triangle.goto(100,200) square.penup() square.goto(-150,-100) square.stamp() square.goto(-200,-100) triangle.penup() triangle.goto(-200,200) triangle.stamp() triangle.goto(-200,150) turtle.mainloop()
true
d3a993be69bcab653c25858d2f6894d4fd864aa2
Python
Marcin-Szadkowski/JFTT-kompilator
/AST/identifiers/array_pid.py
UTF-8
2,203
2.953125
3
[]
no_license
from AST.declarations.array import Array from compiler.asm import Asm from compiler.memory import Memory from compiler.reg_manager import RegManager from compiler.exceptions import IsAnArrayError class ArrayPid: def __init__(self, pid, pid2, line=0): self.pid = pid self.pid2 = pid2 self.line = line def compile(self, code, reg): """Ladujemy do rejestru wartosc zmiennej tablica[index]""" array = Memory.get_var_by_pid(self.pid, self.line) var = Memory.get_var_by_pid(self.pid2, self.line) start_adr = array.memory_addr # wartosc ladujemy do rejestru reg reg_temp = RegManager.get_free_register() if not isinstance(array, Array): raise IsAnArrayError(self) var.compile(code, reg_temp) # reg_temp <- wartosc var code.set_value_in_register(array.left_range, reg) code.add_instr(Asm.SUB(reg_temp, reg)) code.set_value_in_register(start_adr, reg) code.add_instr(Asm.ADD(reg_temp, reg)) code.add_instr(Asm.LOAD(reg, reg_temp)) # reg <- p[reg_temp] # Zwolnienie rejestru RegManager.free_register(reg_temp) def load_addr_to_reg(self, code, reg): """ Ladujemy do rejetru adres zmiennej To wlasciwie do uzytku tylko do operacji przypisania, ale osobna funkcja duzo ulatwia """ """Ladujemy do rejestru wartosc zmiennej tablica[index]""" array = Memory.get_var_by_pid(self.pid, self.line) var = Memory.get_var_by_pid(self.pid2, self.line) if not isinstance(array, Array): raise IsAnArrayError(self) start_adr = array.memory_addr # wartosc ladujemy do rejestru reg reg_temp = RegManager.get_free_register() var.compile(code, reg_temp) # reg_temp <- wartosc var code.set_value_in_register(array.left_range, reg) code.add_instr(Asm.SUB(reg_temp, reg)) code.set_value_in_register(start_adr, reg) code.add_instr(Asm.ADD(reg, reg_temp)) # reg <- reg + reg_temp = addr tab[i] # Zwolnienie rejestru RegManager.free_register(reg_temp) def __str__(self): return self.pid
true
cea04b60a5dc29cf97da4782a4d227fbbad780ba
Python
noaavi94/tdh20
/utils.py
UTF-8
2,146
3.046875
3
[]
no_license
import functools import math import operator import re import time from collections import Counter from nltk.corpus import names labeled_names = ([(name, 'male') for name in names.words('male.txt')] + [(name, 'female') for name in names.words('female.txt')]) def counter_wrapper(c, key): if c.get(key) is None: return 0 return c.get(key) def is_male_name(name): male_names = [s.lower() for s in names.words('male.txt')] print(male_names[:50]) return name in male_names def is_female_name(name): female_names = [s.lower() for s in names.words('female.txt')] return name in female_names def is_male_story(plot): plot = plot.split(" ") plot = [re.sub(r'[^\w\s]', '', s) for s in plot] #remove punctuation plot = [ s.lower() for s in plot] #change all words to lower case c = Counter(plot) male_signs_str = ["he", "his", "him", "man", "men", "brother", "brothers", "father", "fathers", "king", "kings","cowboy", "cowboys", "boy", "boys", "son"] female_signs_str =["she", "her", "women", "woman", "sister", "sisters", "mother", "mothers","daughter", "queen", "queens", "lady"] male_count = functools.reduce(operator.add, [counter_wrapper(c, name) for name in male_signs_str]) female_count = functools.reduce(operator.add, [counter_wrapper(c, name) for name in female_signs_str]) male_names = [s.lower() for s in names.words('male.txt')] female_names = [s.lower() for s in names.words('female.txt')] #adding to the signs any appearance of male or female names male_count += functools.reduce(operator.add, [counter_wrapper(c, name) for name in male_names]) female_count += functools.reduce(operator.add, [counter_wrapper(c, name) for name in female_names]) return male_count >= female_count def timeSince(since): now = time.time() s = now - since m = math.floor(s / 60) s -= m * 60 return '%dm %ds' % (m, s)
true
f48ce8309a97654705b4d4a85e5ecb7521d650ed
Python
hugovk/pescador
/tests/test_core.py
UTF-8
8,647
2.640625
3
[ "ISC" ]
permissive
#!/usr/bin/env python '''Test the streamer object for reusable iterators''' from __future__ import print_function import copy import pytest import warnings warnings.simplefilter('always') import pescador.core import test_utils as T def test_streamer_iterable(): n_items = 10 expected = list(range(n_items)) streamer = pescador.core.Streamer(expected) # Test generate interface actual1 = list(streamer) assert len(expected) == len(actual1) == n_items for b1, b2 in zip(expected, actual1): assert b1 == b2 # Test __iter__ interface actual2 = list(streamer) assert len(expected) == len(actual2) == n_items for b1, b2 in zip(expected, actual2): assert b1 == b2 def test_streamer_generator_func(): n_items = 10 expected = list(T.finite_generator(n_items)) streamer = pescador.core.Streamer(T.finite_generator, n_items) # Test generate interface actual1 = list(streamer) assert len(expected) == len(actual1) == n_items for b1, b2 in zip(expected, actual1): T._eq_batch(b1, b2) # Test __iter__ interface actual2 = list(streamer) assert len(expected) == len(actual2) == n_items for b1, b2 in zip(expected, actual2): T._eq_batch(b1, b2) @pytest.mark.parametrize('n_max', [None, 10, 50, 100]) @pytest.mark.parametrize('stream_size', [1, 2, 7]) @pytest.mark.parametrize('generate', [False, True]) def test_streamer_finite(n_max, stream_size, generate): reference = list(T.finite_generator(50, size=stream_size)) if n_max is not None: reference = reference[:n_max] streamer = pescador.core.Streamer(T.finite_generator, 50, size=stream_size) if generate: gen = streamer.iterate(max_iter=n_max) else: gen = streamer(max_iter=n_max) for i in range(3): query = list(gen) for b1, b2 in zip(reference, query): T._eq_batch(b1, b2) @pytest.mark.parametrize('n_max', [10, 50]) @pytest.mark.parametrize('stream_size', [1, 2, 7]) def test_streamer_infinite(n_max, stream_size): reference = [] for i, data in enumerate(T.infinite_generator(size=stream_size)): if i >= n_max: break reference.append(data) streamer = pescador.core.Streamer(T.infinite_generator, size=stream_size) for i in range(3): query = list(streamer.iterate(max_iter=n_max)) for b1, b2 in zip(reference, query): T._eq_batch(b1, b2) @pytest.mark.parametrize('n_max', [10, 50]) @pytest.mark.parametrize('stream_size', [1, 2, 7]) def test_streamer_in_streamer(n_max, stream_size): # TODO minimize copypasta from above test. reference = [] for i, data in enumerate(T.infinite_generator(size=stream_size)): if i >= n_max: break reference.append(data) streamer = pescador.core.Streamer(T.infinite_generator, size=stream_size) streamer2 = pescador.core.Streamer(streamer) for i in range(3): query = list(streamer2.iterate(max_iter=n_max)) for b1, b2 in zip(reference, query): T._eq_batch(b1, b2) @pytest.mark.parametrize('generate', [False, True]) def test_streamer_cycle(generate): """Test that a limited streamer will die and restart automatically.""" stream_len = 10 streamer = pescador.core.Streamer(T.finite_generator, stream_len) assert streamer.stream_ is None # Exhaust the stream once. query = list(streamer) assert stream_len == len(query) # Now, generate from it infinitely using cycle. # We're going to assume "infinite" == > 5*stream_len count_max = 5 * stream_len data_results = [] if generate: gen = streamer.cycle() else: gen = streamer(cycle=True) for i, x in enumerate(gen): data_results.append(isinstance(x, dict) and 'X' in x) if (i + 1) >= count_max: break assert (len(data_results) == count_max and all(data_results)) @pytest.mark.parametrize('max_iter', [3, 10]) def test_streamer_cycle_maxiter(max_iter): s = pescador.Streamer(T.finite_generator, 6) r1 = list(s.cycle(max_iter=max_iter)) assert len(r1) == max_iter r2 = list(s(max_iter=max_iter, cycle=True)) assert len(r2) == max_iter def test_streamer_bad_function(): def __fail(): return 6 with pytest.raises(pescador.core.PescadorError): pescador.Streamer(__fail) def test_streamer_copy(): stream_len = 10 streamer = pescador.core.Streamer(T.finite_generator, stream_len) s_copy = copy.copy(streamer) assert streamer is not s_copy assert streamer.streamer is s_copy.streamer assert streamer.args is s_copy.args assert streamer.kwargs is s_copy.kwargs assert streamer.active_count_ == s_copy.active_count_ assert streamer.stream_ is s_copy.stream_ def test_streamer_deepcopy(): stream_list = list(range(100)) stream_len = (10,) kwargs = dict(a=10, b=20, c=30) # As stream_list is not callable, the streamer won't actually pass the # args or kwargs to it, but we can still check if they got copied! streamer = pescador.core.Streamer(stream_list, *stream_len, **kwargs) s_copy = copy.deepcopy(streamer) assert streamer is not s_copy assert streamer.streamer is not s_copy.streamer # args is a tuple and is immutable, so it won't actually get deepcopied. assert streamer.args is s_copy.args # But the kwargs dict will get a correct deepcopy. assert streamer.kwargs is not s_copy.kwargs assert streamer.streamer == s_copy.streamer assert streamer.args == s_copy.args assert streamer.kwargs == s_copy.kwargs assert streamer.active_count_ == s_copy.active_count_ assert streamer.stream_ == s_copy.stream_ def test_streamer_context_copy(): """Check that the streamer produced by __enter__/activate is a *different* streamer than the original. Note: Do not use the streamer in this way in your code! You can't actually extract samples from the streamer using the context manager externally. """ stream_len = 10 streamer = pescador.core.Streamer(T.finite_generator, stream_len) assert streamer.stream_ is None assert streamer.active == 0 with streamer as active_stream: # the original streamer should be makred active now assert streamer.active == 1 # The reference shouldn't be active assert active_stream.active == 0 assert isinstance(active_stream, pescador.core.Streamer) # Check that the objects are not the same assert active_stream is not streamer assert streamer.stream_ is None # The active stream should have been activated. assert active_stream.stream_ is not None assert active_stream.streamer == streamer.streamer assert active_stream.args == streamer.args assert active_stream.kwargs == streamer.kwargs assert active_stream.is_activated_copy is True # Now, we should be able to iterate on active_stream without it # causing another copy. with active_stream as test_stream: assert active_stream is test_stream assert streamer.active == 1 # Exhaust the stream once. query = list(active_stream) assert stream_len == len(query) assert streamer.active == 0 def test_streamer_context_multiple_copies(): """Check that a streamer produced by __enter__/activate multiple times yields streamers *different* than the original. """ stream_len = 10 streamer = pescador.core.Streamer(T.finite_generator, stream_len) assert streamer.stream_ is None assert streamer.active == 0 # Active the streamer multiple times with iterate gen1 = streamer.iterate(5) gen2 = streamer.iterate(7) assert id(gen1) != id(gen2) # No streamers should be active until we actually start the generators assert streamer.active == 0 # grab one sample each to make sure we've actually started the generator _ = next(gen1) _ = next(gen2) assert streamer.active == 2 # the first one should die after four more samples result1 = list(gen1) assert len(result1) == 4 assert streamer.active == 1 # The second should die after 6 result2 = list(gen2) assert len(result2) == 6 assert streamer.active == 0 def test_decorator(): @pescador.streamable def my_generator(n): for i in range(n): yield i s = my_generator(5) assert isinstance(s, pescador.Streamer) assert list(s) == [0, 1, 2, 3, 4]
true
01de874c5539a2c86fc506cb4effa829d43b5599
Python
tfhartmann/moc-public
/python-mocutils/mocutils/db_controls.py
UTF-8
11,435
2.578125
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/pyton import sys, os, sqlite3, re, itertools import switch_controls class DB_Controller: def __init__(self, db): # Check if the db already exists new = not os.path.exists(db) # Build the connection to the db self.conn = sqlite3.connect(db) if new: self._create_tables() # Add init machines for line in open(raw_input("File of machine listing:"), 'r'): line = line.rstrip() node_id, mac, node_ip = line.split(' ') self.add_machine_to_db(node_id, mac, node_ip) # Add init vlans for vlan in raw_input("Vlan list:").split(','): if '-' not in vlan: self.add_remove_vlan_to_db(int(vlan), True) else: parts = vlan.split('-') map(lambda x: self.add_remove_vlan_to_db(x, True), range(int(parts[0]), int(parts[1])+1)) # Add init head nodes for name in open(raw_input("File of head node listing:"), 'r'): self.add_head_node_to_db(name.rstrip()) # Now we want to query the switch and ensure that the db and switch agree # If the db has more than switch, alert user to problem # Print switch and db states, and ask who should adopt what # If switch has more than db, alert unowned vlans, but allow to continue return def _create_tables(self): #For initializing a non-existant db c = self.conn.cursor() #The port connected to the node is not fixed c.execute('''CREATE TABLE nodes (node_id integer primary key, port_id integer, mac_addr string, manage_ip string, available integer, group_name string)''') c.execute('''CREATE TABLE groups (group_name string primary key, network_id integer, vm_name string)''') c.execute('''CREATE TABLE vms (vm_name string primary key, available integer)''') c.execute('''CREATE TABLE ports (port_id integer primary key, switch_id integer, port_no integer)''') #network technology, vlan or openflow,etc c.execute('''CREATE TABLE networks (network_id integer primary key, network_technology string, available integer)''') #Different switch model runs different script to setup VLAN c.execute('''CREATE TABLE switches (switch_id integer primary key, vendor_script string)''') def show_group(self, name): if not self.check_exists('groups', 'group_name', name): print "Group", name, "does not exist" return c = self.conn.cursor() c.execute('select * from groups where group_name = ?', (name,)) print 'Group:\n', c.fetchone() print 'Nodes:' c.execute('select * from nodes where group_name = ?', (name,)) for row in c.fetchall(): print row print '' def show_db(self, free, spec_table=''): # Open two cursors into the db # Unfortunately 2 are needed to manage 2 loops c = self.conn.cursor() tmp = self.conn.cursor() # Select and loop over all the tables tmp.execute("select name from sqlite_master where type = 'table'") print '' for table in tmp.fetchall(): table = table[0] if free and table == 'groups': continue if spec_table and table != spec_table: continue print table # Select and print all the column names from the current table c.execute("PRAGMA table_info(" + table +")") for column in c.fetchall(): print column[1], '|', print '' # Select every row from the current table and print it (if free) c.execute("select * from " + table) ### Warning: Cluster fuck below, to be fixed later, functional for now # Problem is getting val_name, fix db entries? for row in c.fetchall(): if free: if table == "nodes": if self.check_available(table, "node_id", row[0]): print row elif table == "vlans": if self.check_available(table, "vlan_id", row[0]): print row elif table == "vms": if self.check_available(table, "vm_name", row[0]): print row else: print row print '' def check_exists(self, table, val_name, val_id): c = self.conn.cursor() c.execute("SELECT EXISTS(SELECT 1 FROM " + table + " WHERE " + val_name + "=? LIMIT 1)", (val_id,)) return c.fetchone()[0] def check_available(self, table, val_name, val_id): # First make sure it exists if not self.check_exists(table, val_name, val_id): print val_name, val_id, "does not exist" return c = self.conn.cursor() # Checks if the desired value is available for allocation c.execute('select available from ' + table + ' where ' + val_name + ' = ?', (val_id,)) return c.fetchone()[0] def add_machine_to_db(self, node_id, mac, node_ip): # Make sure the node_id isn't already taken if self.check_exists('nodes', 'node_id', node_id): print "node_id", node_id, "is already taken" return c = self.conn.cursor() c.execute('''INSERT INTO nodes values(?,?,?,1,'none')''', (node_id, mac, node_ip,)) def add_remove_vlan_to_db(self, vlan_id, add): # Make sure this isn't already a vlan exists = self.check_exists('vlans', 'vlan_id', vlan_id) if add and exists or not (add or exists): print "Error: vlan_id", vlan_id, "not available" return c = self.conn.cursor() if add: c.execute('''INSERT INTO vlans values(?,1)''',(vlan_id,)) else: c.execute('delete from vlans where vlan_id = ?', (vlan_id,)) return def add_head_node_to_db(self, name): # Make sure the head_node isn't already taken if self.check_exists('vms', 'vm_name', name): print "head_node_id", name, "is already taken" return c = self.conn.cursor() c.execute('''INSERT INTO vms values(?,1)''', (name,)) def create_group(self, group_name, vlan_id, vm_name): try: # Make sure that there isn't already a group with this name if self.check_exists('groups', 'group_name', group_name): print "Group", group_name, "already exists." return False # Make sure that the vlan asked for is available if not self.check_available('vlans', 'vlan_id', vlan_id): print "vlan id not available" return False # Make sure that the vm asked for is available if not self.check_available('vms', 'vm_name', vm_name): print "vm not available" return False c = self.conn.cursor() c.execute('update vlans set available = 0 where vlan_id = ?', (vlan_id,)) c.execute('update vms set available = 0 where vm_name = ?', (vm_name,)) c.execute('insert into groups values(?,?,?)', (group_name, vlan_id, vm_name,)) return True except: print "Creating group failed." print "Unexpected error:", sys.exc_info()[0] return False def remove_group(self, group_name): try: # Ensure that group_name is a valid group if not self.check_exists('groups', 'group_name', group_name): print "Group", group_name, "does not exist." return False # Get the vlan_id and vm_name from this group c = self.conn.cursor() c.execute('select vlan_id, vm_name from groups where group_name = ?', (group_name,)) vlan_id, vm_name = c.fetchone() # Release the vlan and vm from the group c.execute('update vlans set available = 1 where vlan_id = ?', (vlan_id,)) c.execute('update vms set available = 1 where vm_name = ?', (vm_name,)) # Get and release the nodes which are assigned to this group c.execute('select node_id from nodes where group_name = ?', (group_name,)) for node in c.fetchall(): print "Removing node", node c.execute('update nodes set available = 1, group_name = ? where node_id = ?', ('none', node[0],)) # Remove the group c.execute('delete from groups where group_name = ?', (group_name,)) return True except: print "Removing group failed." print "Unexpected error:", sys.exc_info()[0] return False def move_nodes_group(self, node_ids, group_name, add): # Unroll the group name and node we want for node_id in node_ids.split(','): node_id = int(node_id) # Make sure that the node asked for is available if add and not self.check_available('nodes', 'node_id', node_id): print "ERROR: node id", node_id, "not available" continue # Add / remove the node from the desired group c = self.conn.cursor() c.execute('update nodes set available=?, group_name=? where node_id=?', (1-add, group_name, node_id,)) return True def change_vlan(self, group_name, vlan_id): # Make sure the group exists if not self.check_exists('groups', 'group_name', group_name): print "Group", group_name, "does not exist." return # Make sure the new vlan wanted is available if not self.check_available('vlans', 'vlan_id', vlan_id): print "Vlan", vlan_id, "not available" return c = self.conn.cursor() # Get the old vlan to be marked as available c.execute('select vlan_id from groups where group_name = ?', (group_name,)) old = c.fetchone()[0] # Update the group c.execute('update groups set vlan_id=? where group_name=?', (vlan_id, group_name,)) # Toggle availability c.execute('update vlans set available=0 where vlan_id=?', (vlan_id,)) c.execute('update vlans set available=1 where vlan_id=?', (old,)) def change_head(self, group_name, vm_name): # Make sure the group exists if not self.check_exists('groups', 'group_name', group_name): print "Group", group_name, "does not exist." return # Make sure the new vlan wanted is available if not self.check_available('vms', 'vm_name', vm_name): print "Vm", vm_name, "not available" return c = self.conn.cursor() # Get the old vlan to be marked as available c.execute('select vm_name from groups where group_name = ?', (group_name,)) old = c.fetchone()[0] # Update the group c.execute('update groups set vm_name=? where group_name=?', (vm_name, group_name,)) # Toggle availability c.execute('update vms set available=0 where vm_name=?', (vm_name,)) c.execute('update vms set available=1 where vm_name=?', (old,)) def deploy(self): # Remove machines to be moved from old vlans # Remove vlans to be deleted # Create new vlans c = self.conn.cursor() c.execute('select * from groups') vlans = "" for group in c.fetchall(): # Make the vlan for this group vlan_id = str(group[1]) switch_controls.make_remove_vlans(vlan_id, True) # Get the nodes assigned to this group c.execute('select node_id from nodes where group_name=?',(group[0],)) nodes = "" for node in c.fetchall(): nodes += str(node[0]) + "," # Ensure that death-star is on all nodes += '16' # Add the ports to the vlan switch_controls.edit_ports_on_vlan(nodes, vlan_id, True) # Write to the vm-shared memory vm_name = group[2] try: os.mkdir('/var/lib/headnode-config/' + vlan_id) except: pass f = open('/var/lib/headnode-config/' + vlan_id + '/machines.txt', 'w+') #f = open('./vms/' + vm_name + '.txt', 'w+') c.execute('select mac_addr, manage_ip from nodes where group_name=?',(group[0],)) for row in c.fetchall(): f.write(row[0] + ' ' + row[1] + '\n') f.close() os.system("vm-vlan up " + vlan_id + " " + vm_name) self.conn.commit()
true
033497a2c0513410efbe8701b624e725b5b1f3ee
Python
borko81/basic_python_solvess
/nasted_loops/lucky_numbers.py
UTF-8
278
3.0625
3
[]
no_license
n = int(input()) for i in range(1111, 10000): test = str(i) if str(0) in test: continue if sum(int(i) for i in test[:2]) == sum(int(i) for i in test[2:]) and \ n % (sum(int(i) for i in test[:2])) == 0: print(int(test), end=' ')
true
36c5607c25083ed5e463cdadd75e311c5acd2e20
Python
HaukurPall/basic_prob
/week2/word_counter.py
UTF-8
1,895
3.890625
4
[]
no_license
import collections from operator import itemgetter c = collections.Counter() #file_path = input("Complete file-path, please: ") file_path = "war_and_peace.txt" with open(file_path) as input_file: for line in input_file: c.update(line.lower().split()) number_unique_words = len(c.most_common()) command = "" list_of_words = c.most_common() # first we order after alphabetical list_of_words.sort(key=itemgetter(0)) # then we order, in place after count list_of_words.sort(key=itemgetter(1), reverse=True) list_of_words = c.most_common()[-1000:] list_of_words.sort(key=itemgetter(0)) # then we order, in place after count list_of_words.sort(key=itemgetter(1), reverse=True) for i in range(0, 1000): print(list_of_words[i][0] + "\t" + str(list_of_words[i][1])) while command != "4": print("What would you like to do? Press the associated number for the action:") print("1. Look for the most frequent words") print("2. Look for the least frequent words") print("3. Look for the count of a specific word") print("4. Exit") command = input() if command == "1": number_of_words = int(input("How many words: ")) for i in range(0, number_of_words): print(list_of_words[i][0] + "\t" + str(list_of_words[i][1])) elif command == "2": number_of_words = int(input("How many words: ")) list_of_words = list_of_words[number_unique_words - number_of_words:] for i in range(0, number_of_words): print(list_of_words[i][0] + "\t" + str(list_of_words[i][1])) elif command == "3": word = input("What word: ") if word in c: print(word + "\t" + str(c[word])) else: print("Sorry, this word does not occur in the text") elif command == "4": print("Good bye!") else: print("Sorry, I do not understand this. Please choose again.")
true
ff0bac4f50b3de66d6ea74ef9e393dec3299eb4f
Python
ry05/personal-attack-classification
/code/src/feature_selection.py
UTF-8
1,438
3.40625
3
[]
no_license
""" Feature selection script ------------------------ Contains elements to aid in feature selection """ from sklearn.feature_selection import chi2, f_classif, mutual_info_classif from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import SelectPercentile class UnivariateFeatureSelection: """ Univariate feature selection Choose any kind of scoring method """ def __init__(self, n_features, scoring): """ Univariate feature selection wrapper :param n_features: If this is float, it is SelectPercentile else it is SelectKBest :param scoring: The scoring function """ # valid scoring functions valid_scoring = { "chi2": chi2, "f_classif": f_classif, "mutual_info_classif": mutual_info_classif } if isinstance(n_features, float): self.selection = SelectPercentile( valid_scoring[scoring], percentile = int(n_features * 100) ) else: self.selection = SelectKBest( valid_scoring[scoring], k=n_features ) def fit(self, X, y): return self.selection.fit(X, y) def transform(self, X): return self.selection.transform(X) def fit_transform(self, X, y): return self.selection.fit_transform(X, y)
true
ca3a344c1088e964484008b9b56f5a921f618e6a
Python
prawnrao/rsd-exam-prep
/Exam/python_language/tlf_bikes.py
UTF-8
5,642
3.421875
3
[]
no_license
import json import numpy as np from matplotlib import pyplot as plt from matplotlib import cm def unpack_data(filename): """ Function to extract data from a json file and convert it to a python dictionary. Parameters: str filename Returns: dict data """ if type(filename) != str: raise Exception('File name not input as str') with open(filename) as infile: raw_data = infile.read() data = json.loads(raw_data) return data def broken_docks(dict_data): """ Function to calculate total number of broken docks for a given data set Parameters: dict dict_data Returns: int broken_docks """ broken_docks = 0 station_list = dict_data['objects'] for station in station_list: allProperties = station['additionalProperties'] for singleProperty in allProperties: if 'NbBikes' == singleProperty['key']: nbBikes = int(singleProperty['value']) if 'NbEmptyDocks' == singleProperty['key']: nbEmptyDocks = int(singleProperty['value']) if 'NbDocks' == singleProperty['key']: nbDocks = int(singleProperty['value']) broken_docks += (nbDocks - (nbBikes + nbEmptyDocks)) return broken_docks def available_space(n, dict_data): """ Function that returns all station names with more than n number of free spaces. Parameters: int n dict dict_data Returns: list free_space_list """ free_space_list = [] station_list = dict_data['objects'] for station in station_list: allProperties = station['additionalProperties'] for singleProperty in allProperties: if 'NbEmptyDocks' == singleProperty['key']: nbEmptyDocks = int(singleProperty['value']) if nbEmptyDocks > n: stationName = station['commonName'] free_space_list.append(stationName) return free_space_list def closest_stations(dict_data, latitude, longitude): """ Function to find closest three stations to a given location. It returns a list sorted by distance. Parameters: dic dict_data float latitude float longitude Returns: list distance_list """ station_list = [] distance_list = [] station_names = available_space(2, dict_data) all_stations = dict_data['objects'] for station in all_stations: if station['commonName'] in station_names: station_list.append(station) for station in station_list: name = station['commonName'] station_lat = station['lat'] station_lon = station['lon'] distance = np.sqrt((latitude-station_lat)**2 + (longitude-station_lon)**2) distance_list.append([name,distance]) distance_list = sorted(distance_list) distance_list = distance_list[0:3] return distance_list def plot_stations(dict_data): """ Function that plots all the stations and shows the number of bikes at each station. Parameters: dict dict_data Output: PNG 2d Scatter """ lats = [] lons = [] colors = [] station_list = dict_data['objects'] for station in station_list: lats.append(station['lat']) lons.append(station['lon']) for prop in station['additionalProperties']: if 'NbBikes' == prop['key']: colors.append(int(prop['value'])) lats = np.array(lats) lons = np.array(lons) colors = np.array(colors) plt.scatter(lats, lons, s=20, c=colors, marker='o', cmap=cm.jet) plt.xlabel('Latitiude') plt.ylabel('Longitude') plt.title('Number of Bikes free at each station') plt.colorbar() plt.savefig('scatter.png') plt.clf() def plot_stations_2(dict_data, color_mode='NbBikes'): """ Function that plots all the stations and shows the number of bikes at each station by default. It can alternatively show free space. Parameters: dict dict_data str color_mode Output: PNG 2d Scatter """ lats = [] lons = [] colors = [] station_list = dict_data['objects'] for station in station_list: lats.append(station['lat']) lons.append(station['lon']) for prop in station['additionalProperties']: if color_mode == prop['key']: colors.append(int(prop['value'])) lats = np.array(lats) lons = np.array(lons) colors = np.array(colors) plt.scatter(lats, lons, s=20, c=colors, marker='o', cmap=cm.jet) plt.xlabel('Latitiude') plt.ylabel('Longitude') plt.title('{} at each station'.format(color_mode)) plt.colorbar() plt.savefig('scatter_{}.png'.format(color_mode)) plt.clf() if __name__ == '__main__': data = unpack_data('python_language_data.json') print(broken_docks(data)) print(len(available_space(2, data))) print(closest_stations(data, 51.527255, -0.113995)) plot_stations(data) plot_stations_2(data, color_mode='NbEmptyDocks')
true
0dfdebb7b331a9f0754a0c660862bb5d0d88f919
Python
zangzelin/Correlation-Analysis-between-Consumer-Price-Index-and-Service-Price-Index
/t.py
UTF-8
477
3.078125
3
[]
no_license
import matplotlib as mpl from matplotlib import pyplot as plt mpl.rcParams[u'font.sans-serif'] = ['simhei'] mpl.rcParams['axes.unicode_minus'] = False years = [1950, 1960, 1970, 1980, 1990, 2000, 2010] gdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3] #创建一副线图,x轴是年份,y轴是gdp plt.plot(years, gdp, color='green', marker='o', linestyle='solid') #添加一个标题 plt.title(u'名义GDP') #给y轴加标记 plt.ylabel(u'十亿美元') plt.show()
true
245eb33822dd024a844c128865aa16bb8efce519
Python
raferalston/PcKoteykaPro
/Homework/12Lesson2.py
UTF-8
484
3.78125
4
[]
no_license
class Player: def attack(self): print(f'{self.name} attacks!') class Mage(Player): def __init__(self): self.name = 'mage' class Barb(Player): def __init__(self): self.name = 'barbarian' m = Mage() b = Barb() while 1: q = input('Кого атакуем? - ') if q == 'mage': m.attack() elif q == 'barbarian': b.attack() elif q == 'exit': break else: print('Try Again or type exit to finish')
true
868acb74d857937a5c95fcbd0589200a6c0df5db
Python
ricardowiest/Python_CURSO
/Ex058.py
UTF-8
588
4.03125
4
[]
no_license
import random n=0 print('\033[1:32mAdivinhe que número estou pensando...\033[m') e=random.randint(1,100) tot=0 acertou= False while not acertou: n=int(input('Escolha um número de 1 até 100: ')) tot+=1 if n==e: acertou=True else: if n<e: print('\033[1:31mO número que pensei é maior, continue tentando...\033[m') else: print('\033[1:34mO número que pensei é menor, continue tentando...') print('O computador pensou {}.\nParabéns, você acertou!\nForam necessário(s) {} tentativa(s).'.format(e,tot))
true
5d510f572ccfe2294cf850f54aacd79f12706736
Python
alvations/sugali
/universalcorpus/crawlandclean/udhr.py
UTF-8
4,926
2.78125
3
[]
no_license
# -*- coding: utf-8 -*- # Access modules from parent dir, see http://goo.gl/dZ5HVk import os, sys parentddir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) sys.path.append(parentddir) import codecs, os, zipfile, urllib, urllib2, tempfile, shutil, re, io from unicodize import is_utf8, what_the_encoding from utils import make_tarfile, read_tarfile def get_from_unicodedotorg(testing=False): """ Crawl and clean UDHR files from www.unicode.org . """ TEMP_RAW_DIR = tempfile.mkdtemp() UDHR_DOWNLOAD = 'http://www.unicode.org/udhr/d/' AHREF_REGEX = '<a href="?\'?([^"\'>]*)' # Makes a temp output directory for the files that can be converted into utf8. UDHR_UTF8_DIR = './udhr-utf8/' # for saving the temp udhr files. if not os.path.exists(UDHR_UTF8_DIR): os.makedirs(UDHR_UTF8_DIR) # Get the directory page from the www.unicode.org UDHR page unicode_page = urllib.urlopen(UDHR_DOWNLOAD).read() # Crawls the www.unicode.org page for all udhr txt files. for i in re.findall(AHREF_REGEX,unicode_page): if i.endswith('.txt'): print UDHR_DOWNLOAD+i urllib.urlretrieve(UDHR_DOWNLOAD+i, filename=TEMP_RAW_DIR+i) with io.open(TEMP_RAW_DIR+i,'r',encoding='utf8') as udhrfile: # Gets the language from the end of the file line. lang = udhrfile.readline().partition('-')[2].strip() # Gets the language code from the filename. langcode = i.partition('.')[0].partition('_')[2] # Skip the header lines. for _ in range(5): udhrfile.readline(); # Reads the rest of the lines and that's the udhr data. the_rest = udhrfile.readlines() data = "\n".join([i.strip() for i in the_rest if i.strip() != '']) ##print langcode, data.split('\n')[0] with codecs.open(UDHR_UTF8_DIR+'udhr-'+langcode+'.txt','w','utf8') as outfile: print>>outfile, data if testing: break if testing: # Compress the utf8 UDHR files into a single tarfile in the test dir. try: make_tarfile('../test/udhr-unicode.tar',UDHR_UTF8_DIR) except IOError: # if function is called within the sugarlike/src/universalcorpus dir # To move up directory to access sugarlike/data/ and sugarlike/test/. make_tarfile('../../test/udhr-unicode.tar',UDHR_UTF8_DIR) else: # Compresses the utf8 UDHR files into a single tarfile. try: make_tarfile('../data/udhr/udhr-unicode.tar',UDHR_UTF8_DIR) except IOError: # if function is called within the sugarlike/src/universalcorpus dir # To move up directory to access sugarlike/data/ and sugarlike/test/. make_tarfile('../../data/udhr/udhr-unicode.tar',UDHR_UTF8_DIR) # Remove the udhr-utf8 directory. shutil.rmtree(UDHR_UTF8_DIR) def enumerate_udhr(intarfile): """ Returns the number of languages in a defaultdict(list). If language(s) has dialects/registers in the UDHR, len(enumerate_udhr(intarfile)[lang]) > 1 . # USAGE: >>> ls = enumerate_udhr('../data/udhr/udhr-unicode.tar') >>> for i in sorted(ls): >>> print i, ls[i] >>> print len(ls) # Number of languages """ from collections import defaultdict import tarfile TEMP_DIR = tempfile.mkdtemp() # Reads the tarfile and extract to temp directory. with tarfile.open(intarfile) as tf: for member in tf.getmembers(): tf.extract(member, TEMP_DIR) languages = defaultdict(list) # Loop through temp directory. for infile in os.listdir(TEMP_DIR): lang = infile.partition('.')[0].lower() try: lang, dialect = lang.split('_') # Checks for dialects denoted by "_". languages[lang].append(dialect) except: languages[lang].append(lang) return languages def documents(intarfile=parentddir+'/data/udhr/udhr-unicode.tar', \ bysentence=False): """ Yields UDHR by documents. """ for infile in read_tarfile(intarfile): #language = infile.split('/')[-1][:3] language = infile.split('/')[-1].split('-')[1].split('.')[0].split('_')[0] with codecs.open(infile,'r','utf8') as fin: if bysentence: for sentence in fin.readlines(): if sentence: yield language, sentence.strip() else: yield language, fin.read() def sents(intarfile=parentddir+'/data/udhr/udhr-unicode.tar', \ bysentence=True): return documents(intarfile, bysentence) def source_sents(intarfile=parentddir+'/data/udhr/udhr-unicode.tar', \ bysentence=True): return sents(intarfile, bysentence) def languages(): """ Returns a list of available languages from original data source. """ langs = [i.partition('-')[2].partition('.')[0] for i in \ enumerate_udhr(intarfile=parentddir+ '/data/udhr/udhr-unicode.tar')] return langs def num_languages(): """ Returns the number of languages available from original data source. """ return len(languages())
true
355f57ee9cb4e2a1b3575c4b95616fd32be22113
Python
zldobbs/TwittoMe
/main.py
UTF-8
9,688
3.265625
3
[]
no_license
# TwittoMe # A final project for CS4830 developed using Flask. Works with the # Twitter and GroupMe APIs to create a cohesive bot that polls for new # tweets from user specified accounts. # Developed by Zachary Dobbs and Austin Sizemore # --------------- INITIALIZATION AND CONFIG ---- # imports and initiatilization from flask import Flask, request, render_template, url_for import tweepy, json, config, time, threading, requests, html application = Flask(__name__) # pull config for twitter API (tweepy) auth = tweepy.OAuthHandler(config.twit['consumer_key'], config.twit['consumer_secret']) auth.set_access_token(config.twit['access_token_key'], config.twit['access_token_secret']) # initialize the tweepy api api = tweepy.API(auth) # ------------- POLLING THREAD ----------------- # create a thread that will run in the background # this thread will poll the user's twitter app every 15 seconds # to check if a new tweet has been posted # twitter's API restricts the retrieval of data to 10 second intervals class PollingThread(object): # establish thread details def __init__(self, interval=15): # the interval is the time between polls to the api self.interval = interval # users will contain the accounts currently being followed # defaults to Donald Trump at the start of the server # the top parameter specifies the ID of the user's most recent tweet self.users = [ { 'username' : '@Salvado43061975', 'top' : 0 } ] # start the thread as a daemon so it does not interrupt normal functionality thread = threading.Thread(target=self.run, args=()) thread.daemon = True thread.start() # method will follow add a new user to the current follow list def add_tweeter(self, name): # limit the amount of users being followed at one time to 5 users if len(self.users) >= 5: send_message("A maximum of 5 users may be followed at once! Type #twit unfollow <name> to open a spot") return 0 # keep the data consistent by enforcing an @ character in each username if '@' not in name: name = '@' + name # check if the user is already being followed, don't want a duplicate for tweeter in self.users: if tweeter['username'].lower() == name.lower(): send_message("Follow failed! User is already being followed!") return 0 # must try to follow the user try: api.user_timeline(screen_name = name) tweeter = {'username': name, 'top': 0} self.users.append(tweeter) # if it fails, it means that the username sent was either not real or a private account except Exception as e: print(e) send_message("Follow failed! Please make sure the account name is correct and not private!") # method will remove a username from the list of followed users def remove_tweeter(self, name): # check for an @ character being sent, must maintain data consistency if '@' not in name: name = '@' + name # iterate through the current users, if the user is found then it will be removed for index, tweeter in enumerate(self.users): if tweeter['username'].lower() == name.lower(): del self.users[index] send_message("Successfully unfollowed " + name + "!") return 0 # if the method doesn't return above, then the user specified was not found send_message("User specified is not currently being followed!") # method will print all accounts currently being followed def list(self): # check if noone is being followed if len(self.users) == 0: msg = "Noone is being followed! Type #twit follow <user> to start following!" # if it is not empty, iterate through each user and print their name else: msg = "Users currently being followed: " for tweeter in self.users: msg = msg + tweeter['username'] + ' ' send_message(msg) # method that will poll for a new tweet for a given user def query_user(self, tweeter): # if top is 0, then no tweets for this user have been evaluated yet if tweeter['top'] == 0: # status will contain the tweet infromation retrieved from the API status = api.user_timeline(screen_name = tweeter['username'], count = 1, tweet_mode = 'extended') # set top to the id of the tweet. this id increments with each new tweet tweeter['top'] = status[0].id print("Init: " + html.unescape(status[0].full_text)) # maintain data consistency by checking for the @ character if '@' not in tweeter['username']: send_message("Started following @" + tweeter['username'] + "!") else: send_message("Started following " + tweeter['username'] + "!") # send the tweet retrieved tweet = status[0] send_tweet(tweet) # if top is not 0, then some tweet has already been referenced else: status = api.user_timeline(screen_name = tweeter['username'], count = 1, tweet_mode = 'extended') curr = status[0] # check if the retrieved tweet is newer than current top tweet if curr.id > tweeter['top']: print("New tweet! -> " + html.unescape(curr.full_text)) send_tweet(curr) # set the new top to the current tweet tweeter['top'] = curr.id # method for the looping that will run on the daemon thread def run(self): # infinite loop, this process should run in the backround continuously while True: # for each user being followed, poll for their most recent tweet for tweeter in self.users: self.query_user(tweeter) # wait 15 seconds before checking again # twitter API requires at least 10 seconds between queries print('polling...') time.sleep(self.interval) # start the polling! poll = PollingThread() # method will send the tweet infromation to GroupMe via bot def send_tweet(status): # set the name and message name = status.user.name msg = html.unescape(status.full_text) send_message(name + ": " + msg) # --------------- GROUPME BOT ------------------ # sends the specified message to the GroupMe chat def send_message(msg): print('Attempting to send: ' + msg) # uses a post request to send to the chat # the bot's ID is stored in an external config file r = requests.post('https://api.groupme.com/v3/bots/post', data = {"text" : msg, "bot_id" : config.meBot['bot_id']}) # --------------- ROUTES ----------------------- # handle the display page of the applicaiton @application.route("/", methods=['GET']) def index(): return render_template('home.html') @application.route("/home", methods=['GET']) def home(): return render_template('home.html') @application.route("/tech", methods=['GET']) def tech(): return render_template('tech.html') @application.route("/instructions", methods=['GET']) def instructions(): return render_template('instructions.html') # handle the callback of messages sent from the group chat @application.route("/msg", methods=['POST']) def handle(): # get the message sent in json format data = request.get_json() # make sure that the the message sent is from an actual user and not the bot # #twit will denote the signal for a bot command if data['name'] != 'TwittoBot' and '#twit' in data['text']: # parse the received message for a valid command tokens = data['text'].split() # default to the error message, will change if a valid command is found msg = "Sorry, I didn't recognize that command. Try typing '#twit help' to list available commands" # commands if tokens[1]: command = tokens[1] # help will display some basic information on the application if command == 'help': msg = "Follow your favorite accounts to receive realtime updates on new tweets! Some available commands: " msg = msg + "follow <user>, unfollow <user>, list" # follow will add a user to the follow list if command == 'follow': # check if a username was specified if not tokens[2]: msg = "You must specify a valid public user to follow!" # try to follow the specified user else: msg = "" poll.add_tweeter(tokens[2]) # list will display all users being followed if command == 'list': msg = "" poll.list() # unfollow will remove a user from the follow list if command == 'unfollow': # check if a username was specified if not tokens[2]: msg = "You must specify a user to unfollow!" # try to unfollow the specified user else: msg = "" poll.remove_tweeter(tokens[2]) # send a message to the chat, will either be an error or success response send_message(msg) print("Original message sent -> " + data['text']) return "Righteous!" # --------------- SERVER START ----------------- if __name__ == "__main__": # 8080 port is allowed inbound on AWS application.run(host='0.0.0.0', port='8080')
true
97adb462a1fe6768bc946a579681f66a5e87f623
Python
Wenmingxing/Reinforcement-Learning
/Double_DQN/RL_brain.py
UTF-8
5,985
2.578125
3
[]
no_license
#! usr/bin/env python ''' Coded by Luke Wen on 11th Oct 2017 referece :https://github.com/MorvanZhou/Reinforcement-learning-with-tensorflow/blob/master/contents/5.1_Double_DQN/RL_brain.py It's aiming to build the double DQN for the cartpolr Env in the gym. The Double DQN is to overcome the overestimation problem exsited in the Natural DQN due to the Qmax which is included into the system by Q_learning. ''' import numpy as np import tensorflow as tf np.random.seed(1) tf.set_random_seed(1) class DoubleDQN: def __init__(self,n_actions,n_features,learning_rate = 0.005,reward_decay = 0.9,e_greedy = 0.9,replace_target_iter = 200,memory_size = 3000,batch_size = 32, e_greedy_increment=None,output_graph=False,double_q = True,sess = None): self.n_actions = n_actions self.n_features = n_features self.lr = learning_rate self.gamma = reward_decay self.epsilon_max = e_greedy self.replace_target_iter = replace_target_iter self.batch_size = batch_size self.memory_size = memory_size self.epsilon_increment = e_greedy_increment self.epsilon = 0 if e_greedy_increment is not None else self.epsilon_max self.double_q = double_q # sign for whether using the double q network self.learn_step_counter = 0 self.memory = np.zeros((self.memory_size,n_features * 2 + 2)) self._build_net() t_params = tf.get_collection('target_net_params') e_params = tf.get_collection('eval_net_params') self.replace_target_op = [tf.assign(e,t) for e,t in zip(e_params,t_params)] if sess is None: self.sess = tf.Session() self.sess.run(tf.global_variables_initializer()) else: self.sess = sess if output_graph: tf.summary.FileWriter('logs/',self.sess.graph) self.cost_his = [] def _build_net(self): ''' Build the evaluation and target network for training. ''' def build_layers(s,c_names,n_l1,w_initializer,b_initializer): with tf.variable_scope('l1'): w1 = tf.get_variable('w1',[self.n_features,n_l1],initializer = w_initializer,collections = c_names) b1 = tf.get_variable('b1',[1,n_l1],initializer = b_initializer,collections = c_names) l1 = tf.nn.relu(tf.matmul(s,w1) + b1) with tf.variable_scope('l2'): w2 = tf.get_variable('w2',[n_l1,self.n_actions],initializer = w_initializer,collections = c_names) b2 = tf.get_variable('b2',[1,self.n_actions],initializer = b_initializer,collections = c_names) out = tf.matmul(l1,w2) + b2 return out # build evaluate_net self.s = tf.placeholder(name = 's',shape = [None,self.n_features],dtype = tf.float32) # input self.q_target = tf.placeholder(name = 'Q_target',shape =[None,self.n_actions],dtype =tf.float32) # for calculating loss with tf.variable_scope('eval_net'): c_names, n_l1, w_initializer, b_initializer = ['eval_net_params',tf.GraphKeys.GLOBAL_VARIABLES],20,tf.random_normal_initializer(0.,0.3),tf.constant_initializer(0.1) # config of layers self.q_eval = build_layers(self.s,c_names,n_l1,w_initializer,b_initializer) with tf.variable_scope('loss'): self.loss = tf.reduce_mean(tf.squared_difference(self.q_target,self.q_eval)) with tf.variable_scope('train'): self._train_op = tf.train.RMSPropOptimizer(self.lr).minimize(self.loss) # Build target-net self.s_ = tf.placeholder(name = 's_',shape = [None,self.n_features],dtype =tf.float32) with tf.variable_scope('target_net'): c_names = ['target_net',tf.GraphKeys.GLOBAL_VARIABLES] self.q_next = build_layers(self.s_,c_names,n_l1,w_initializer,b_initializer) def store_transition(self,s,a,r,s_): ''' Store the transition into the memory ''' if not hasattr(self,'memory_counter'): self.memory_counter = 0 transition = np.hstack((s,[a,r],s_)) index = self.memory_counter % self.memory_size self.memory[index,:] = transition self.memory_counter += 1 def choose_action(self,observation): ''' Choose an action based on the current observation. ''' observation = observation[np.newaxis,:] actions_value = self.sess.run(self.q_eval,feed_dict={self.s:observation}) action = np.argmax(actions_value) if not hasattr(self,'q'): self.q = [] # record action value it gets self.running_q = 0 self.running_q = self.running_q * 0.99 + 0.01 * np.max(actions_value) self.q.append(self.running_q) if np.random.uniform() > self.epsilon: action = np.random.randint(0,self.n_actions) return action def learn(self): ''' update the network and learn ''' if self.learn_step_counter % self.replace_target_iter == 0: self.sess.run(self.replace_target_op) print('\ntraget_params_replaced\n') if self.memory_counter > self.memory_size: sample_index = np.random.choice(self.memory_size,size = self.batch_size) else: sample_index = np.random.choice(self.memory_counter,size = self.batch_size) batch_memory = self.memory[sample_index,:] q_next,q_eval4next = self.sess.run([self.q_next,self.q_eval],feed_dict = {self.s_:batch_memory[:,-self.n_features:],self.s:batch_memory[:,-self.n_features:]}) q_eval = self.sess.run(self.q_eval,feed_dict={self.s:batch_memory[:,:self.n_features]}) q_target = q_eval.copy() batch_index = np.arange(self.batch_size,dtype = np.int32) eval_act_index = batch_memory[:,self.n_features].astype(int) reward = batch_memory[:,self.n_features + 1] if self.double_q: max_act4next = np.argmax(q_eval4next,axis = 1) # the action that brings the highest value is evaluated by q-eval selected_q_next = q_next[batch_index,max_act4next] # double DQN, select q_next depending on above actions else: selected_q_next = np.max(q_next,axis = 1) # the natural DQN q_target[batch_index,eval_act_index] = reward + self.gamma * selected_q_next _, self.cost = self.sess.run([self._train_op,self.loss],feed_dict={self.s:batch_memory[:,:self.n_features],self.q_target:q_target}) self.cost_his.append(self.cost) self.epsilon = self.epsilon + self.epsilon_increment if self.epsilon < self.epsilon_max else self.epsilon_max self.learn_step_counter += 1
true
f258f8f93493694157332e4e41d396d1f73c77ec
Python
Hossain-Shah/Project
/AI & ML/Fake news detection.py
UTF-8
1,006
2.78125
3
[]
no_license
import numpy as np import pandas as pd import itertools from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import PassiveAggressiveClassifier from sklearn.metrics import accuracy_score, confusion_matrix df=pd.read_csv('C:/Users/HP/Downloads/Compressed/news.csv') print(df.shape) print(df.head()) labels=df.label print(labels.head()) x_train,x_test,y_train,y_test=train_test_split(df['text'], labels, test_size=0.2, random_state=7) tfidf_vectorizer=TfidfVectorizer(stop_words='english', max_df=0.7) tfidf_train=tfidf_vectorizer.fit_transform(x_train) tfidf_test=tfidf_vectorizer.transform(x_test) pac=PassiveAggressiveClassifier(max_iter=50) pac.fit(tfidf_train,y_train) #DataFlair - Predict on the test set and calculate accuracy y_pred=pac.predict(tfidf_test) score=accuracy_score(y_test,y_pred) print(f'Accuracy: {round(score*100,2)}%') confusion_matrix(y_test,y_pred, labels=['FAKE','REAL'])
true
dae073a3c5832be431afe89dbf94386129fe6161
Python
WangXichang/somescriptsrecordforgetlater
/py2ee_seg0906.py
UTF-8
4,938
3.109375
3
[]
no_license
# -*- utf-8 -*- import pandas as pd import numpy as np # example for SegTable def exp_segtable(): df = pd.DataFrame({'a': [x % 100 for x in range(10000)], 'b': [min(max(int(np.random.randn()*10+50), 0), 100) for x in range(10000)]}) seg = SegTable() seg.inputdf = df seg.segsort = 'desending' seg.segstep = 5 seg.segmax = 99 seg.segmin = 0 seg.segfields = ['a', 'b'] seg.run() return seg.outputdf # segment table for score dataframe class SegTable(object): __doc__ = ''' input: dataframe with a value field(int,float) to calculate segment table parameters: segStep: int, levels for segment value segMax: int, maxvalue for segment segMin: int, minvalue for segment segFields: list, field names to calculate, empty for calculate all fields output:dataframe with field 'seg, segfield_count, segfield_cumsum, segfield_percent' example: seg = ps.SegTable() seg.inputdf = pd.DataFrame({'sf':[i for i in range(1000)]}) seg.segStep = 1 #default:1 seg.segMax = 100 #default:150 seg.segMin = 1 #default:0 seg.segSort = 'desencding' #default:'ascending' seg.run() seg.outputdf #fields:sf, sf_count, sf_cumsum, sf_percent Note: score value >=0 score fields type is int ''' def __init__(self): self.__df = None self.__segdf = None self.__segStep = 1 self.__segMax = 150 self.__segMin = 0 self.__segSort = 'ascending' self.__segFields = [] return @property def segfields(self): return self.__segFields @segfields.setter def segfields(self, sf): self.__segFields = sf return @property def segstep(self): return self.__segStep @segstep.setter def segstep(self, segstep): self.__segStep = segstep return @property def segmin(self): return self.__segMin @segmin.setter def segmin(self, smin): self.__segMin = smin return @property def segmax(self): return self.__segMax @segmax.setter def segmax(self, smax): self.__segMax = smax @property def segsort(self): return self.__segSort @segsort.setter def segsort(self, sort): self.__segSort = sort return @property def rawdf(self): return self.__df @rawdf.setter def rawdf(self, df): self.__df = df return @property def outdf(self): return self.__segdf def run(self): if type(self.__df) == pd.Series: self.__df = pd.DataFrame(self.__df) if type(self.__df) != pd.DataFrame: print('data set is not ready!') return # create output dataframe with segstep = 1 seglist = [x for x in range(self.__segMin, self.__segMax + 1)] self.__segdf = pd.DataFrame({'seg': seglist}) if len(self.__segFields) == 0: self.__segFields = self.__df.columns.values for f in self.__segFields: r = self.__df.groupby(f)[f].count() self.__segdf[f+'_count'] = self.__segdf['seg'].apply(lambda x: r[x] if x in r.index else 0) if self.__segSort != 'ascending': self.__segdf = self.__segdf.sort_values(by='seg', ascending=False) self.__segdf[f+'_cumsum'] = self.__segdf[f+'_count'].cumsum() maxsum = max(max(self.__segdf[f+'_cumsum']), 1) self.__segdf[f+'_percent'] = self.__segdf[f+'_cumsum'].apply(lambda x: x/maxsum) if self.__segStep > 1: segcountname = f+'_count{0}'.format(self.__segStep) segcumsumname = f+'_cumsum{0}'.format(self.__segStep) segpercentname = f+'_percent{0}'.format(self.__segStep) self.__segdf[segcountname] = -1 c = 0 if self.__segSort == 'ascending': curpoint = self.__segMin curstep = self.__segStep else: curpoint = self.__segMax curstep = -self.__segStep for x in self.__segdf['seg']: c += self.__segdf.loc[self.__segdf['seg'] == x, f+'_count'].values[0] if x == curpoint: self.__segdf.loc[self.__segdf.seg == x, segcountname] = c c = 0 curpoint += curstep self.__segdf[segcumsumname] = self.__segdf[segcountname][self.__segdf[segcountname] >= 0].cumsum() self.__segdf[self.__segdf.isnull()] = -1 self.__segdf[segpercentname] = self.__segdf[segcumsumname].\ apply(lambda x: x / max(self.__segdf[segcumsumname]) if x > 0 else x) return # SegTable class end
true
9ea1c571cd66c8e7d6ce71e251cfbaed57eefb7d
Python
shengchaohua/leetcode-solution
/leetcode solution in python/PowerfulIntegers.py
UTF-8
927
3.53125
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sun Jan 6 10:59:58 2019 @problem: leetcode 970. Powerful Integers @author: shengchaohua """ class Solution: def powerfulIntegers(self, x, y, bound): """ :type x: int :type y: int :type bound: int :rtype: List[int] """ if x == 1 and y == 1: return [2] if bound >= 2 else [] elif x == 1: x, y = y, x res = set() i = 0 while x ** i <= bound: residue = bound - x ** i j = 0 while y ** j <= residue: if y == 1: res.add(x**i + 1) break res.add(x ** i + y ** j) j += 1 i += 1 return list(res) def test(): s = Solution() print(s.powerfulIntegers(5, 3, 15)) if __name__ == '__main__': test()
true
ee7b75d5b16e1bff0d7428b04528a849cba0d487
Python
anhtv26062000/vietocr
/vietocr/model/seqmodel/convseq2seq.py
UTF-8
11,634
2.671875
3
[ "Apache-2.0" ]
permissive
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F class Encoder(nn.Module): def __init__(self, emb_dim, hid_dim, n_layers, kernel_size, dropout, device, max_length = 512): super().__init__() assert kernel_size % 2 == 1, "Kernel size must be odd!" self.device = device self.scale = torch.sqrt(torch.FloatTensor([0.5])).to(device) # self.tok_embedding = nn.Embedding(input_dim, emb_dim) self.pos_embedding = nn.Embedding(max_length, emb_dim) self.emb2hid = nn.Linear(emb_dim, hid_dim) self.hid2emb = nn.Linear(hid_dim, emb_dim) self.convs = nn.ModuleList([nn.Conv1d(in_channels = hid_dim, out_channels = 2 * hid_dim, kernel_size = kernel_size, padding = (kernel_size - 1) // 2) for _ in range(n_layers)]) self.dropout = nn.Dropout(dropout) def forward(self, src): #src = [batch size, src len] src = src.transpose(0, 1) batch_size = src.shape[0] src_len = src.shape[1] device = src.device #create position tensor pos = torch.arange(0, src_len).unsqueeze(0).repeat(batch_size, 1).to(device) #pos = [0, 1, 2, 3, ..., src len - 1] #pos = [batch size, src len] #embed tokens and positions # tok_embedded = self.tok_embedding(src) tok_embedded = src pos_embedded = self.pos_embedding(pos) #tok_embedded = pos_embedded = [batch size, src len, emb dim] #combine embeddings by elementwise summing embedded = self.dropout(tok_embedded + pos_embedded) #embedded = [batch size, src len, emb dim] #pass embedded through linear layer to convert from emb dim to hid dim conv_input = self.emb2hid(embedded) #conv_input = [batch size, src len, hid dim] #permute for convolutional layer conv_input = conv_input.permute(0, 2, 1) #conv_input = [batch size, hid dim, src len] #begin convolutional blocks... for i, conv in enumerate(self.convs): #pass through convolutional layer conved = conv(self.dropout(conv_input)) #conved = [batch size, 2 * hid dim, src len] #pass through GLU activation function conved = F.glu(conved, dim = 1) #conved = [batch size, hid dim, src len] #apply residual connection conved = (conved + conv_input) * self.scale #conved = [batch size, hid dim, src len] #set conv_input to conved for next loop iteration conv_input = conved #...end convolutional blocks #permute and convert back to emb dim conved = self.hid2emb(conved.permute(0, 2, 1)) #conved = [batch size, src len, emb dim] #elementwise sum output (conved) and input (embedded) to be used for attention combined = (conved + embedded) * self.scale #combined = [batch size, src len, emb dim] return conved, combined class Decoder(nn.Module): def __init__(self, output_dim, emb_dim, hid_dim, n_layers, kernel_size, dropout, trg_pad_idx, device, max_length = 512): super().__init__() self.kernel_size = kernel_size self.trg_pad_idx = trg_pad_idx self.device = device self.scale = torch.sqrt(torch.FloatTensor([0.5])).to(device) self.tok_embedding = nn.Embedding(output_dim, emb_dim) self.pos_embedding = nn.Embedding(max_length, emb_dim) self.emb2hid = nn.Linear(emb_dim, hid_dim) self.hid2emb = nn.Linear(hid_dim, emb_dim) self.attn_hid2emb = nn.Linear(hid_dim, emb_dim) self.attn_emb2hid = nn.Linear(emb_dim, hid_dim) self.fc_out = nn.Linear(emb_dim, output_dim) self.convs = nn.ModuleList([nn.Conv1d(in_channels = hid_dim, out_channels = 2 * hid_dim, kernel_size = kernel_size) for _ in range(n_layers)]) self.dropout = nn.Dropout(dropout) def calculate_attention(self, embedded, conved, encoder_conved, encoder_combined): #embedded = [batch size, trg len, emb dim] #conved = [batch size, hid dim, trg len] #encoder_conved = encoder_combined = [batch size, src len, emb dim] #permute and convert back to emb dim conved_emb = self.attn_hid2emb(conved.permute(0, 2, 1)) #conved_emb = [batch size, trg len, emb dim] combined = (conved_emb + embedded) * self.scale #combined = [batch size, trg len, emb dim] energy = torch.matmul(combined, encoder_conved.permute(0, 2, 1)) #energy = [batch size, trg len, src len] attention = F.softmax(energy, dim=2) #attention = [batch size, trg len, src len] attended_encoding = torch.matmul(attention, encoder_combined) #attended_encoding = [batch size, trg len, emd dim] #convert from emb dim -> hid dim attended_encoding = self.attn_emb2hid(attended_encoding) #attended_encoding = [batch size, trg len, hid dim] #apply residual connection attended_combined = (conved + attended_encoding.permute(0, 2, 1)) * self.scale #attended_combined = [batch size, hid dim, trg len] return attention, attended_combined def forward(self, trg, encoder_conved, encoder_combined): #trg = [batch size, trg len] #encoder_conved = encoder_combined = [batch size, src len, emb dim] trg = trg.transpose(0, 1) batch_size = trg.shape[0] trg_len = trg.shape[1] device = trg.device #create position tensor pos = torch.arange(0, trg_len).unsqueeze(0).repeat(batch_size, 1).to(device) #pos = [batch size, trg len] #embed tokens and positions tok_embedded = self.tok_embedding(trg) pos_embedded = self.pos_embedding(pos) #tok_embedded = [batch size, trg len, emb dim] #pos_embedded = [batch size, trg len, emb dim] #combine embeddings by elementwise summing embedded = self.dropout(tok_embedded + pos_embedded) #embedded = [batch size, trg len, emb dim] #pass embedded through linear layer to go through emb dim -> hid dim conv_input = self.emb2hid(embedded) #conv_input = [batch size, trg len, hid dim] #permute for convolutional layer conv_input = conv_input.permute(0, 2, 1) #conv_input = [batch size, hid dim, trg len] batch_size = conv_input.shape[0] hid_dim = conv_input.shape[1] for i, conv in enumerate(self.convs): #apply dropout conv_input = self.dropout(conv_input) #need to pad so decoder can't "cheat" padding = torch.zeros(batch_size, hid_dim, self.kernel_size - 1).fill_(self.trg_pad_idx).to(device) padded_conv_input = torch.cat((padding, conv_input), dim = 2) #padded_conv_input = [batch size, hid dim, trg len + kernel size - 1] #pass through convolutional layer conved = conv(padded_conv_input) #conved = [batch size, 2 * hid dim, trg len] #pass through GLU activation function conved = F.glu(conved, dim = 1) #conved = [batch size, hid dim, trg len] #calculate attention attention, conved = self.calculate_attention(embedded, conved, encoder_conved, encoder_combined) #attention = [batch size, trg len, src len] #apply residual connection conved = (conved + conv_input) * self.scale #conved = [batch size, hid dim, trg len] #set conv_input to conved for next loop iteration conv_input = conved conved = self.hid2emb(conved.permute(0, 2, 1)) #conved = [batch size, trg len, emb dim] output = self.fc_out(self.dropout(conved)) #output = [batch size, trg len, output dim] return output, attention class ConvSeq2Seq(nn.Module): def __init__(self, vocab_size, emb_dim, hid_dim, enc_layers, dec_layers, enc_kernel_size, dec_kernel_size, enc_max_length, dec_max_length, dropout, pad_idx, device): super().__init__() enc = Encoder(emb_dim, hid_dim, enc_layers, enc_kernel_size, dropout, device, enc_max_length) dec = Decoder(vocab_size, emb_dim, hid_dim, dec_layers, dec_kernel_size, dropout, pad_idx, device, dec_max_length) self.encoder = enc self.decoder = dec def forward_encoder(self, src): encoder_conved, encoder_combined = self.encoder(src) return encoder_conved, encoder_combined def forward_decoder(self, trg, memory): encoder_conved, encoder_combined = memory output, attention = self.decoder(trg, encoder_conved, encoder_combined) return output, (encoder_conved, encoder_combined) def forward(self, src, trg): #src = [batch size, src len] #trg = [batch size, trg len - 1] (<eos> token sliced off the end) #calculate z^u (encoder_conved) and (z^u + e) (encoder_combined) #encoder_conved is output from final encoder conv. block #encoder_combined is encoder_conved plus (elementwise) src embedding plus # positional embeddings encoder_conved, encoder_combined = self.encoder(src) #encoder_conved = [batch size, src len, emb dim] #encoder_combined = [batch size, src len, emb dim] #calculate predictions of next words #output is a batch of predictions for each word in the trg sentence #attention a batch of attention scores across the src sentence for # each word in the trg sentence output, attention = self.decoder(trg, encoder_conved, encoder_combined) #output = [batch size, trg len - 1, output dim] #attention = [batch size, trg len - 1, src len] return output#, attention
true
45583209c2b2ebc98237dc955cb83efb77f50bf1
Python
yosifnandrov/softuni-stuff
/fundamentals 01/Balanced Brackets.py
UTF-8
392
3.609375
4
[]
no_license
n = int(input()) counter = 0 counter_two = 0 for i in range(1, n + 1): symbol = input() if symbol == "(": counter += 1 elif symbol == ")": counter_two += 1 if counter == 0 and counter_two == 0: print("BALANCED") elif counter % 2 == 0 and counter_two == 0: print("BALANCED") elif counter == counter_two: print("BALANCED") else: print("UNBALANCED")
true
1a0929b9bc28ccaa8f3f416fc83a472a0352e90c
Python
myFinTechPL/Complete-Python-3-Bootcamp
/08-Milestone Project - 2/test_cap.py
UTF-8
478
3.171875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat Dec 7 20:45:05 2019 @author: ktzaj """ import unittest import cap class TestCap(unittest.TestCase): def test_one_word(self): text = 'python' result = cap.cap_text(text) self.assertEqual(result, 'Python') def test_multiple_words(self): text = 'monty python' result = cap.cap_text(text) self.assertEqual(result, 'Monty Python') if __name__ == '__main__': unittest.main()
true
b50a3b54afd648f0349b42b7eca5428f4d35a9b6
Python
prakharguptaz/Adv_gen_dialogue
/adversarial_creation/mask-and-fill-ilm/ilm/mask/custom.py
UTF-8
1,745
2.59375
3
[]
no_license
from enum import Enum import random from .base import MaskFn class MaskPunctuationType(Enum): SENTENCE_TERMINAL = 0 OTHER = 1 class MaskPunctuation(MaskFn): def __init__(self, p=0.5): self.p = p @classmethod def mask_types(cls): return list(MaskPunctuationType) @classmethod def mask_type_serialize(cls, m_type): return m_type.name.lower() def mask(self, doc): masked_spans = [] for span_offset, char in enumerate(doc): if not char.isalnum() and len(char.strip()) > 0 and random.random() < self.p: if char in ['.', '?', '!']: span_type = MaskPunctuationType.SENTENCE_TERMINAL else: span_type = MaskPunctuationType.OTHER span_len = 1 masked_spans.append((span_type, span_offset, span_len)) return masked_spans from nltk import pos_tag from ..string_util import word_tokenize from ..tokenize_util import tokens_offsets class MaskProperNounType(Enum): PROPER_NOUN = 0 class MaskProperNoun(MaskFn): def __init__(self, p=1.): try: pos_tag(['Ensure', 'tagger']) except: raise ValueError('Need to call nltk.download(\'averaged_perceptron_tagger\')') self.p = p @classmethod def mask_types(cls): return list(MaskProperNounType) @classmethod def mask_type_serialize(cls, m_type): return m_type.name.lower() def mask(self, doc): from nltk import pos_tag masked_spans = [] toks = word_tokenize(doc) toks_offsets = tokens_offsets(doc, toks) toks_pos = pos_tag(toks) for t, off, (_, pos) in zip(toks, toks_offsets, toks_pos): if pos == 'NNP' and random.random() < self.p: masked_spans.append((MaskProperNounType.PROPER_NOUN, off, len(t))) return masked_spans
true
613cbffa89356efaa460f726addb4224ae03d16e
Python
kavyasreesg/Datastructures_Algorithms
/Binary_Search_Tree.py
UTF-8
2,258
4.03125
4
[]
no_license
class Tree: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def insert(self, data): if self.data == data: return False # Eliminating duplicate nodes elif data < self.data: if self.left is None: self.left = Tree(data) return True else: return self.left.insert(data) else: if self.right is None: self.right = Tree(data) return True else: return self.right.insert(data) def find(self, data): if self.data == data: return data elif data < self.data: if self.left is None: return False else: self.left.find(data) else: if self.right is None: return False else: return self.right.find(data) def size_of_tree(self): if self.left is not None and self.right is not None: return 1 + self.left.size_of_tree() + self.right.size_of_tree() elif self.left: return 1 + self.left.size_of_tree() elif self.right: return 1 + self.right.size_of_tree() else: return 1 def preorder_traverse(self): if self is not None: print(self.data, end=' ') if self.left is not None: self.left.preorder_traverse() if self.right is not None: self.right.preorder_traverse() def inorder_traverse(self): if self is not None: if self.left is not None: self.left.inorder_traverse() print(self.data, end=' ') if self.right is not None: self.right.inorder_traverse() if __name__ == "__main__": tree = Tree(10) tree.insert(11) for i in range(3, 12): tree.insert(i) tree.inorder_traverse() # Prints in sorted order print() tree.preorder_traverse() found = tree.find(11) print() print("element searched ", found)
true
bec4a96b9dd4f4870f7c33a41a03b8f6add278fc
Python
wseungjin/codingTest
/naver/chihoon/1.py
UTF-8
798
3.359375
3
[]
no_license
from functools import reduce def getSumDigit(number): sumValue = 0 while number != 0: sumValue += number % 10 number = number // 10 return sumValue def solution(A): A = sorted(A) result = {} for element in A: sumValue = getSumDigit(element) try: result[sumValue].append(element) except: result[sumValue] = [element] maxValue = -1 sumIndexs = list(result) for sumIndex in sumIndexs: if len(result[sumIndex])>= 2: maxValue = max(maxValue,result[sumIndex][-1] + result[sumIndex][-2]) return maxValue def main(): print(solution([51,71,17,42])) print(solution([42,33,60])) print(solution([51,32,43])) main()
true
4a52c264213a41b47c339f0217ad133409a00b7f
Python
OfriHarlev/ConnectK
/pyshell.py
UTF-8
2,610
3.140625
3
[]
no_license
#Author: Toluwanimi Salako import sys from student_ai import StudentAI sys.path.append(r'\ConnectKSource_python') import ConnectKSource_python.board_model as boardmodel is_first_player = False deadline = 0 def make_ai_shell_from_input(): global is_first_player ai_shell = None begin = "makeMoveWithState:" end = "end" go = True while (go): mass_input = input().split(" ") if (mass_input[0] == end): sys.exit() elif (mass_input[0] == begin): #first I want the gravity, then number of cols, then number of rows, then the col of the last move, then the row of the last move then the values for all the spaces. # 0 for no gravity, 1 for gravity #then rows #then cols #then lastMove col #then lastMove row. #then deadline. #add the K variable after deadline. #then the values for the spaces. #cout<<"beginning"<<endl; gravity = int(mass_input[1]) col_count = int(mass_input[2]) row_count = int(mass_input[3]) last_move_col = int(mass_input[4]) last_move_row = int(mass_input[5]) #add the deadline here: deadline = -1 deadline = int(mass_input[6]) k = int(mass_input[7]) #now the values for each space. counter = 8 #allocate 2D array. model = boardmodel.BoardModel(col_count, row_count, k, gravity) count_own_moves = 0 for col in range(col_count): for row in range(row_count): model.pieces[col][row] = int(mass_input[counter]) if (model.pieces[col][row] == 1): count_own_moves += model.pieces[col][row] counter+=1 if (count_own_moves % 2 == 0): is_first_player = True model.last_move = (last_move_col, last_move_row) ai_shell = StudentAI(1 if is_first_player else 2, model) return ai_shell else: print("unrecognized command", mass_input) #otherwise loop back to the top and wait for proper _input. return ai_shell def return_move(move): made_move = "ReturningTheMoveMade"; #outputs made_move then a space then the row then a space then the column then a line break. print(made_move, move[0], move[1]) def check_if_first_player(): global is_first_player return is_first_player if __name__ == '__main__': print ("Make sure this program is ran by the Java shell. It is incomplete on its own. :") go = True while (go): #do this forever until the make_ai_shell_from_input function ends the process or it is killed by the java wrapper. ai_shell = make_ai_shell_from_input() moveMade = ai_shell.make_move(deadline) return_move(moveMade) del ai_shell sys.stdout.flush()
true
76d492d2503ce7581c3e328dbfa08ca687ab11f1
Python
shingasia/DataCrawling
/Popular_Destination.py
UTF-8
1,766
2.984375
3
[]
no_license
import pandas as pd import matplotlib import matplotlib.pyplot as plt import time #1203 부터 1212까지 df1203=pd.read_csv('1203Departure.csv', encoding='euc-kr') df1204=pd.read_csv('1204Departure.csv', encoding='euc-kr') df1205=pd.read_csv('1205Departure.csv', encoding='euc-kr') df1206=pd.read_csv('1206Departure.csv', encoding='euc-kr') df1207=pd.read_csv('1207Departure.csv', encoding='euc-kr') df1208=pd.read_csv('1208Departure.csv', encoding='euc-kr') df1209=pd.read_csv('1209Departure.csv', encoding='euc-kr') df1210=pd.read_csv('1210Departure.csv', encoding='euc-kr') df1211=pd.read_csv('1211Departure.csv', encoding='euc-kr') df1212=pd.read_csv('1212Departure.csv', encoding='euc-kr') time.sleep(1) #데이터 프레임 전체를 리스트에 저장 df_list=[df1203, df1204, df1205, df1206, df1207, df1208, df1209, df1210, df1211, df1212] # Unnamed:0 칼럼을 제거한다 # df1203.drop(df1203.columns[[0]], axis=1, inplace=True) for dfTemp in df_list: dfTemp.drop(dfTemp.columns[[0]], axis=1, inplace=True) #데이터 프레임 10개를 전부다 total_df 로 합친다 total_df=pd.concat(df_list, ignore_index=True) destinations=dict() #(목적지: 운항횟수)를 쌍으로 저장할 딕셔너리 생성 for des in list(total_df['목적지']): if des not in destinations : destinations[des]=1#없으면 추가 else: destinations[des]=destinations[des]+1#있으면 1씩 증가 df=pd.DataFrame({'Destination' : list(destinations.keys()), 'frequency': list(destinations.values())}) #저장 !!!!!!!!!!!!!!!!!!!!!!! #df.to_csv('Flying_Frequency.csv', encoding='euc-kr') x=list(destinations.values()) y=list(destinations.keys()) plt.barh(y, x) plt.show()
true
a72b2e8ad935cbe48ba33b13fdccd0ec2dd91438
Python
Finalcheat/qiushibaike_scrapy
/qiushibaike/spiders/qiushibaike_spider.py
UTF-8
1,173
2.609375
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- import scrapy import re from qiushibaike.items import QiushibaikeItem class QiushibaikeSpider(scrapy.Spider): """ 糗事百科spider """ name = "qiushibaike" allowed_domains = ["qiushibaike.com"] start_urls = [ "http://www.qiushibaike.com/text/", ] def parse(self, response): articles = response.css('div.article') for article in articles: content = article.xpath('.//div[@class="content"]').extract()[0] content = content.replace('<div class="content">', '<div>') content = content.replace("\n", "") like = article.xpath('.//div[@class="stats"]/span[@class="stats-vote"]/i[@class="number"]/text()').extract()[0] like = int(like) dislike = 0 href = article.xpath('.//a[@class="contentHerf"]/@href').extract()[0] if not href.startswith('http'): href = 'http://www.qiushibaike.com' + href source = u"糗事百科" item = QiushibaikeItem(content=content, like=like, dislike=dislike, href=href, source=source) yield item
true
9b452a645d1dc53a7f9fe2428439352bc8113ca2
Python
Naumov89/python_metiz
/11/test_name_function.py
UTF-8
768
3.671875
4
[]
no_license
import unittest from name_function import get_formated_name class NamesTestCase(unittest.TestCase): """Тесты для 'name_function.py'""" def test_first_last_name(self): """Имена вида 'Jenis Joplin' работают, правильно!""" formatted_name = get_formated_name('jenis', 'joplin') self.assertEqual(formatted_name, 'Jenis Joplin') # Проверяет полученный результат с ожидающим def test_first_last_middle_name(self): """Работают ли такие имена, как 'Wolfgang Amadeus Mozart'?""" formatted_name = get_formated_name('wolfgang', 'mozart', 'amadeus') self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart') if __name__=='__main__': unittest.main()
true
a55b4cf0dba959e4906e5acb27938581d7232d5d
Python
Kit55/Python-test
/.старое/2fix/2.4.py
UTF-8
837
2.765625
3
[]
no_license
def addit(_add): def hidden(_hid): return(_add+_hid) return hidden def add_range(_start,_finish): for i in range (_start,_finish): globals()['add%d' %i] = addit(i) add_range(0, 10) def map2(*_ars): """ >>> map2([add0,add1],[1,2]) [1, 2, 2, 3] """ l0=list() l1=list() l3=list() if hasattr(_ars[0], '__iter__'): l0=_ars[0] else: l0.append(_ars[0]) if hasattr(_ars[1], '__iter__'): l1=_ars[1] else: l1.append(_ars[1]) for i in l0: l2=list() for g in l1: l2.append(i(g)) l3.append(l2) return (l3) print(map2(add0,1)) print(map2(add0,[1,2])) print(map2([add0,add1],1)) print(map2([add0,add1],[1,2])) tu=list(1) tu+=1; if __name__ == "__main__": import doctest doctest.testmod()
true
31b6209db268bed01c10e05d3646b1a556b52c76
Python
AjinkyaTaranekar/AlgorithmX
/Codeforces/617/A.py
UTF-8
261
3.5625
4
[]
no_license
n = int(input()) count=0 while n-5 >= 0: n-=5 count+=1 while n-4 >= 0: n-=4 count+=1 while n-3 >= 0: n-=3 count+=1 while n-2 >= 0: n-=2 count+=1 while n-1 >= 0: n-=1 count+=1 print(count)
true
8eab390dad7396ca05f1dc40dfa42de1a2adf5fc
Python
pratikkarad/unipune-practicals
/mini_scoa/fuzzy_ac.py
UTF-8
6,531
3.046875
3
[]
no_license
import numpy as np import skfuzzy as fuzz from skfuzzy import control as ctrl from statistics import mean, stdev '''Declaring the Antecedents''' roomtemp = ctrl.Antecedent(np.arange(0, 50, 1), "Room Temperature \u00b0C") roomtemp.automf(names=['Low', 'Normal', 'High', 'Very High']) humidity = ctrl.Antecedent(np.arange(0, 100, 1), 'Humidity in Percentage (%)') humidity.automf(names=['Low', 'Normal', 'High']) bright = ctrl.Antecedent(np.arange(0, 100, 1), 'Brightness in Percentage (%)') bright.automf(names=['Rainy', 'Cloudy', 'Sunny']) '''Declaring the Consequents''' comfort = ctrl.Consequent(np.arange(15, 25, 1), 'Comfortable Temperature in \u00b0C') comfort.automf(names=['Low', 'Medium', 'High']) time_in_min = ctrl.Consequent(np.arange(0, 60, 1), 'Time in Minuites') time_in_min.automf(names=['Very Short Time', 'Short Time', 'Medium Time', 'Long Time', 'Very Long Time']) '''Declaring the User Defined Membership Functions''' roomtemp['Low'] = fuzz.gaussmf(roomtemp.universe, mean([0, 0, 15]),stdev([0, 0, 15])) roomtemp['Normal'] = fuzz.gaussmf(roomtemp.universe, mean([0, 15, 30]), stdev([0, 15, 30])) roomtemp['High'] = fuzz.gaussmf(roomtemp.universe, mean([15, 30, 45]), stdev([15, 30, 45])) roomtemp['Very High'] = fuzz.gaussmf(roomtemp.universe, mean([30, 45, 60]), stdev([30, 45, 60])) roomtemp.view() humidity['Low'] = fuzz.trimf(humidity.universe, [0,0,40]) humidity['Normal'] = fuzz.trimf(humidity.universe, [10,50,90]) humidity['High'] = fuzz.trimf(humidity.universe, [50,80,120]) humidity.view() bright['Rainy'] = fuzz.trimf(bright.universe, [0,0,40]) bright['Cloudy'] = fuzz.trimf(bright.universe, [10,50,90]) bright['Sunny'] = fuzz.trimf(bright.universe, [50,80,120]) bright.view() comfort['Low'] = fuzz.gaussmf(comfort.universe, mean([15, 17, 19]),stdev([15, 17, 19])) comfort['Medium'] = fuzz.gaussmf(comfort.universe, mean([17, 19, 21]),stdev([17, 19, 21])) comfort['High'] = fuzz.gaussmf(comfort.universe, mean([19, 21, 23]),stdev([19, 21, 23])) comfort.view() time_in_min['Very Short Time'] = fuzz.trimf(time_in_min.universe, [0, 0, 15]) time_in_min['Short Time'] = fuzz.trimf(time_in_min.universe, [0, 15, 30]) time_in_min['Medium Time'] = fuzz.trimf(time_in_min.universe, [15, 30, 45]) time_in_min['Long Time'] = fuzz.trimf(time_in_min.universe, [30, 45, 60]) time_in_min['Very Long Time'] = fuzz.trimf(time_in_min.universe, [45, 60, 60]) '''Define Rules for Fuzzy Control System-1 for AC On Time''' rule1 = ctrl.Rule(roomtemp['Low'] | humidity['Low'], time_in_min['Very Short Time']) rule2 = ctrl.Rule(roomtemp['Normal'] | humidity['Low'], time_in_min['Short Time']) rule3 = ctrl.Rule(roomtemp['Normal'] | humidity['Normal'], time_in_min['Short Time']) rule4 = ctrl.Rule(roomtemp['Normal'] | humidity['High'], time_in_min['Medium Time']) rule5 = ctrl.Rule(roomtemp['Normal'] | humidity['High'], time_in_min['Medium Time']) rule6 = ctrl.Rule(roomtemp['High'] | humidity['Low'], time_in_min['Long Time']) rule7 = ctrl.Rule(roomtemp['High'] | humidity['Normal'], time_in_min['Long Time']) rule8 = ctrl.Rule(roomtemp['High'] | humidity['High'], time_in_min['Long Time']) rule9 = ctrl.Rule(roomtemp['High'] | humidity['High'], time_in_min['Long Time']) rule10 = ctrl.Rule(roomtemp['High'] | humidity['High'], time_in_min['Very Long Time']) rule11 = ctrl.Rule(roomtemp['High'] | humidity['High'], time_in_min['Very Long Time']) '''Define Rules for Fuzzy Control System-1 for Comfortable Temperature''' fuzz1_rule1 = ctrl.Rule(roomtemp['Very High'] | humidity['High'] | bright['Sunny'], comfort['Low']) fuzz1_rule2 = ctrl.Rule(roomtemp['Very High'], comfort['Medium']) fuzz1_rule3 = ctrl.Rule(roomtemp['High'] | humidity['High'] | bright['Sunny'], comfort['Low']) fuzz1_rule4 = ctrl.Rule(roomtemp['High'] | humidity['High'], comfort['Medium']) fuzz1_rule5 = ctrl.Rule(roomtemp['Normal'] | humidity['High'] | bright['Sunny'], comfort['Medium']) fuzz1_rule6 = ctrl.Rule(roomtemp['Normal'] | humidity['High'], comfort['Medium']) fuzz1_rule7 = ctrl.Rule(roomtemp['Normal'] | humidity['Normal'] | bright['Sunny'], comfort['Medium']) fuzz1_rule8 = ctrl.Rule(roomtemp['Normal'] | humidity['Normal'] | bright['Cloudy'], comfort['Medium']) fuzz1_rule9 = ctrl.Rule(roomtemp['Normal'] | humidity['Normal'] | bright['Rainy'], comfort['High']) fuzz1_rule10 = ctrl.Rule(roomtemp['Low'] | humidity['High'] | bright['Sunny'], comfort['Low']) fuzz1_rule11 = ctrl.Rule(roomtemp['Low'] | humidity['High'] | bright['Cloudy'], comfort['Low']) fuzz1_rule12 = ctrl.Rule(roomtemp['Low'] | humidity['High'] | bright['Rainy'], comfort['Medium']) fuzz1_rule13 = ctrl.Rule(roomtemp['Low'] | humidity['Normal'] | bright['Sunny'], comfort['Medium']) fuzz1_rule14 = ctrl.Rule(roomtemp['Low'] | humidity['Normal'] | bright['Cloudy'], comfort['Medium']) fuzz1_rule15 = ctrl.Rule(roomtemp['Low'] | humidity['Normal'] | bright['Rainy'], comfort['High']) fuzz1_rule16 = ctrl.Rule(roomtemp['Low'] | humidity['Low'] | bright['Sunny'], comfort['Medium']) fuzz1_rule17 = ctrl.Rule(roomtemp['Low'] | humidity['Low'] | bright['Cloudy'], comfort['Medium']) '''Train the AC Fuzzy Control System-1''' ac_ctrl_system_temp = ctrl.ControlSystem([fuzz1_rule1, fuzz1_rule2, fuzz1_rule3, fuzz1_rule4, fuzz1_rule5, fuzz1_rule6, fuzz1_rule7, fuzz1_rule8, fuzz1_rule9, fuzz1_rule10, fuzz1_rule11, fuzz1_rule12, fuzz1_rule13, fuzz1_rule14, fuzz1_rule15, fuzz1_rule16, fuzz1_rule17]) ac_ctrl_temp = ctrl.ControlSystemSimulation(ac_ctrl_system_temp) '''Train the AC Fuzzy Control System-1''' ac_ctrl_system_time = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9, rule10, rule11]) ac_ctrl_time = ctrl.ControlSystemSimulation(ac_ctrl_system_time) '''Take Input from User''' ac_ctrl_temp.input['Room Temperature \u00b0C'] = 0 ac_ctrl_temp.input['Humidity in Percentage (%)'] = 0 ac_ctrl_temp.input['Brightness in Percentage (%)'] = 0 ac_ctrl_time.input['Room Temperature \u00b0C'] = 0 ac_ctrl_time.input['Humidity in Percentage (%)'] = 0 '''Compute the Output of Fuzzy Control Systems (Comf Temp)/(Time)''' ac_ctrl_temp.compute() comfort.view(sim=ac_ctrl_temp) ac_ctrl_time.compute() time_in_min.view(sim=ac_ctrl_time) '''Print And Store Outputs''' fuzzy_output_temp = ac_ctrl_temp.output['Comfortable Temperature in \u00b0C'] fuzzy_output_time = ac_ctrl_time.output['Time in Minuites'] print('Comfortable Temperature: ', fuzzy_output_temp) print('Time in Minuites: ', fuzzy_output_time)
true
4cf628c354733739fc0b2474bbc8f4b04d525f57
Python
scmsqhn/zhihu_spider
/panAnaly.py
UTF-8
696
2.734375
3
[]
no_license
#!/usr/bin/env python #coding=utf-8 import sys reload(sys) sys.setdefaultencoding('utf-8') import pandas from to_csv import mongo_to_csv import matplotlib.pyplot as mplt if __name__=='__main__': #将数据库中的数据转化成csv格式 mongo_to_csv() #使用pandas模块进行条形图的绘制;TODO 更加详细的分析 target=pandas.read_csv('zhihu_user_data_30k.csv',encoding='utf-8') city_count=target[u'所在地'].value_counts()[:10] # plt=city_count.plot(kind='bar',title="City Statistics",figsize=(10,10)).get_figure() plt=city_count.plot(kind='barh',title="City Statistics").get_figure() mplt.legend(loc='best') plt.savefig("city.png")
true
ebef8db975b0b3d400eae3fe047f21f8d812b55c
Python
Functional-Brain-Mapping-Laboratory/PyCartool
/pycartool/lf/leadfield.py
UTF-8
940
2.796875
3
[ "BSD-3-Clause" ]
permissive
# -*- coding: utf-8 -*- # Authors: Victor Férat <victor.ferat@live.fr> # # License: BSD (3-clause) import struct import numpy as np def read_lf(filename): """Read Cartool leadfield (``.lf``) file. Parameters ---------- filename : str or file-like The leadfield file (``.lf``) to read. Returns ------- leadfield_matrix : `~numpy.array` The leadfield matrix. shape(``n_channels``, ``n_sources``, ``3``). """ with open(filename, "rb") as f: byte = f.read(4) number_of_electrodes = struct.unpack("i", byte)[0] byte = f.read(4) number_of_solution_points = struct.unpack("i", byte)[0] buf = f.read(number_of_electrodes * number_of_solution_points * 8) data = np.frombuffer(buf, dtype=np.double) number_of_points = int(number_of_solution_points / 3) leadfield_matrix = data.reshape(number_of_electrodes, number_of_points, 3) return leadfield_matrix
true
92b9a4f13629546bd5178778a0f9119556d02e76
Python
arianepaola/tg2jython
/sqlalchemy60/lib/sqlalchemy/dialects/mssql/base.py
UTF-8
53,649
3.015625
3
[ "MIT" ]
permissive
# mssql.py """Support for the Microsoft SQL Server database. Driver ------ The MSSQL dialect will work with three different available drivers: * *pyodbc* - http://pyodbc.sourceforge.net/. This is the recommeded driver. * *pymssql* - http://pymssql.sourceforge.net/ * *adodbapi* - http://adodbapi.sourceforge.net/ Drivers are loaded in the order listed above based on availability. If you need to load a specific driver pass ``module_name`` when creating the engine:: engine = create_engine('mssql+module_name://dsn') ``module_name`` currently accepts: ``pyodbc``, ``pymssql``, and ``adodbapi``. Currently the pyodbc driver offers the greatest level of compatibility. Connecting ---------- Connecting with create_engine() uses the standard URL approach of ``mssql://user:pass@host/dbname[?key=value&key=value...]``. If the database name is present, the tokens are converted to a connection string with the specified values. If the database is not present, then the host token is taken directly as the DSN name. Examples of pyodbc connection string URLs: * *mssql+pyodbc://mydsn* - connects using the specified DSN named ``mydsn``. The connection string that is created will appear like:: dsn=mydsn;TrustedConnection=Yes * *mssql+pyodbc://user:pass@mydsn* - connects using the DSN named ``mydsn`` passing in the ``UID`` and ``PWD`` information. The connection string that is created will appear like:: dsn=mydsn;UID=user;PWD=pass * *mssql+pyodbc://user:pass@mydsn/?LANGUAGE=us_english* - connects using the DSN named ``mydsn`` passing in the ``UID`` and ``PWD`` information, plus the additional connection configuration option ``LANGUAGE``. The connection string that is created will appear like:: dsn=mydsn;UID=user;PWD=pass;LANGUAGE=us_english * *mssql+pyodbc://user:pass@host/db* - connects using a connection string dynamically created that would appear like:: DRIVER={SQL Server};Server=host;Database=db;UID=user;PWD=pass * *mssql+pyodbc://user:pass@host:123/db* - connects using a connection string that is dynamically created, which also includes the port information using the comma syntax. If your connection string requires the port information to be passed as a ``port`` keyword see the next example. This will create the following connection string:: DRIVER={SQL Server};Server=host,123;Database=db;UID=user;PWD=pass * *mssql+pyodbc://user:pass@host/db?port=123* - connects using a connection string that is dynamically created that includes the port information as a separate ``port`` keyword. This will create the following connection string:: DRIVER={SQL Server};Server=host;Database=db;UID=user;PWD=pass;port=123 If you require a connection string that is outside the options presented above, use the ``odbc_connect`` keyword to pass in a urlencoded connection string. What gets passed in will be urldecoded and passed directly. For example:: mssql+pyodbc:///?odbc_connect=dsn%3Dmydsn%3BDatabase%3Ddb would create the following connection string:: dsn=mydsn;Database=db Encoding your connection string can be easily accomplished through the python shell. For example:: >>> import urllib >>> urllib.quote_plus('dsn=mydsn;Database=db') 'dsn%3Dmydsn%3BDatabase%3Ddb' Additional arguments which may be specified either as query string arguments on the URL, or as keyword argument to :func:`~sqlalchemy.create_engine()` are: * *auto_identity_insert* - enables support for IDENTITY inserts by automatically turning IDENTITY INSERT ON and OFF as required. Defaults to ``True``. * *query_timeout* - allows you to override the default query timeout. Defaults to ``None``. This is only supported on pymssql. * *use_scope_identity* - allows you to specify that SCOPE_IDENTITY should be used in place of the non-scoped version @@IDENTITY. Defaults to ``False``. On pymssql this defaults to ``True``, and on pyodbc this defaults to ``True`` if the version of pyodbc being used supports it. * *max_identifier_length* - allows you to se the maximum length of identfiers supported by the database. Defaults to 128. For pymssql the default is 30. * *schema_name* - use to set the schema name. Defaults to ``dbo``. Auto Increment Behavior ----------------------- ``IDENTITY`` columns are supported by using SQLAlchemy ``schema.Sequence()`` objects. In other words:: Table('test', mss_engine, Column('id', Integer, Sequence('blah',100,10), primary_key=True), Column('name', String(20)) ).create() would yield:: CREATE TABLE test ( id INTEGER NOT NULL IDENTITY(100,10) PRIMARY KEY, name VARCHAR(20) NULL, ) Note that the ``start`` and ``increment`` values for sequences are optional and will default to 1,1. * Support for ``SET IDENTITY_INSERT ON`` mode (automagic on / off for ``INSERT`` s) * Support for auto-fetching of ``@@IDENTITY/@@SCOPE_IDENTITY()`` on ``INSERT`` Collation Support ----------------- MSSQL specific string types support a collation parameter that creates a column-level specific collation for the column. The collation parameter accepts a Windows Collation Name or a SQL Collation Name. Supported types are MSChar, MSNChar, MSString, MSNVarchar, MSText, and MSNText. For example:: Column('login', String(32, collation='Latin1_General_CI_AS')) will yield:: login VARCHAR(32) COLLATE Latin1_General_CI_AS NULL LIMIT/OFFSET Support -------------------- MSSQL has no support for the LIMIT or OFFSET keysowrds. LIMIT is supported directly through the ``TOP`` Transact SQL keyword:: select.limit will yield:: SELECT TOP n If using SQL Server 2005 or above, LIMIT with OFFSET support is available through the ``ROW_NUMBER OVER`` construct. For versions below 2005, LIMIT with OFFSET usage will fail. Nullability ----------- MSSQL has support for three levels of column nullability. The default nullability allows nulls and is explicit in the CREATE TABLE construct:: name VARCHAR(20) NULL If ``nullable=None`` is specified then no specification is made. In other words the database's configured default is used. This will render:: name VARCHAR(20) If ``nullable`` is ``True`` or ``False`` then the column will be ``NULL` or ``NOT NULL`` respectively. Date / Time Handling -------------------- DATE and TIME are supported. Bind parameters are converted to datetime.datetime() objects as required by most MSSQL drivers, and results are processed from strings if needed. The DATE and TIME types are not available for MSSQL 2005 and previous - if a server version below 2008 is detected, DDL for these types will be issued as DATETIME. Compatibility Levels -------------------- MSSQL supports the notion of setting compatibility levels at the database level. This allows, for instance, to run a database that is compatibile with SQL2000 while running on a SQL2005 database server. ``server_version_info`` will always retrun the database server version information (in this case SQL2005) and not the compatibiility level information. Because of this, if running under a backwards compatibility mode SQAlchemy may attempt to use T-SQL statements that are unable to be parsed by the database server. Known Issues ------------ * No support for more than one ``IDENTITY`` column per table * pymssql has problems with binary and unicode data that this module does **not** work around """ import datetime, decimal, inspect, operator, sys, re from sqlalchemy import sql, schema, exc, util from sqlalchemy.sql import compiler, expression, operators as sql_operators, functions as sql_functions from sqlalchemy.engine import default, base, reflection from sqlalchemy import types as sqltypes from decimal import Decimal as _python_Decimal MS_2008_VERSION = (10,) #MS_2005_VERSION = ?? #MS_2000_VERSION = ?? MSSQL_RESERVED_WORDS = set(['function']) class MSNumeric(sqltypes.Numeric): def result_processor(self, dialect): if self.asdecimal: def process(value): if value is not None: return _python_Decimal(str(value)) else: return value return process else: def process(value): return float(value) return process def bind_processor(self, dialect): def process(value): if isinstance(value, decimal.Decimal): if value.adjusted() < 0: result = "%s0.%s%s" % ( (value < 0 and '-' or ''), '0' * (abs(value.adjusted()) - 1), "".join([str(nint) for nint in value._int])) else: if 'E' in str(value): result = "%s%s%s" % ( (value < 0 and '-' or ''), "".join([str(s) for s in value._int]), "0" * (value.adjusted() - (len(value._int)-1))) else: if (len(value._int) - 1) > value.adjusted(): result = "%s%s.%s" % ( (value < 0 and '-' or ''), "".join([str(s) for s in value._int][0:value.adjusted() + 1]), "".join([str(s) for s in value._int][value.adjusted() + 1:])) else: result = "%s%s" % ( (value < 0 and '-' or ''), "".join([str(s) for s in value._int][0:value.adjusted() + 1])) return result else: return value return process class MSReal(sqltypes.Float): """A type for ``real`` numbers.""" __visit_name__ = 'REAL' def __init__(self): super(MSReal, self).__init__(precision=24) class MSTinyInteger(sqltypes.Integer): __visit_name__ = 'TINYINT' # MSSQL DATE/TIME types have varied behavior, sometimes returning # strings. MSDate/MSTime check for everything, and always # filter bind parameters into datetime objects (required by pyodbc, # not sure about other dialects). class MSDate(sqltypes.Date): def bind_processor(self, dialect): def process(value): if type(value) == datetime.date: return datetime.datetime(value.year, value.month, value.day) else: return value return process _reg = re.compile(r"(\d+)-(\d+)-(\d+)") def result_processor(self, dialect): def process(value): if isinstance(value, datetime.datetime): return value.date() elif isinstance(value, basestring): return datetime.date(*[int(x or 0) for x in self._reg.match(value).groups()]) else: return value return process class MSTime(sqltypes.Time): def __init__(self, precision=None, **kwargs): self.precision = precision super(MSTime, self).__init__() __zero_date = datetime.date(1900, 1, 1) def bind_processor(self, dialect): def process(value): if isinstance(value, datetime.datetime): value = datetime.datetime.combine(self.__zero_date, value.time()) elif isinstance(value, datetime.time): value = datetime.datetime.combine(self.__zero_date, value) return value return process _reg = re.compile(r"(\d+):(\d+):(\d+)(?:\.(\d+))?") def result_processor(self, dialect): def process(value): if isinstance(value, datetime.datetime): return value.time() elif isinstance(value, basestring): return datetime.time(*[int(x or 0) for x in self._reg.match(value).groups()]) else: return value return process class _DateTimeBase(object): def bind_processor(self, dialect): def process(value): if type(value) == datetime.date: return datetime.datetime(value.year, value.month, value.day) else: return value return process class MSDateTime(_DateTimeBase, sqltypes.DATETIME): pass class MSSmallDateTime(_DateTimeBase, sqltypes.DateTime): __visit_name__ = 'SMALLDATETIME' class MSDateTime2(_DateTimeBase, sqltypes.DateTime): __visit_name__ = 'DATETIME2' def __init__(self, precision=None, **kwargs): self.precision = precision class MSDateTimeOffset(sqltypes.TypeEngine): __visit_name__ = 'DATETIMEOFFSET' def __init__(self, precision=None, **kwargs): self.precision = precision class _StringType(object): """Base for MSSQL string types.""" def __init__(self, collation=None): self.collation = collation def __repr__(self): attributes = inspect.getargspec(self.__init__)[0][1:] attributes.extend(inspect.getargspec(_StringType.__init__)[0][1:]) params = {} for attr in attributes: val = getattr(self, attr) if val is not None and val is not False: params[attr] = val return "%s(%s)" % (self.__class__.__name__, ', '.join(['%s=%r' % (k, params[k]) for k in params])) class MSText(_StringType, sqltypes.TEXT): """MSSQL TEXT type, for variable-length text up to 2^31 characters.""" def __init__(self, *args, **kw): """Construct a TEXT. :param collation: Optional, a column-level collation for this string value. Accepts a Windows Collation Name or a SQL Collation Name. """ collation = kw.pop('collation', None) _StringType.__init__(self, collation) sqltypes.Text.__init__(self, *args, **kw) class MSNText(_StringType, sqltypes.UnicodeText): """MSSQL NTEXT type, for variable-length unicode text up to 2^30 characters.""" __visit_name__ = 'NTEXT' def __init__(self, *args, **kwargs): """Construct a NTEXT. :param collation: Optional, a column-level collation for this string value. Accepts a Windows Collation Name or a SQL Collation Name. """ collation = kwargs.pop('collation', None) _StringType.__init__(self, collation) sqltypes.UnicodeText.__init__(self, None, **kwargs) class MSString(_StringType, sqltypes.VARCHAR): """MSSQL VARCHAR type, for variable-length non-Unicode data with a maximum of 8,000 characters.""" def __init__(self, *args, **kw): """Construct a VARCHAR. :param length: Optinal, maximum data length, in characters. :param convert_unicode: defaults to False. If True, convert ``unicode`` data sent to the database to a ``str`` bytestring, and convert bytestrings coming back from the database into ``unicode``. Bytestrings are encoded using the dialect's :attr:`~sqlalchemy.engine.base.Dialect.encoding`, which defaults to `utf-8`. If False, may be overridden by :attr:`sqlalchemy.engine.base.Dialect.convert_unicode`. :param assert_unicode: If None (the default), no assertion will take place unless overridden by :attr:`sqlalchemy.engine.base.Dialect.assert_unicode`. If 'warn', will issue a runtime warning if a ``str`` instance is used as a bind value. If true, will raise an :exc:`sqlalchemy.exc.InvalidRequestError`. :param collation: Optional, a column-level collation for this string value. Accepts a Windows Collation Name or a SQL Collation Name. """ collation = kw.pop('collation', None) _StringType.__init__(self, collation) sqltypes.VARCHAR.__init__(self, *args, **kw) class MSNVarchar(_StringType, sqltypes.NVARCHAR): """MSSQL NVARCHAR type. For variable-length unicode character data up to 4,000 characters.""" def __init__(self, *args, **kw): """Construct a NVARCHAR. :param length: Optional, Maximum data length, in characters. :param collation: Optional, a column-level collation for this string value. Accepts a Windows Collation Name or a SQL Collation Name. """ collation = kw.pop('collation', None) _StringType.__init__(self, collation) sqltypes.NVARCHAR.__init__(self, *args, **kw) class MSChar(_StringType, sqltypes.CHAR): """MSSQL CHAR type, for fixed-length non-Unicode data with a maximum of 8,000 characters.""" def __init__(self, *args, **kw): """Construct a CHAR. :param length: Optinal, maximum data length, in characters. :param convert_unicode: defaults to False. If True, convert ``unicode`` data sent to the database to a ``str`` bytestring, and convert bytestrings coming back from the database into ``unicode``. Bytestrings are encoded using the dialect's :attr:`~sqlalchemy.engine.base.Dialect.encoding`, which defaults to `utf-8`. If False, may be overridden by :attr:`sqlalchemy.engine.base.Dialect.convert_unicode`. :param assert_unicode: If None (the default), no assertion will take place unless overridden by :attr:`sqlalchemy.engine.base.Dialect.assert_unicode`. If 'warn', will issue a runtime warning if a ``str`` instance is used as a bind value. If true, will raise an :exc:`sqlalchemy.exc.InvalidRequestError`. :param collation: Optional, a column-level collation for this string value. Accepts a Windows Collation Name or a SQL Collation Name. """ collation = kw.pop('collation', None) _StringType.__init__(self, collation) sqltypes.CHAR.__init__(self, *args, **kw) class MSNChar(_StringType, sqltypes.NCHAR): """MSSQL NCHAR type. For fixed-length unicode character data up to 4,000 characters.""" def __init__(self, *args, **kw): """Construct an NCHAR. :param length: Optional, Maximum data length, in characters. :param collation: Optional, a column-level collation for this string value. Accepts a Windows Collation Name or a SQL Collation Name. """ collation = kw.pop('collation', None) _StringType.__init__(self, collation) sqltypes.NCHAR.__init__(self, *args, **kw) class MSBinary(sqltypes.Binary): __visit_name__ = 'BINARY' class MSVarBinary(sqltypes.Binary): __visit_name__ = 'VARBINARY' class MSImage(sqltypes.Binary): __visit_name__ = 'IMAGE' class MSBit(sqltypes.TypeEngine): __visit_name__ = 'BIT' class MSBoolean(sqltypes.Boolean): def result_processor(self, dialect): def process(value): if value is None: return None return value and True or False return process def bind_processor(self, dialect): def process(value): if value is True: return 1 elif value is False: return 0 elif value is None: return None else: return value and True or False return process class MSMoney(sqltypes.TypeEngine): __visit_name__ = 'MONEY' class MSSmallMoney(MSMoney): __visit_name__ = 'SMALLMONEY' class MSUniqueIdentifier(sqltypes.TypeEngine): __visit_name__ = "UNIQUEIDENTIFIER" class MSVariant(sqltypes.TypeEngine): __visit_name__ = 'SQL_VARIANT' class MSTypeCompiler(compiler.GenericTypeCompiler): def _extend(self, spec, type_): """Extend a string-type declaration with standard SQL COLLATE annotations. """ if getattr(type_, 'collation', None): collation = 'COLLATE %s' % type_.collation else: collation = None if type_.length: spec = spec + "(%d)" % type_.length return ' '.join([c for c in (spec, collation) if c is not None]) def visit_FLOAT(self, type_): precision = getattr(type_, 'precision', None) if precision is None: return "FLOAT" else: return "FLOAT(%(precision)s)" % {'precision': precision} def visit_REAL(self, type_): return "REAL" def visit_TINYINT(self, type_): return "TINYINT" def visit_DATETIMEOFFSET(self, type_): if type_.precision: return "DATETIMEOFFSET(%s)" % type_.precision else: return "DATETIMEOFFSET" def visit_TIME(self, type_): precision = getattr(type_, 'precision', None) if precision: return "TIME(%s)" % precision else: return "TIME" def visit_DATETIME2(self, type_): precision = getattr(type_, 'precision', None) if precision: return "DATETIME2(%s)" % precision else: return "DATETIME2" def visit_SMALLDATETIME(self, type_): return "SMALLDATETIME" def visit_NTEXT(self, type_): return self._extend("NTEXT", type_) def visit_TEXT(self, type_): return self._extend("TEXT", type_) def visit_VARCHAR(self, type_): return self._extend("VARCHAR", type_) def visit_CHAR(self, type_): return self._extend("CHAR", type_) def visit_NCHAR(self, type_): return self._extend("NCHAR", type_) def visit_NVARCHAR(self, type_): return self._extend("NVARCHAR", type_) def visit_date(self, type_): if self.dialect.server_version_info < MS_2008_VERSION: return self.visit_DATETIME(type_) else: return self.visit_DATE(type_) def visit_time(self, type_): if self.dialect.server_version_info < MS_2008_VERSION: return self.visit_DATETIME(type_) else: return self.visit_TIME(type_) def visit_binary(self, type_): if type_.length: return self.visit_BINARY(type_) else: return self.visit_IMAGE(type_) def visit_BINARY(self, type_): if type_.length: return "BINARY(%s)" % type_.length else: return "BINARY" def visit_IMAGE(self, type_): return "IMAGE" def visit_VARBINARY(self, type_): if type_.length: return "VARBINARY(%s)" % type_.length else: return "VARBINARY" def visit_boolean(self, type_): return self.visit_BIT(type_) def visit_BIT(self, type_): return "BIT" def visit_MONEY(self, type_): return "MONEY" def visit_SMALLMONEY(self, type_): return 'SMALLMONEY' def visit_UNIQUEIDENTIFIER(self, type_): return "UNIQUEIDENTIFIER" def visit_SQL_VARIANT(self, type_): return 'SQL_VARIANT' def _has_implicit_sequence(column): return column.primary_key and \ column.autoincrement and \ isinstance(column.type, sqltypes.Integer) and \ not column.foreign_keys and \ ( column.default is None or ( isinstance(column.default, schema.Sequence) and column.default.optional) ) def _table_sequence_column(tbl): if not hasattr(tbl, '_ms_has_sequence'): tbl._ms_has_sequence = None for column in tbl.c: if getattr(column, 'sequence', False) or _has_implicit_sequence(column): tbl._ms_has_sequence = column break return tbl._ms_has_sequence class MSExecutionContext(default.DefaultExecutionContext): IINSERT = False HASIDENT = False def pre_exec(self): """Activate IDENTITY_INSERT if needed.""" if self.isinsert: tbl = self.compiled.statement.table seq_column = _table_sequence_column(tbl) self.HASIDENT = bool(seq_column) if self.dialect.auto_identity_insert and self.HASIDENT: self.IINSERT = tbl._ms_has_sequence.key in self.compiled_parameters[0] else: self.IINSERT = False if self.IINSERT: self.cursor.execute("SET IDENTITY_INSERT %s ON" % self.dialect.identifier_preparer.format_table(self.compiled.statement.table)) def handle_dbapi_exception(self, e): if self.IINSERT: try: self.cursor.execute("SET IDENTITY_INSERT %s OFF" % self.dialect.identifier_preparer.format_table(self.compiled.statement.table)) except: pass def post_exec(self): """Disable IDENTITY_INSERT if enabled.""" if self.isinsert and not self.executemany and self.HASIDENT and not self.IINSERT: if not self._last_inserted_ids or self._last_inserted_ids[0] is None: if self.dialect.use_scope_identity: self.cursor.execute("SELECT scope_identity() AS lastrowid") else: self.cursor.execute("SELECT @@identity AS lastrowid") row = self.cursor.fetchone() self._last_inserted_ids = [int(row[0])] + self._last_inserted_ids[1:] if self.IINSERT: self.cursor.execute("SET IDENTITY_INSERT %s OFF" % self.dialect.identifier_preparer.format_table(self.compiled.statement.table)) colspecs = { sqltypes.Unicode : MSNVarchar, sqltypes.Numeric : MSNumeric, sqltypes.DateTime : MSDateTime, sqltypes.Date : MSDate, sqltypes.Time : MSTime, sqltypes.String : MSString, sqltypes.Boolean : MSBoolean, sqltypes.Text : MSText, sqltypes.UnicodeText : MSNText, sqltypes.CHAR: MSChar, sqltypes.NCHAR: MSNChar, } ischema_names = { 'int' : sqltypes.INTEGER, 'bigint': sqltypes.BigInteger, 'smallint' : sqltypes.SmallInteger, 'tinyint' : MSTinyInteger, 'varchar' : MSString, 'nvarchar' : MSNVarchar, 'char' : MSChar, 'nchar' : MSNChar, 'text' : MSText, 'ntext' : MSNText, 'decimal' : sqltypes.DECIMAL, 'numeric' : sqltypes.NUMERIC, 'float' : sqltypes.FLOAT, 'datetime' : sqltypes.DATETIME, 'datetime2' : MSDateTime2, 'datetimeoffset' : MSDateTimeOffset, 'date': sqltypes.DATE, 'time': MSTime, 'smalldatetime' : MSSmallDateTime, 'binary' : MSBinary, 'varbinary' : MSVarBinary, 'bit': sqltypes.Boolean, 'real' : MSReal, 'image' : MSImage, 'timestamp': sqltypes.TIMESTAMP, 'money': MSMoney, 'smallmoney': MSSmallMoney, 'uniqueidentifier': MSUniqueIdentifier, 'sql_variant': MSVariant, } class MSSQLCompiler(compiler.SQLCompiler): operators = compiler.OPERATORS.copy() operators.update({ sql_operators.concat_op: '+', sql_operators.match_op: lambda x, y: "CONTAINS (%s, %s)" % (x, y) }) functions = compiler.SQLCompiler.functions.copy() functions.update ( { sql_functions.now: 'CURRENT_TIMESTAMP', sql_functions.current_date: 'GETDATE()', 'length': lambda x: "LEN(%s)" % x, sql_functions.char_length: lambda x: "LEN(%s)" % x } ) def __init__(self, *args, **kwargs): super(MSSQLCompiler, self).__init__(*args, **kwargs) self.tablealiases = {} def get_select_precolumns(self, select): """ MS-SQL puts TOP, it's version of LIMIT here """ if select._distinct or select._limit: s = select._distinct and "DISTINCT " or "" if select._limit: if not select._offset: s += "TOP %s " % (select._limit,) return s return compiler.SQLCompiler.get_select_precolumns(self, select) def limit_clause(self, select): # Limit in mssql is after the select keyword return "" def visit_select(self, select, **kwargs): """Look for ``LIMIT`` and OFFSET in a select statement, and if so tries to wrap it in a subquery with ``row_number()`` criterion. """ if not getattr(select, '_mssql_visit', None) and select._offset: # to use ROW_NUMBER(), an ORDER BY is required. orderby = self.process(select._order_by_clause) if not orderby: raise exc.InvalidRequestError('MSSQL requires an order_by when using an offset.') _offset = select._offset _limit = select._limit select._mssql_visit = True select = select.column(sql.literal_column("ROW_NUMBER() OVER (ORDER BY %s)" % orderby).label("mssql_rn")).order_by(None).alias() limitselect = sql.select([c for c in select.c if c.key!='mssql_rn']) limitselect.append_whereclause("mssql_rn>%d" % _offset) if _limit is not None: limitselect.append_whereclause("mssql_rn<=%d" % (_limit + _offset)) return self.process(limitselect, iswrapper=True, **kwargs) else: return compiler.SQLCompiler.visit_select(self, select, **kwargs) def _schema_aliased_table(self, table): if getattr(table, 'schema', None) is not None: if table not in self.tablealiases: self.tablealiases[table] = table.alias() return self.tablealiases[table] else: return None def visit_table(self, table, mssql_aliased=False, **kwargs): if mssql_aliased: return super(MSSQLCompiler, self).visit_table(table, **kwargs) # alias schema-qualified tables alias = self._schema_aliased_table(table) if alias is not None: return self.process(alias, mssql_aliased=True, **kwargs) else: return super(MSSQLCompiler, self).visit_table(table, **kwargs) def visit_alias(self, alias, **kwargs): # translate for schema-qualified table aliases self.tablealiases[alias.original] = alias kwargs['mssql_aliased'] = True return super(MSSQLCompiler, self).visit_alias(alias, **kwargs) def visit_savepoint(self, savepoint_stmt): util.warn("Savepoint support in mssql is experimental and may lead to data loss.") return "SAVE TRANSACTION %s" % self.preparer.format_savepoint(savepoint_stmt) def visit_rollback_to_savepoint(self, savepoint_stmt): return "ROLLBACK TRANSACTION %s" % self.preparer.format_savepoint(savepoint_stmt) def visit_column(self, column, result_map=None, **kwargs): if column.table is not None and \ (not self.isupdate and not self.isdelete) or self.is_subquery(): # translate for schema-qualified table aliases t = self._schema_aliased_table(column.table) if t is not None: converted = expression._corresponding_column_or_error(t, column) if result_map is not None: result_map[column.name.lower()] = (column.name, (column, ), column.type) return super(MSSQLCompiler, self).visit_column(converted, result_map=None, **kwargs) return super(MSSQLCompiler, self).visit_column(column, result_map=result_map, **kwargs) def visit_binary(self, binary, **kwargs): """Move bind parameters to the right-hand side of an operator, where possible. """ if isinstance(binary.left, expression._BindParamClause) and binary.operator == operator.eq \ and not isinstance(binary.right, expression._BindParamClause): return self.process(expression._BinaryExpression(binary.right, binary.left, binary.operator), **kwargs) else: if (binary.operator is operator.eq or binary.operator is operator.ne) and ( (isinstance(binary.left, expression._FromGrouping) and isinstance(binary.left.element, expression._ScalarSelect)) or \ (isinstance(binary.right, expression._FromGrouping) and isinstance(binary.right.element, expression._ScalarSelect)) or \ isinstance(binary.left, expression._ScalarSelect) or isinstance(binary.right, expression._ScalarSelect)): op = binary.operator == operator.eq and "IN" or "NOT IN" return self.process(expression._BinaryExpression(binary.left, binary.right, op), **kwargs) return super(MSSQLCompiler, self).visit_binary(binary, **kwargs) def visit_insert(self, insert_stmt): insert_select = False if insert_stmt.parameters: insert_select = [p for p in insert_stmt.parameters.values() if isinstance(p, sql.Select)] if insert_select: self.isinsert = True colparams = self._get_colparams(insert_stmt) preparer = self.preparer insert = ' '.join(["INSERT"] + [self.process(x) for x in insert_stmt._prefixes]) if not colparams and not self.dialect.supports_default_values and not self.dialect.supports_empty_insert: raise exc.CompileError( "The version of %s you are using does not support empty inserts." % self.dialect.name) elif not colparams and self.dialect.supports_default_values: return (insert + " INTO %s DEFAULT VALUES" % ( (preparer.format_table(insert_stmt.table),))) else: return (insert + " INTO %s (%s) SELECT %s" % (preparer.format_table(insert_stmt.table), ', '.join([preparer.format_column(c[0]) for c in colparams]), ', '.join([c[1] for c in colparams]))) else: return super(MSSQLCompiler, self).visit_insert(insert_stmt) def label_select_column(self, select, column, asfrom): if isinstance(column, expression.Function): return column.label(None) else: return super(MSSQLCompiler, self).label_select_column(select, column, asfrom) def for_update_clause(self, select): # "FOR UPDATE" is only allowed on "DECLARE CURSOR" which SQLAlchemy doesn't use return '' def order_by_clause(self, select): order_by = self.process(select._order_by_clause) # MSSQL only allows ORDER BY in subqueries if there is a LIMIT if order_by and (not self.is_subquery() or select._limit): return " ORDER BY " + order_by else: return "" class MSDDLCompiler(compiler.DDLCompiler): def get_column_specification(self, column, **kwargs): colspec = self.preparer.format_column(column) + " " + self.dialect.type_compiler.process(column.type) if column.nullable is not None: if not column.nullable or column.primary_key: colspec += " NOT NULL" else: colspec += " NULL" if not column.table: raise exc.InvalidRequestError("mssql requires Table-bound columns in order to generate DDL") seq_col = _table_sequence_column(column.table) # install a IDENTITY Sequence if we have an implicit IDENTITY column if seq_col is column: sequence = getattr(column, 'sequence', None) if sequence: start, increment = sequence.start or 1, sequence.increment or 1 else: start, increment = 1, 1 colspec += " IDENTITY(%s,%s)" % (start, increment) else: default = self.get_column_default_string(column) if default is not None: colspec += " DEFAULT " + default return colspec def visit_drop_index(self, drop): return "\nDROP INDEX %s.%s" % ( self.preparer.quote_identifier(drop.element.table.name), self.preparer.quote(self._validate_identifier(drop.element.name, False), drop.element.quote) ) class MSIdentifierPreparer(compiler.IdentifierPreparer): reserved_words = compiler.IdentifierPreparer.reserved_words.union(MSSQL_RESERVED_WORDS) def __init__(self, dialect): super(MSIdentifierPreparer, self).__init__(dialect, initial_quote='[', final_quote=']') def _escape_identifier(self, value): #TODO: determine MSSQL's escaping rules return value class MSDialect(default.DefaultDialect): name = 'mssql' supports_default_values = True supports_empty_insert = False auto_identity_insert = True execution_ctx_cls = MSExecutionContext text_as_varchar = False use_scope_identity = False max_identifier_length = 128 schema_name = "dbo" colspecs = colspecs ischema_names = ischema_names supports_unicode_binds = True server_version_info = () statement_compiler = MSSQLCompiler ddl_compiler = MSDDLCompiler type_compiler = MSTypeCompiler preparer = MSIdentifierPreparer def __init__(self, auto_identity_insert=True, query_timeout=None, use_scope_identity=False, max_identifier_length=None, schema_name="dbo", **opts): self.auto_identity_insert = bool(auto_identity_insert) self.query_timeout = int(query_timeout or 0) self.schema_name = schema_name self.use_scope_identity = bool(use_scope_identity) self.max_identifier_length = int(max_identifier_length or 0) or \ self.max_identifier_length super(MSDialect, self).__init__(**opts) def do_begin(self, connection): cursor = connection.cursor() cursor.execute("SET IMPLICIT_TRANSACTIONS OFF") cursor.execute("BEGIN TRANSACTION") def do_release_savepoint(self, connection, name): pass @base.connection_memoize(('dialect', 'default_schema_name')) def get_default_schema_name(self, connection): query = "SELECT user_name() as user_name;" user_name = connection.scalar(sql.text(query)) if user_name is not None: # now, get the default schema query = """ SELECT default_schema_name FROM sys.database_principals WHERE name = :user_name AND type = 'S' """ try: default_schema_name = connection.scalar(sql.text(query), user_name=user_name) if default_schema_name is not None: return default_schema_name except: pass return self.schema_name def table_names(self, connection, schema): from sqlalchemy.dialects import information_schema as ischema return ischema.table_names(connection, schema) def uppercase_table(self, t): # convert all names to uppercase -- fixes refs to INFORMATION_SCHEMA for case-senstive DBs, and won't matter for case-insensitive t.name = t.name.upper() if t.schema: t.schema = t.schema.upper() for c in t.columns: c.name = c.name.upper() return t def has_table(self, connection, tablename, schema=None): import sqlalchemy.dialects.information_schema as ischema current_schema = schema or self.get_default_schema_name(connection) columns = self.uppercase_table(ischema.columns) s = sql.select([columns], current_schema and sql.and_(columns.c.table_name==tablename, columns.c.table_schema==current_schema) or columns.c.table_name==tablename, ) c = connection.execute(s) row = c.fetchone() return row is not None @reflection.cache def get_schema_names(self, connection, info_cache=None): import sqlalchemy.dialects.information_schema as ischema s = sql.select([self.uppercase_table(ischema.schemata).c.schema_name], order_by=[ischema.schemata.c.schema_name] ) schema_names = [r[0] for r in connection.execute(s)] return schema_names @reflection.cache def get_table_names(self, connection, schemaname, info_cache=None): import sqlalchemy.dialects.information_schema as ischema current_schema = schemaname or self.get_default_schema_name(connection) tables = self.uppercase_table(ischema.tables) s = sql.select([tables.c.table_name], sql.and_( tables.c.table_schema == current_schema, tables.c.table_type == 'BASE TABLE' ), order_by=[tables.c.table_name] ) table_names = [r[0] for r in connection.execute(s)] return table_names @reflection.cache def get_view_names(self, connection, schemaname=None, info_cache=None): import sqlalchemy.dialects.information_schema as ischema current_schema = schemaname or self.get_default_schema_name(connection) tables = self.uppercase_table(ischema.tables) s = sql.select([tables.c.table_name], sql.and_( tables.c.table_schema == current_schema, tables.c.table_type == 'VIEW' ), order_by=[tables.c.table_name] ) view_names = [r[0] for r in connection.execute(s)] return view_names @reflection.cache def get_indexes(self, connection, tablename, schemaname=None, info_cache=None): current_schema = schemaname or self.get_default_schema_name(connection) full_tname = "%s.%s" % (current_schema, tablename) indexes = [] s = sql.text("exec sp_helpindex '%s'" % full_tname) rp = connection.execute(s) for row in rp: if 'primary key' not in row['index_description']: indexes.append({ 'name' : row['index_name'], 'column_names' : row['index_keys'].split(','), 'unique': 'unique' in row['index_description'] }) return indexes @reflection.cache def get_view_definition(self, connection, viewname, schemaname=None, info_cache=None): import sqlalchemy.dialects.information_schema as ischema current_schema = schemaname or self.get_default_schema_name(connection) views = self.uppercase_table(ischema.views) s = sql.select([views.c.view_definition], sql.and_( views.c.table_schema == current_schema, views.c.table_name == viewname ), ) rp = connection.execute(s) if rp: view_def = rp.scalar() return view_def @reflection.cache def get_columns(self, connection, tablename, schemaname=None, info_cache=None): # Get base columns current_schema = schemaname or self.get_default_schema_name(connection) import sqlalchemy.dialects.information_schema as ischema columns = self.uppercase_table(ischema.columns) s = sql.select([columns], current_schema and sql.and_(columns.c.table_name==tablename, columns.c.table_schema==current_schema) or columns.c.table_name==table_name, order_by=[columns.c.ordinal_position]) c = connection.execute(s) cols = [] while True: row = c.fetchone() if row is None: break (name, type, nullable, charlen, numericprec, numericscale, default, collation) = ( row[columns.c.column_name], row[columns.c.data_type], row[columns.c.is_nullable] == 'YES', row[columns.c.character_maximum_length], row[columns.c.numeric_precision], row[columns.c.numeric_scale], row[columns.c.column_default], row[columns.c.collation_name] ) coltype = self.ischema_names.get(type, None) kwargs = {} if coltype in (MSString, MSChar, MSNVarchar, MSNChar, MSText, MSNText, MSBinary, MSVarBinary, sqltypes.Binary): kwargs['length'] = charlen if collation: kwargs['collation'] = collation if coltype == MSText or (coltype in (MSString, MSNVarchar) and charlen == -1): kwargs.pop('length') if coltype is None: util.warn("Did not recognize type '%s' of column '%s'" % (type, name)) coltype = sqltypes.NULLTYPE if issubclass(coltype, sqltypes.Numeric) and coltype is not MSReal: kwargs['scale'] = numericscale kwargs['precision'] = numericprec coltype = coltype(**kwargs) colargs = [] if default is not None: colargs.append(schema.DefaultClause(sql.text(default))) cdict = { 'name' : name, 'type' : coltype, 'nullable' : nullable, 'default' : default, 'attrs' : colargs } cols.append(cdict) return cols @reflection.cache def get_primary_keys(self, connection, tablename, schemaname=None, info_cache=None): import sqlalchemy.dialects.information_schema as ischema current_schema = schemaname or self.get_default_schema_name(connection) pkeys = [] # Add constraints RR = self.uppercase_table(ischema.ref_constraints) #information_schema.referential_constraints TC = self.uppercase_table(ischema.constraints) #information_schema.table_constraints C = self.uppercase_table(ischema.pg_key_constraints).alias('C') #information_schema.constraint_column_usage: the constrained column R = self.uppercase_table(ischema.pg_key_constraints).alias('R') #information_schema.constraint_column_usage: the referenced column # Primary key constraints s = sql.select([C.c.column_name, TC.c.constraint_type], sql.and_(TC.c.constraint_name == C.c.constraint_name, C.c.table_name == tablename, C.c.table_schema == current_schema) ) c = connection.execute(s) for row in c: if 'PRIMARY' in row[TC.c.constraint_type.name]: pkeys.append(row[0]) return pkeys @reflection.cache def get_foreign_keys(self, connection, tablename, schemaname=None, info_cache=None): import sqlalchemy.dialects.information_schema as ischema current_schema = schemaname or self.get_default_schema_name(connection) # Add constraints RR = self.uppercase_table(ischema.ref_constraints) #information_schema.referential_constraints TC = self.uppercase_table(ischema.constraints) #information_schema.table_constraints C = self.uppercase_table(ischema.pg_key_constraints).alias('C') #information_schema.constraint_column_usage: the constrained column R = self.uppercase_table(ischema.pg_key_constraints).alias('R') #information_schema.constraint_column_usage: the referenced column # Foreign key constraints s = sql.select([C.c.column_name, R.c.table_schema, R.c.table_name, R.c.column_name, RR.c.constraint_name, RR.c.match_option, RR.c.update_rule, RR.c.delete_rule], sql.and_(C.c.table_name == tablename, C.c.table_schema == current_schema, C.c.constraint_name == RR.c.constraint_name, R.c.constraint_name == RR.c.unique_constraint_name, C.c.ordinal_position == R.c.ordinal_position ), order_by = [RR.c.constraint_name, R.c.ordinal_position]) rows = connection.execute(s).fetchall() # group rows by constraint ID, to handle multi-column FKs fkeys = [] fknm, scols, rcols = (None, [], []) for r in rows: scol, rschema, rtbl, rcol, rfknm, fkmatch, fkuprule, fkdelrule = r if rfknm != fknm: if fknm: fkeys.append({ 'name' : fknm, 'constrained_columns' : scols, 'referred_schema' : rschema, 'referred_table' : rtbl, 'referred_columns' : rcols }) fknm, scols, rcols = (rfknm, [], []) if not scol in scols: scols.append(scol) if not rcol in rcols: rcols.append(rcol) if fknm and scols: fkeys.append({ 'name' : fknm, 'constrained_columns' : scols, 'referred_schema' : rschema, 'referred_table' : rtbl, 'referred_columns' : rcols }) return fkeys def reflecttable(self, connection, table, include_columns): import sqlalchemy.dialects.information_schema as ischema # Get base columns if table.schema is not None: current_schema = table.schema else: current_schema = self.get_default_schema_name(connection) info_cache = MSInfoCache() columns = self.get_columns(connection, table.name, current_schema, info_cache) found_table = False for cdict in columns: name = cdict['name'] coltype = cdict['type'] nullable = cdict['nullable'] default = cdict['default'] colargs = cdict['attrs'] found_table = True if include_columns and name not in include_columns: continue table.append_column(schema.Column(name, coltype, nullable=nullable, autoincrement=False, *colargs)) if not found_table: raise exc.NoSuchTableError(table.name) # We also run an sp_columns to check for identity columns: cursor = connection.execute("sp_columns @table_name = '%s', @table_owner = '%s'" % (table.name, current_schema)) ic = None while True: row = cursor.fetchone() if row is None: break col_name, type_name = row[3], row[5] if type_name.endswith("identity") and col_name in table.c: ic = table.c[col_name] ic.autoincrement = True # setup a psuedo-sequence to represent the identity attribute - we interpret this at table.create() time as the identity attribute ic.sequence = schema.Sequence(ic.name + '_identity', 1, 1) # MSSQL: only one identity per table allowed cursor.close() break if not ic is None: try: cursor = connection.execute("select ident_seed(?), ident_incr(?)", table.fullname, table.fullname) row = cursor.fetchone() cursor.close() if not row is None: ic.sequence.start = int(row[0]) ic.sequence.increment = int(row[1]) except: # ignoring it, works just like before pass # Primary key constraints pkeys = self.get_primary_keys(connection, table.name, current_schema, info_cache) for pkey in pkeys: if pkey in table.c: table.primary_key.add(table.c[pkey]) # Foreign key constraints def _gen_fkref(table, rschema, rtbl, rcol): if rschema == current_schema and not table.schema: return '.'.join([rtbl, rcol]) else: return '.'.join([rschema, rtbl, rcol]) fkeys = self.get_foreign_keys(connection, table.name, current_schema, info_cache) for fkey_d in fkeys: fknm = fkey_d['name'] scols = fkey_d['constrained_columns'] rschema = fkey_d['referred_schema'] rtbl = fkey_d['referred_table'] rcols = fkey_d['referred_columns'] # if the reflected schema is the default schema then don't set it because this will # play into the metadata key causing duplicates. if rschema == current_schema and not table.schema: schema.Table(rtbl, table.metadata, autoload=True, autoload_with=connection) else: schema.Table(rtbl, table.metadata, schema=rschema, autoload=True, autoload_with=connection) ##table.append_constraint(schema.ForeignKeyConstraint(scols, [_gen_fkref(table, s, t, c) for s, t, c in rcols], fknm, link_to_name=True)) table.append_constraint(schema.ForeignKeyConstraint(scols, [_gen_fkref(table, rschema, rtbl, c) for c in rcols], fknm, link_to_name=True)) # fixme. I added this for the tests to run. -Randall MSSQLDialect = MSDialect
true
e3c5377d32dc3edf1fb243a4a6830cecd7ed7a68
Python
aSafarpoor/tafsir-swe2-prj
/Backend/raw_certificate_maker_should_be_embeded/certificate.py
UTF-8
2,806
2.734375
3
[]
no_license
from PIL import Image from PIL import ImageFont from PIL import ImageDraw import numpy as np # install: pip install --upgrade arabic-reshaper import arabic_reshaper # install: pip install python-bidi from bidi.algorithm import get_display # install: pip install Pillow from PIL import ImageFont from PIL import Image from PIL import ImageDraw from random import randint def make_certificate(first_name,last_name,passed_day,course_name,teacher_name): print(passed_day) fontFile = "raw_certificate_maker_should_be_embeded/B Koodak Bold.ttf" # this was a 400x400 jpg file # imageFile = "tmp.png" print("hello") # imageFile="raw_certificate_maker_should_be_embeded/images2.jpeg" imageFile="raw_certificate_maker_should_be_embeded/images.jpg" # load the font and image pic = "raw_certificate_maker_should_be_embeded/emza.jpg" font = ImageFont.truetype(fontFile, 66) print(7777777777777777) image = Image.open(imageFile) print(666666666666) text="\n"*32+" گواهی میشود آقا/خانم "+first_name+" "+last_name+" "*(178-(23+len(first_name)+len(last_name))) text+="\n\n"+" دوره "+course_name+" "+" "*(193-len(course_name)-6) text+="\n\n"+" ارائه شده توسط "+teacher_name+ " "*(155-len(teacher_name)) print(3333333333) text+="\n"*2+" را در تاریخ "+str(passed_day[1:-1])+" "*(162) print(99999999999999999) text+="\n\n"+"با موفقیت گذرانده است"+"."+" "*165 print(88888888888) reshaped_text = arabic_reshaper.reshape(text) # correct its shape bidi_text = get_display(reshaped_text) # correct its direction print(99999999999999) # start drawing on image draw = ImageDraw.Draw(image) draw.text((100,100), bidi_text, (255,0,255), font=font) draw = ImageDraw.Draw(image) image2 = Image.open(pic) image2 = image2.resize( (400,620), Image.ANTIALIAS) # img = Image.open('/path/to/file'?, 'r') img_w, img_h = image2.size background = image#Image.new('RGBA', (1440, 900), (255, 255, 255, 255)) bg_w, bg_h = background.size offset = ((bg_w - img_w) // 9, (bg_h - img_h) // 2) background.paste(image2, offset) # background.save('outttt.png') name=str(randint(1,99999999999))+".pdf" adrs="media/folanja/certificate/"+name # save it print(pic) # image.save("raw_certificate_maker_should_be_embeded/media/output.png",resolution=100.0) image.save(adrs,resolution=100.0) print(adrs," dddddddddddddddddd") return adrs # imageFile="raw_certificate_maker_should_be_embeded/media/output.pdf" # return imageFile # print(make_certificate("علی" ,"صفرپور","1392/01/14" , " تاریخ صدر اسلام", "حجت الاسلام مجتهدی"))
true
68c4da92a3468949eb01789f7997d25d6a9d7e58
Python
ipenn/python-process
/demo3.py
UTF-8
651
2.578125
3
[]
no_license
# -*- coding:utf-8 -*- import win32com.client def check_exsit(process_name): WMI = win32com.client.GetObject('winmgmts:') processCodeCov = WMI.ExecQuery('select * from Win32_Process where Name="%s"' % process_name) if len(processCodeCov) > 0: print '%s is exists' % process_name else: print '%s is not exists' % process_name for child in processCodeCov: print '\t', child.Name, child.Properties_('ProcessId'), \ int(child.Properties_('UserModeTime').Value) + int(child.Properties_('KernelModeTime').Value) if __name__ == '__main__': check_exsit('terminal.exe')
true
1e07741968f1db8b79f28fed4f4ff1d6d85c3249
Python
MilaNedic/programiranje-1
/vaje/korita.py
UTF-8
271
2.84375
3
[]
no_license
from functools import lru_cache def korita(n, m, l): if n == 0: return 0 if l > n: return 0 counter = 0 if m * (l + 1) <= n: counter += 1 + korita(n - m, m - 1, l) return counter print(korita(9, 3, 2))
true
a191018a5f06836999967c3c575612f8e9ed3cf8
Python
dsor-isr/isr-flying-arena
/5. Tools/3. Real Time Monitoring/1. real_time_monitor.py
UTF-8
32,066
2.9375
3
[]
no_license
#!/usr/bin/env python3 """ Software program that enables the user to monitor the state of the vehicles during experiments. This tool is important for the developed testing framework because it complements and improves the monitoring setup available in the QGroundControl software, in which the user has to monitor the components of all desired variables in a single window with only two subplots. """ #Import python libraries import os import sys import math import yaml import rospy import threading import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from tf.transformations import euler_from_quaternion from matplotlib.ticker import (AutoMinorLocator, MultipleLocator) # Import ROS messages. from geometry_msgs.msg import PoseStamped from geometry_msgs.msg import TwistStamped from mavros_msgs.msg import PositionTarget from mavros_msgs.msg import AttitudeTarget class REAL_TIME_MONITOR(): """ Class responsible for plotting, in a window, the time evolution of the desired and measured control variables. Methods ------- subscriber(self) Subscribes to the ROS topics with the measured and desired values for the position, attitude and linear and angular velocities of the drone. update_position(self, msg) Updates the variable that stores the position of the drone, in local NED coordinates, provided by the extended Kalman filter of the PX4 autopilot. update_velocity(self, msg) Updates the variable that stores the linear velocity of the vehicle, in local NED coordinates, provided by the extended Kalman filter of the PX4 autopilot. update_attitude(self, msg) Updates the variables that store the attitude of the vehicle provided by the extended Kalman filter of the PX4 autopilot. update_angular_velocity(self, msg) Updates the variable that stores the angular velocity of the vehicle provided by the extended Kalman filter of the PX4 autopilot. update_position_ref(self, msg) Updates the variable that stores the desired position for the vehicle. update_velocity_ref(self, msg) Updates the variable that stores the desired velocity for the vehicle. update_attitude_ref(self, msg) Updates the variable that stores the desired attitude for the vehicle. update_ang_velocity_ref(self, msg) Updates the variable that stores the desired angular velocity for the vehicle. start_window(self) Creates a window to display the time evolution of the selected physical quantities. static_plot_pos(self) Plots the static elements of the position monitoring window. static_plot_vel(self) Plots the static elements of the velocity monitoring window. static_plot_att(self) Plots the static elements of the attitude monitoring window. static_plot_ang_vel(self) Plots the static elements of the angular velocity monitoring window. dynamic_plot(self, _) Plots the dynamic elements of the monitoring window. """ def __init__(self, drone_ns, graph_type, update_freq, source_pos_ref, source_vel_ref, source_att_ref, source_ang_vel_ref, time_window): """ Constructor of the REAL_TIME_MONITOR class. Starts a thread to subscribe to the ROS topics that store the state of the drone. Calls the method that creates a window to display the time evolution of the selected physical quantities. Parameters ---------- drone_ns : str ROS namespace where the data from the PX4 autopilot and the MOCAP system is encapsulated. graph_type : str States the control variable to be monitored. update_freq : float Update frequency of the window. source_pos_ref : str States the source of the position control references. source_vel_ref : str States the source of the velocity control references. source_att_ref : str States the source of the attitude control references. source_ang_vel_ref : str States the source of the angular velocity control references. time_window : float Limits of the time axis. """ self.drone_ns = drone_ns self.graph_type = graph_type self.update_freq = update_freq self.source_pos_ref = source_pos_ref self.source_vel_ref = source_vel_ref self.source_att_ref = source_att_ref self.source_ang_vel_ref = source_ang_vel_ref self.time_window = time_window self.ekf_pos = None; self.ekf_vel = None; self.ekf_att_euler = None; self.ekf_ang_vel = None self.pos_ref = None; self.vel_ref = None; self.att_euler_ref = None; self.ang_vel_ref = None self.pos_ref_flag = False; self.vel_ref_flag = False; self.att_euler_ref_flag = False; self.ang_vel_ref_flag = False self.x = list(np.arange(-self.time_window, 1/self.update_freq, 1/self.update_freq)) self.y1 = [0]*(self.time_window*self.update_freq+1); self.y2 = [0]*(self.time_window*self.update_freq+1) self.y3 = [0]*(self.time_window*self.update_freq+1); self.y4 = [0]*(self.time_window*self.update_freq+1) self.y5 = [0]*(self.time_window*self.update_freq+1); self.y6 = [0]*(self.time_window*self.update_freq+1) self.fig = None; self.ax1 = None; self.ax2 = None; self.ax3 = None self.line1 = None; self.line2 = None; self.line3 = None; self.line4 = None; self.line5 = None; self.line6 = None threading.Thread(target=self.subscriber, daemon=True).start() self.start_window() def subscriber(self): """ Subscribes to the ROS topics with the measured and desired values for the position, attitude and linear and angular velocities of the drone. """ if self.graph_type == 'pos': pos_sub = rospy.Subscriber(self.drone_ns+'/mavros/local_position/pose', PoseStamped, self.update_position) if self.source_pos_ref == 'user': pos_ref_sub= rospy.Subscriber(self.drone_ns+'/mavros/waypoints/position', PoseStamped, self.update_position_ref) elif self.source_pos_ref == 'px4': pos_ref_sub = rospy.Subscriber(self.drone_ns+'/mavros/setpoint_position/local', PoseStamped, self.update_position_ref) elif self.graph_type == 'vel': vel_sub = rospy.Subscriber(self.drone_ns+'/mavros/local_position/velocity_local', TwistStamped, self.update_velocity) if self.source_vel_ref == 'user': vel_ref_sub = rospy.Subscriber(self.drone_ns+'/mavros/waypoints/velocity', PositionTarget, self.update_velocity_ref) elif self.source_vel_ref == 'px4': vel_ref_sub = rospy.Subscriber(self.drone_ns+'/mavros/setpoint_raw/local', PositionTarget, self.update_velocity_ref) elif self.graph_type == 'att': att_sub = rospy.Subscriber(self.drone_ns+'/mavros/local_position/pose', PoseStamped, self.update_attitude) if self.source_att_ref == 'user': att_ref_sub = rospy.Subscriber(self.drone_ns+'/mavros/waypoints/attitude', AttitudeTarget, self.update_attitude_ref) elif self.source_att_ref == 'px4': att_ref_sub = rospy.Subscriber(self.drone_ns+'/mavros/setpoint_raw/attitude', AttitudeTarget, self.update_attitude_ref) elif self.graph_type == 'ang_vel': ang_vel_sub = rospy.Subscriber(self.drone_ns+'/mavros/local_position/velocity_body', TwistStamped, self.update_angular_velocity) if self.source_ang_vel_ref == 'user': ang_vel_ref_sub = rospy.Subscriber(self.drone_ns+'/mavros/waypoints/angular_velocity', AttitudeTarget, self.update_ang_velocity_ref) elif self.ang_vel_ref == 'px4': ang_vel_ref_sub = rospy.Subscriber(self.drone_ns+'/mavros/setpoint_raw/attitude', AttitudeTarget, self.update_ang_velocity_ref) def update_position(self, msg): """ Updates the variable that stores the position of the drone, in local NED coordinates, provided by the extended Kalman filter of the PX4 autopilot. Makes appropriate convertions to the local NED frame since the ROS message stores the position of the drone in the local ENU frame. Parameters ---------- msg : PoseStamped (from geometry_msgs) ROS message containing the extended Kalman filter output value for the position of the drone. """ self.ekf_pos = enu_to_ned(np.array([[msg.pose.position.x], [msg.pose.position.y], [msg.pose.position.z]])) def update_velocity(self, msg): """ Updates the variable that stores the linear velocity of the vehicle, in local NED coordinates, provided by the extended Kalman filter of the PX4 autopilot. Makes appropriate convertions to the local NED frame since the ROS message stores the velocity of the drone in the local ENU frame. Parameters ---------- msg : TwistStamped (from geometry_msgs) ROS message containing the extended Kalman filter output value for the velocity of the drone. """ self.ekf_vel = enu_to_ned(np.array([[msg.twist.linear.x], [msg.twist.linear.y], [msg.twist.linear.z]])) def update_attitude(self, msg): """ Updates the variables that store the attitude of the vehicle provided by the extended Kalman filter of the PX4 autopilot. Makes appropriate convertions to local NED frame since the ROS message stores the attitude of the drone in the local ENU frame. Parameters ---------- msg : PoseStamped (from geometry_msgs) ROS message containing the extended Kalman filter output value for the attitude of the vehicle. """ ros_q = [msg.pose.orientation.x, msg.pose.orientation.y, msg.pose.orientation.z, msg.pose.orientation.w] self.ekf_att_euler = enu_to_ned(np.asarray(euler_from_quaternion(ros_q)).reshape(3,1)) def update_angular_velocity(self, msg): """ Updates the variable that stores the angular velocity of the vehicle provided by the extended Kalman filter of the PX4 autopilot. Makes appropriate convertions to the local NED frame since the ROS message stores the angular velocity of the drone in the local ENU frame. Parameters ---------- msg : TwistStamped (from geometry_msgs) ROS message containing the the extended Kalman filter output value for the angular velocity of the vehicle. """ self.ekf_ang_vel = enu_to_ned(np.array([[msg.twist.angular.x], [msg.twist.angular.y], [msg.twist.angular.z]])) def update_position_ref(self, msg): """ Updates the variable that stores the desired position for the vehicle. Parameters ---------- msg : PoseStamped (from geometry_msgs) ROS message containing the desired position for the vehicle. """ self.pos_ref = enu_to_ned(np.array([[msg.pose.position.x], [msg.pose.position.y], [msg.pose.position.z]])) self.pos_ref_flag = True def update_velocity_ref(self, msg): """ Updates the variable that stores the desired velocity for the vehicle. Parameters ---------- msg : PositionTarget (from mavros_msgs) ROS message containing the desired velocity for the vehicle. """ self.vel_ref = enu_to_ned(np.array([[msg.velocity.x], [msg.velocity.y], [msg.velocity.z]])) self.vel_ref_flag = True def update_attitude_ref(self, msg): """ Updates the variable that stores the desired attitude for the vehicle. Parameters ---------- msg : AttitudeTarget (from mavros_msgs) ROS message containing the desired attitude for the vehicle. """ ros_q = [msg.orientation.x, msg.orientation.y, msg.orientation.z, msg.orientation.w] self.att_euler_ref = enu_to_ned(np.asarray(euler_from_quaternion(ros_q)).reshape(3,1)) self.att_euler_ref_flag = True def update_ang_velocity_ref(self, msg): """ Updates the variable that stores the desired angular velocity for the vehicle. Parameters ---------- msg : AttitudeTarget (from mavros_msgs) ROS message containing the desired angular velocity for the vehicle. """ self.ang_vel_ref = enu_to_ned(np.array([[msg.body_rate.x], [msg.body_rate.y], [msg.body_rate.z]])) self.ang_vel_ref_flag = True def start_window(self): """ Creates a window to display the time evolution of the selected physical quantities. Defines the methods responsible for plotting the static and dynamic elements of the window. Static elements only have to be plotted once. Dynamic elements must be plotted at the frequency selected by the user. """ self.fig, (self.ax1, self.ax2, self.ax3) = plt.subplots(3, 1, figsize=(16,9)) self.line1, = self.ax1.plot([], [], color='black') self.line2, = self.ax1.plot([], [], color='blue') self.line3, = self.ax2.plot([], [], color='black') self.line4, = self.ax2.plot([], [], color='blue') self.line5, = self.ax3.plot([], [], color='black') self.line6, = self.ax3.plot([], [], color='blue') if self.graph_type == 'pos': graph = animation.FuncAnimation(self.fig, self.dynamic_plot, interval=1000/self.update_freq, init_func=self.static_plot_pos, blit=True) elif self.graph_type == 'vel': graph = animation.FuncAnimation(self.fig, self.dynamic_plot, interval=1000/self.update_freq, init_func=self.static_plot_vel, blit=True) elif self.graph_type == 'att': graph = animation.FuncAnimation(self.fig, self.dynamic_plot, interval=1000/self.update_freq, init_func=self.static_plot_att, blit=True) elif self.graph_type == 'ang_vel': graph = animation.FuncAnimation(self.fig, self.dynamic_plot, interval=1000/self.update_freq, init_func=self.static_plot_ang_vel, blit=True) plt.show() def static_plot_pos(self): """ Plots the static elements of the position monitoring window. The static elements are the background of the window, the title of the plots, the axis, the grid, and the label of the axis. """ rect = self.fig.patch rect.set_facecolor('lightblue') plt.subplots_adjust(left=0.08, bottom=0.08, right=0.95, top=0.92, wspace=None, hspace=None) self.line1.set_label('Reference') self.line2.set_label('Real') self.ax1.legend(loc='upper left', prop={'size': 9}) self.line3.set_label('Reference') self.line4.set_label('Real') self.ax2.legend(loc='upper left', prop={'size': 9}) self.line5.set_label('Reference') self.line6.set_label('Real') self.ax3.legend(loc='upper left', prop={'size': 9}) self.ax1.set_facecolor('whitesmoke') self.ax1.set_title('Real Time NED Position Plots: '+self.drone_ns, pad=10, fontsize=20, fontweight='bold') self.ax1.set_xlim(-self.time_window, 0) self.ax1.tick_params(axis='x', which='major', labelsize=8) self.ax1.xaxis.set_major_locator(MultipleLocator(self.time_window/5)) self.ax1.grid(axis='x', which='major', color='#000000', linestyle='--') self.ax1.set_ylabel('North [m]', labelpad=8, fontsize=14, fontweight='bold') self.ax1.set_ylim(-3, 3) self.ax1.tick_params(axis='y', which='major', labelsize=8) self.ax1.tick_params(axis='y', which='minor', labelsize=4) self.ax1.yaxis.set_major_locator(MultipleLocator(1)) self.ax1.yaxis.set_minor_locator(AutoMinorLocator(2)) self.ax1.grid(axis='y', which='major', color='#000000', linestyle='--') self.ax1.grid(axis='y', which='minor', color='#000000', linestyle=':') self.ax2.set_facecolor('whitesmoke') self.ax2.set_xlim(-self.time_window, 0) self.ax2.tick_params(axis='x', which='major', labelsize=8) self.ax2.xaxis.set_major_locator(MultipleLocator(self.time_window/5)) self.ax2.grid(axis='x', which='major', color='#000000', linestyle='--') self.ax2.set_ylabel('East [m]', labelpad=8, fontsize=14, fontweight='bold') self.ax2.set_ylim(-2, 2) self.ax2.tick_params(axis='y', which='major', labelsize=8) self.ax2.tick_params(axis='y', which='minor', labelsize=4) self.ax2.yaxis.set_major_locator(MultipleLocator(1)) self.ax2.yaxis.set_minor_locator(AutoMinorLocator(2)) self.ax2.grid(axis='y', which='major', color='#000000', linestyle='--') self.ax2.grid(axis='y', which='minor', color='#000000', linestyle=':') self.ax3.set_facecolor('whitesmoke') self.ax3.set_xlabel('Time: Last '+str(self.time_window)+' [seconds]', labelpad=5, fontsize=15, fontweight='bold') self.ax3.set_xlim(-self.time_window, 0) self.ax3.tick_params(axis='x', which='major', labelsize=8) self.ax3.xaxis.set_major_locator(MultipleLocator(self.time_window/5)) self.ax3.grid(axis='x', which='major', color='#000000', linestyle='--') self.ax3.set_ylabel('-Down [m]', labelpad=8, fontsize=14, fontweight='bold') self.ax3.set_ylim(0, 2.5) self.ax3.tick_params(axis='y', which='major', labelsize=8) self.ax3.tick_params(axis='y', which='minor', labelsize=4) self.ax3.yaxis.set_major_locator(MultipleLocator(1)) self.ax3.yaxis.set_minor_locator(AutoMinorLocator(2)) self.ax3.grid(axis='y', which='major', color='#000000', linestyle='--') self.ax3.grid(axis='y', which='minor', color='#000000', linestyle=':') return self.line1, self.line2, self.line3, self.line4, self.line5, self.line6 def static_plot_vel(self): """ Plots the static elements of the velocity monitoring window. The static elements are the background of the window, the title of the plots, the axis, the grid, and the label of the axis. """ rect = self.fig.patch rect.set_facecolor('lightblue') plt.subplots_adjust(left=0.08, bottom=0.08, right=0.95, top=0.92, wspace=None, hspace=None) self.line1.set_label('Reference') self.line2.set_label('Real') self.ax1.legend(loc='upper left', prop={'size': 9}) self.line3.set_label('Reference') self.line4.set_label('Real') self.ax2.legend(loc='upper left', prop={'size': 9}) self.line5.set_label('Reference') self.line6.set_label('Real') self.ax3.legend(loc='upper left', prop={'size': 9}) self.ax1.set_facecolor('whitesmoke') self.ax1.set_title('Real Time NED Velocity Plots: '+self.drone_ns, pad=10, fontsize=20, fontweight='bold') self.ax1.set_xlim(-self.time_window, 0) self.ax1.tick_params(axis='x', which='major', labelsize=8) self.ax1.xaxis.set_major_locator(MultipleLocator(self.time_window/5)) self.ax1.grid(axis='x', which='major', color='#000000', linestyle='--') self.ax1.set_ylabel('Vel. North [m/s]', labelpad=8, fontsize=14, fontweight='bold') self.ax1.set_ylim(-3, 3) self.ax1.tick_params(axis='y', which='major', labelsize=8) self.ax1.tick_params(axis='y', which='minor', labelsize=4) self.ax1.yaxis.set_major_locator(MultipleLocator(1)) self.ax1.yaxis.set_minor_locator(AutoMinorLocator(2)) self.ax1.grid(axis='y', which='major', color='#000000', linestyle='--') self.ax1.grid(axis='y', which='minor', color='#000000', linestyle=':') self.ax2.set_facecolor('whitesmoke') self.ax2.set_xlim(-self.time_window, 0) self.ax2.tick_params(axis='x', which='major', labelsize=8) self.ax2.xaxis.set_major_locator(MultipleLocator(self.time_window/5)) self.ax2.grid(axis='x', which='major', color='#000000', linestyle='--') self.ax2.set_ylabel('Vel. East [m/s]', labelpad=8, fontsize=14, fontweight='bold') self.ax2.set_ylim(-3, 3) self.ax2.tick_params(axis='y', which='major', labelsize=8) self.ax2.tick_params(axis='y', which='minor', labelsize=4) self.ax2.yaxis.set_major_locator(MultipleLocator(1)) self.ax2.yaxis.set_minor_locator(AutoMinorLocator(2)) self.ax2.grid(axis='y', which='major', color='#000000', linestyle='--') self.ax2.grid(axis='y', which='minor', color='#000000', linestyle=':') self.ax3.set_facecolor('whitesmoke') self.ax3.set_xlabel('Time: Last '+str(self.time_window)+' [seconds]', labelpad=5, fontsize=15, fontweight='bold') self.ax3.set_xlim(-self.time_window, 0) self.ax3.tick_params(axis='x', which='major', labelsize=8) self.ax3.xaxis.set_major_locator(MultipleLocator(self.time_window/5)) self.ax3.grid(axis='x', which='major', color='#000000', linestyle='--') self.ax3.set_ylabel('-Vel. Down [m/s]', labelpad=8, fontsize=14, fontweight='bold') self.ax3.set_ylim(-3, 3) self.ax3.tick_params(axis='y', which='major', labelsize=8) self.ax3.tick_params(axis='y', which='minor', labelsize=4) self.ax3.yaxis.set_major_locator(MultipleLocator(1)) self.ax3.yaxis.set_minor_locator(AutoMinorLocator(2)) self.ax3.grid(axis='y', which='major', color='#000000', linestyle='--') self.ax3.grid(axis='y', which='minor', color='#000000', linestyle=':') return self.line1, self.line2, self.line3, self.line4, self.line5, self.line6 def static_plot_att(self): """ Plots the static elements of the attitude monitoring window. The static elements are the background of the window, the title of the plots, the axis, the grid, and the label of the axis. """ rect = self.fig.patch rect.set_facecolor('lightblue') plt.subplots_adjust(left=0.08, bottom=0.08, right=0.95, top=0.92, wspace=None, hspace=None) self.line1.set_label('Reference') self.line2.set_label('Real') self.ax1.legend(loc='upper left', prop={'size': 9}) self.line3.set_label('Reference') self.line4.set_label('Real') self.ax2.legend(loc='upper left', prop={'size': 9}) self.line5.set_label('Reference') self.line6.set_label('Real') self.ax3.legend(loc='upper left', prop={'size': 9}) self.ax1.set_facecolor('whitesmoke') self.ax1.set_title('Real Time Attitude Plots: '+self.drone_ns, pad=10, fontsize=20, fontweight='bold') self.ax1.set_xlim(-self.time_window, 0) self.ax1.tick_params(axis='x', which='major', labelsize=8) self.ax1.xaxis.set_major_locator(MultipleLocator(self.time_window/5)) self.ax1.grid(axis='x', which='major', color='#000000', linestyle='--') self.ax1.set_ylabel('Roll [degrees]', labelpad=8, fontsize=14, fontweight='bold') self.ax1.set_ylim(-45, 45) self.ax1.tick_params(axis='y', which='major', labelsize=8) self.ax1.tick_params(axis='y', which='minor', labelsize=4) self.ax1.yaxis.set_major_locator(MultipleLocator(15)) self.ax1.yaxis.set_minor_locator(AutoMinorLocator(2)) self.ax1.grid(axis='y', which='major', color='#000000', linestyle='--') self.ax1.grid(axis='y', which='minor', color='#000000', linestyle=':') self.ax2.set_facecolor('whitesmoke') self.ax2.set_xlim(-self.time_window, 0) self.ax2.tick_params(axis='x', which='major', labelsize=8) self.ax2.xaxis.set_major_locator(MultipleLocator(self.time_window/5)) self.ax2.grid(axis='x', which='major', color='#000000', linestyle='--') self.ax2.set_ylabel('Pitch [degrees]', labelpad=8, fontsize=14, fontweight='bold') self.ax2.set_ylim(-45, 45) self.ax2.tick_params(axis='y', which='major', labelsize=8) self.ax2.tick_params(axis='y', which='minor', labelsize=4) self.ax2.yaxis.set_major_locator(MultipleLocator(15)) self.ax2.yaxis.set_minor_locator(AutoMinorLocator(2)) self.ax2.grid(axis='y', which='major', color='#000000', linestyle='--') self.ax2.grid(axis='y', which='minor', color='#000000', linestyle=':') self.ax3.set_facecolor('whitesmoke') self.ax3.set_xlabel('Time: Last '+str(self.time_window)+' [seconds]', labelpad=5, fontsize=15, fontweight='bold') self.ax3.set_xlim(-self.time_window, 0) self.ax3.tick_params(axis='x', which='major', labelsize=8) self.ax3.xaxis.set_major_locator(MultipleLocator(self.time_window/5)) self.ax3.grid(axis='x', which='major', color='#000000', linestyle='--') self.ax3.set_ylabel('Yaw [degrees]', labelpad=8, fontsize=14, fontweight='bold') self.ax3.set_ylim(-180, 180) self.ax3.tick_params(axis='y', which='major', labelsize=8) self.ax3.tick_params(axis='y', which='minor', labelsize=4) self.ax3.yaxis.set_major_locator(MultipleLocator(60)) self.ax3.yaxis.set_minor_locator(AutoMinorLocator(2)) self.ax3.grid(axis='y', which='major', color='#000000', linestyle='--') self.ax3.grid(axis='y', which='minor', color='#000000', linestyle=':') return self.line1, self.line2, self.line3, self.line4, self.line5, self.line6 def static_plot_ang_vel(self): """ Plots the static elements of the angular velocity monitoring window. The static elements are the background of the window, the title of the plots, the axis, the grid, and the label of the axis. """ rect = self.fig.patch rect.set_facecolor('lightblue') plt.subplots_adjust(left=0.08, bottom=0.08, right=0.95, top=0.92, wspace=None, hspace=None) self.line1.set_label('Reference') self.line2.set_label('Real') self.ax1.legend(loc='upper left', prop={'size': 9}) self.line3.set_label('Reference') self.line4.set_label('Real') self.ax2.legend(loc='upper left', prop={'size': 9}) self.line5.set_label('Reference') self.line6.set_label('Real') self.ax3.legend(loc='upper left', prop={'size': 9}) self.ax1.set_facecolor('whitesmoke') self.ax1.set_title('Real Time Angular Velocity Plots '+self.drone_ns, pad=10, fontsize=20, fontweight='bold') self.ax1.set_xlim(-self.time_window, 0) self.ax1.tick_params(axis='x', which='major', labelsize=8) self.ax1.xaxis.set_major_locator(MultipleLocator(self.time_window/5)) self.ax1.grid(axis='x', which='major', color='#000000', linestyle='--') self.ax1.set_ylabel('Roll Rate [deg/s]', labelpad=8, fontsize=14, fontweight='bold') self.ax1.set_ylim(-180, 180) self.ax1.tick_params(axis='y', which='major', labelsize=8) self.ax1.tick_params(axis='y', which='minor', labelsize=4) self.ax1.yaxis.set_major_locator(MultipleLocator(60)) self.ax1.yaxis.set_minor_locator(AutoMinorLocator(2)) self.ax1.grid(axis='y', which='major', color='#000000', linestyle='--') self.ax1.grid(axis='y', which='minor', color='#000000', linestyle=':') self.ax2.set_facecolor('whitesmoke') self.ax2.set_xlim(-self.time_window, 0) self.ax2.tick_params(axis='x', which='major', labelsize=8) self.ax2.xaxis.set_major_locator(MultipleLocator(self.time_window/5)) self.ax2.grid(axis='x', which='major', color='#000000', linestyle='--') self.ax2.set_ylabel('Pitch Rate [deg/s]', labelpad=8, fontsize=14, fontweight='bold') self.ax2.set_ylim(-180, 180) self.ax2.tick_params(axis='y', which='major', labelsize=8) self.ax2.tick_params(axis='y', which='minor', labelsize=4) self.ax2.yaxis.set_major_locator(MultipleLocator(60)) self.ax2.yaxis.set_minor_locator(AutoMinorLocator(2)) self.ax2.grid(axis='y', which='major', color='#000000', linestyle='--') self.ax2.grid(axis='y', which='minor', color='#000000', linestyle=':') self.ax3.set_facecolor('whitesmoke') self.ax3.set_xlabel('Time: Last '+str(self.time_window)+' [seconds]', labelpad=5, fontsize=15, fontweight='bold') self.ax3.set_xlim(-self.time_window, 0) self.ax3.tick_params(axis='x', which='major', labelsize=8) self.ax3.xaxis.set_major_locator(MultipleLocator(self.time_window/5)) self.ax3.grid(axis='x', which='major', color='#000000', linestyle='--') self.ax3.set_ylabel('Yaw Rate [deg/s]', labelpad=8, fontsize=14, fontweight='bold') self.ax3.set_ylim(-180, 180) self.ax3.tick_params(axis='y', which='major', labelsize=8) self.ax3.tick_params(axis='y', which='minor', labelsize=4) self.ax3.yaxis.set_major_locator(MultipleLocator(60)) self.ax3.yaxis.set_minor_locator(AutoMinorLocator(2)) self.ax3.grid(axis='y', which='major', color='#000000', linestyle='--') self.ax3.grid(axis='y', which='minor', color='#000000', linestyle=':') return self.line1, self.line2, self.line3, self.line4, self.line5, self.line6 def dynamic_plot(self, _): """ Plots the dynamic elements of the monitoring window. The dynamic elements are the plot lines that represent the time evolution of the desired and measured control variables. """ if self.graph_type == 'pos': self.y2 = self.y2[1:]; self.y2.append(self.ekf_pos[0][0]) self.y4 = self.y4[1:]; self.y4.append(self.ekf_pos[1][0]) self.y6 = self.y6[1:]; self.y6.append(-self.ekf_pos[2][0]) self.line2.set_data(self.x, self.y2) self.line4.set_data(self.x, self.y4) self.line6.set_data(self.x, self.y6) if self.pos_ref_flag != False: self.y1 = self.y1[1:]; self.y1.append(self.pos_ref[0][0]) self.y3 = self.y3[1:]; self.y3.append(self.pos_ref[1][0]) self.y5 = self.y5[1:]; self.y5.append(-self.pos_ref[2][0]) self.line1.set_data(self.x, self.y1) self.line3.set_data(self.x, self.y3) self.line5.set_data(self.x, self.y5) elif self.graph_type == 'vel': self.y2 = self.y2[1:]; self.y2.append(self.ekf_vel[0][0]) self.y4 = self.y4[1:]; self.y4.append(self.ekf_vel[1][0]) self.y6 = self.y6[1:]; self.y6.append(-self.ekf_vel[2][0]) self.line2.set_data(self.x, self.y2) self.line4.set_data(self.x, self.y4) self.line6.set_data(self.x, self.y6) if self.vel_ref_flag != False: self.y1 = self.y1[1:]; self.y1.append(self.vel_ref[0][0]) self.y3 = self.y3[1:]; self.y3.append(self.vel_ref[1][0]) self.y5 = self.y5[1:]; self.y5.append(-self.vel_ref[2][0]) self.line1.set_data(self.x, self.y1) self.line3.set_data(self.x, self.y3) self.line5.set_data(self.x, self.y5) elif self.graph_type == 'att': self.y2 = self.y2[1:]; self.y2.append(math.degrees(self.ekf_att_euler[0][0])) self.y4 = self.y4[1:]; self.y4.append(math.degrees(self.ekf_att_euler[1][0])) self.y6 = self.y6[1:]; self.y6.append(math.degrees(self.ekf_att_euler[2][0])) self.line2.set_data(self.x, self.y2) self.line4.set_data(self.x, self.y4) self.line6.set_data(self.x, self.y6) if self.att_euler_ref_flag != False: self.y1 = self.y1[1:]; self.y1.append(math.degrees(self.att_euler_ref[0][0])) self.y3 = self.y3[1:]; self.y3.append(math.degrees(self.att_euler_ref[1][0])) self.y5 = self.y5[1:]; self.y5.append(math.degrees(self.att_euler_ref[2][0])) self.line1.set_data(self.x, self.y1) self.line3.set_data(self.x, self.y3) self.line5.set_data(self.x, self.y5) elif self.graph_type == 'ang_vel': self.y2 = self.y2[1:]; self.y2.append(math.degrees(self.ekf_ang_vel[0][0])) self.y4 = self.y4[1:]; self.y4.append(math.degrees(self.ekf_ang_vel[1][0])) self.y6 = self.y6[1:]; self.y6.append(math.degrees(self.ekf_ang_vel[2][0])) self.line2.set_data(self.x, self.y2) self.line4.set_data(self.x, self.y4) self.line6.set_data(self.x, self.y6) if self.ang_vel_ref_flag != False: self.y1 = self.y1[1:]; self.y1.append(math.degrees(self.ang_vel_ref[0][0])) self.y3 = self.y3[1:]; self.y3.append(math.degrees(self.ang_vel_ref[1][0])) self.y5 = self.y5[1:]; self.y5.append(math.degrees(self.ang_vel_ref[2][0])) self.line1.set_data(self.x, self.y1) self.line3.set_data(self.x, self.y3) self.line5.set_data(self.x, self.y5) return self.line1, self.line2, self.line3, self.line4, self.line5, self.line6 def enu_to_ned(v): """ Converts a 3x1 physical variable from ENU coordinates to NED coordinates. Parameters ---------- v : np.array of floats with shape (3,1) 3x1 physical variable in ENU coordinates. Returns ------- np.array of floats with shape (3,1) 3x1 physical variable in NED coordinates. """ return np.array([[v[1][0]],[v[0][0]],[-v[2][0]]]) def read_yaml_configuration_file(): """ Retrieves, from the yaml configuration file associated with this tool, the update frequency, the limits of the time axis, and the sources of the control references. Returns ------- update_freq Update frequency of the generated window. source_pos_ref States the source of the position control references. source_vel_ref States the source of the velocity control references. source_att_ref States the source of the attitude control references. source_ang_vel_ref States the source of the angular velocity control references. time_window Limits of the time axis. """ with open(os.path.expanduser('~/catkin_ws_python/src/tools/src/real_time_monitor.yaml')) as config_file: configs_dict = yaml.load(config_file, Loader=yaml.FullLoader) update_freq = configs_dict['update_frequency'] source_pos_ref = configs_dict['source_position_ref'] source_vel_ref = configs_dict['source_velocity_ref'] source_att_ref = configs_dict['source_attitude_ref'] source_ang_vel_ref = configs_dict['source_angular_velocity_ref'] time_window = configs_dict['x_axis_time_window'] return update_freq, source_pos_ref, source_vel_ref, source_att_ref, source_ang_vel_ref, time_window if __name__ == "__main__": """ Main function. Starts a ROS node. Reads the yaml configuration file associated with this tool. Creates a window that displays the time evolution of the selected physical quantities. """ rospy.init_node('real_time_monitor', anonymous=True) update_freq, source_pos_ref, source_vel_ref, source_att_ref, source_ang_vel_ref, time_window = read_yaml_configuration_file() monitor = REAL_TIME_MONITOR(sys.argv[1], sys.argv[2], update_freq, source_pos_ref, source_vel_ref, source_att_ref, source_ang_vel_ref, time_window)
true
8f618392ef24da1173ef6617ec00d2beaa3bc447
Python
t9s9/BeeMeter
/streaming/watching.py
UTF-8
653
2.671875
3
[ "MIT" ]
permissive
import threading import cv2 import numpy as np import time class Watcher(threading.Thread): def __init__(self, q, fps=24): super(Watcher, self).__init__() self.running = True self.fps = fps self.q = q def run(self): while self.running: if not self.q.empty(): image = self.q.get() image = np.frombuffer(image, dtype=np.uint8) decimg = cv2.imdecode(image, flags=1) cv2.imshow('Stream', decimg) cv2.waitKey(24) cv2.destroyAllWindows() def stop(self): self.running = False self.join()
true
46e9fee74e5ad131978ca36f22b4d2c071e98559
Python
jerrywindtwow/twow
/py_excercise/separator.py
UTF-8
1,888
2.671875
3
[]
no_license
import math import pandas as pd def separate_to_groups(par_df_first, par_col_name, par_group_num): par_df = par_df_first cols = par_df_first.columns grouped = pd.DataFrame(index=[], columns=cols) str_where = 'group==' + str(par_group_num) for group_id in range(1, par_group_num): par_df = par_df.query(str_where) data_sum = par_df[par_col_name].sum() amount = par_df.shape[0] ave = math.ceil(data_sum / (par_group_num - group_id + 1)) # print(par_df[par_col_name]) # print("avg=",ave) remain = ave abs_diff = data_sum abs_diff_index = -1 for j in range(amount-1, -1, -1): elem_df = par_df[j:j+1] elem_index = elem_df.index[0] elem = par_df.at[elem_index, 'size'] tmp = remain - elem if elem >= ave: par_df.at[elem_index, 'group'] = group_id par_df_first.at[elem_index, 'group'] = group_id grouped = grouped.append(elem_df) abs_diff = data_sum abs_diff_index = -1 break elif tmp >= 0: remain = tmp par_df.at[elem_index, 'group'] = group_id par_df_first.at[elem_index, 'group'] = group_id grouped = grouped.append(elem_df) abs_diff = data_sum abs_diff_index = -1 elif abs(tmp) < abs_diff: abs_diff = abs(tmp) abs_diff_index = elem_index if remain>abs_diff: par_df.at[abs_diff_index, 'group'] = group_id par_df_first.at[abs_diff_index, 'group'] = group_id elem_df = par_df.loc[abs_diff_index] grouped = grouped.append(elem_df) par_df=par_df.query(str_where) grouped = grouped.append(par_df) return grouped
true
7393dabbc2847b52376b1f020e35c25247d79a9f
Python
sakethraogandra/python1
/5.py
UTF-8
127
3
3
[]
no_license
x=28 g=0 inc=0.01 aprox=0.01 count=0 while (g**2-x)<aprox and (g**2-x)<0: g+=inc count+=1 print("guess:"+str(g))
true