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
12648d227fc7ba4ee9197bcc3d64838a83908874
Python
froggengoing/LeetCodeInPython
/20210819[496]Next Greater Element I.py
UTF-8
4,185
3.5625
4
[]
no_license
# The next greater element of some element x in an array is the first greater el # ement that is to the right of x in the same array. # # You are given two distinct 0-indexed integer arrays nums1 and nums2, where nu # ms1 is a subset of nums2. # # For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[ # j] and determine the next greater element of nums2[j] in nums2. If there is no n # ext greater element, then the answer for this query is -1. # # Return an array ans of length nums1.length such that ans[i] is the next great # er element as described above. # # # Example 1: # # # Input: nums1 = [4,1,2], nums2 = [1,3,4,2] # Output: [-1,3,-1] # Explanation: The next greater element for each value of nums1 is as follows: # - 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so t # he answer is -1. # - 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3. # - 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so t # he answer is -1. # # # Example 2: # # # Input: nums1 = [2,4], nums2 = [1,2,3,4] # Output: [3,-1] # Explanation: The next greater element for each value of nums1 is as follows: # - 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3. # - 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so t # he answer is -1. # # # # Constraints: # # # 1 <= nums1.length <= nums2.length <= 1000 # 0 <= nums1[i], nums2[i] <= 104 # All integers in nums1 and nums2 are unique. # All the integers of nums1 also appear in nums2. # # # # Follow up: Could you find an O(nums1.length + nums2.length) solution? Related # Topics Array Hash Table Stack Monotonic Stack # 👍 432 👎 30 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def nextGreaterElement3(self, nums1, nums2): ''' 评论给出的答案,没有使用map保存结果。时间复杂度不行 :param nums1: :param nums2: :return: ''' result = [-1] * len(nums1) stack = [0] for i in range(1, len(nums2)): while len(stack) != 0 and nums2[i] > nums2[stack[-1]]: if nums2[stack[-1]] in nums1: # 时间复杂度为o(n) index = nums1.index(nums2[stack[-1]]) result[index] = nums2[i] stack.pop() stack.append(i) return result def nextGreaterElement(self, nums1, nums2): ''' 使用map保存nums[1] :param nums1: :param nums2: :return: 类似题目,向右找最大值 遍历nums2 得到数值每个元素下一个最大值 遍历nums1,相等则获取对应的下一个最大值 [1, 3, 4, 2] ''' stack = [] n2_dict = {} res = [-1] * len(nums1) for i in range(len(nums2)): while stack and nums2[i] > nums2[stack[-1]]: cur = stack.pop() n2_dict[nums2[cur]] = nums2[i] stack.append(i) for i in range(len(nums1)): if nums1[i] in n2_dict: res[i] = n2_dict[nums1[i]] return res def nextGreaterElement1(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] 暴力解法,遍历nums1,在遍历nums2 """ res = [-1] * len(nums1) for i in range(len(nums1)): is_find = False for j in range(len(nums2)): if nums2[j] == nums1[i]: is_find = True if is_find: if nums2[j] > nums1[i]: res[i] = nums2[j] break return res # leetcode submit region end(Prohibit modification and deleti print(Solution().nextGreaterElement([4, 1, 2], [1, 3, 4, 2])) print(Solution().nextGreaterElement([2, 4], [1, 2, 3, 4])) # a = {'2': 3, 'd': 5} print(Solution().nextGreaterElement1([4, 1, 2], [1, 3, 4, 2])) print(Solution().nextGreaterElement1([2, 4], [1, 2, 3, 4]))
true
87832cbfdd220247c915e8f5bb1cfae804ef1304
Python
durgesh-agrhari/coderspree
/ML/Ayushsingh07_Ayushkumarsingh_2024cse1037_2/gettingstarted/gcdlcm.py
UTF-8
125
3.140625
3
[]
no_license
a=int(input()) b=int(input()) c=1 for i in range(1,a+1): if a%i==0 and b%i==0: c=i l=int(a*b/c) print(c) print(l)
true
229938614f9d193ef45032d8aea7f02e41c715d8
Python
davidmorck/Phyton-test
/kap5,1.py
UTF-8
694
3.140625
3
[]
no_license
namn = ["Daniel Radcliffe", "Rupert Grint", "Emma Watson", "Selena Gomez"] kön = ["man", "man", "kvinna", "kvinna"] ögon = ["brun","blå","brun","brun"] hår = ["brun","röd","brun","brun"] rättnamn=[] Akön = input("ange kön> ") Ahårfärg = input("ange hårfärg> ") Aögonfärg = input("ange ögonfärg> ") Akön = Akön.lower() Ahårfärg = Ahårfärg.lower() Aögonfärg = Aögonfärg.lower() namnVar = 0 antalnamn = len(namn) while (namnVar<antalnamn): if (Akön == kön[namnVar]and Aögonfärg == ögon[namnVar] and Ahårfärg == hår[namnVar]): rättnamn.append(namn[namnVar]) namnVar+=1 if(len(rättnamn)!=0): print("Du liknar:",rättnamn) else: print("Du liknar ingen kändis.")
true
977c05928f1cb401d071531d66eb66cc0540b2bc
Python
DREAMToBeSucessfulDataAnalytics/Data-Analytics-Project
/Superstores Sales Analysis project/ARIMA module.py
UTF-8
5,866
2.625
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env python # coding: utf-8 # In[1]: import warnings import itertools import numpy as np import matplotlib.pyplot as plt warnings.filterwarnings("ignore") plt.style.use('fivethirtyeight') import pandas as pd import statsmodels.api as sm import matplotlib matplotlib.rcParams['axes.labelsize'] = 14 matplotlib.rcParams['xtick.labelsize'] = 12 matplotlib.rcParams['ytick.labelsize'] = 12 matplotlib.rcParams['text.color'] = 'k' # In[2]: df = pd.read_excel("/Users/Apple/Desktop/ML/SampleSuperstore.xls") furniture = df.loc[df['Category'] == 'Furniture'] # In[3]: furniture['Order Date'].min(), furniture['Order Date'].max() # In[4]: cols = ['Row ID', 'Order ID', 'Ship Date', 'Ship Mode', 'Customer ID', 'Customer Name', 'Segment', 'Country', 'City', 'State', 'Postal Code', 'Region', 'Product ID', 'Category', 'Sub-Category', 'Product Name', 'Quantity', 'Discount', 'Profit'] furniture.drop(cols, axis=1, inplace=True) furniture = furniture.sort_values('Order Date') furniture.isnull().sum() # In[5]: furniture = furniture.groupby('Order Date')['Sales'].sum().reset_index() # In[6]: furniture = furniture.set_index('Order Date') furniture.index # In[7]: y = furniture['Sales'].resample('MS').mean() # In[9]: y['2016':] # In[10]: y.plot(figsize=(12, 6)) plt.show() # In[11]: from pylab import rcParams rcParams['figure.figsize'] = 18, 8 decomposition = sm.tsa.seasonal_decompose(y, model='additive') fig = decomposition.plot() plt.show() # In[12]: p = d = q = range(0, 2) pdq = list(itertools.product(p, d, q)) seasonal_pdq = [(x[0], x[1], x[2], 12) for x in list(itertools.product(p, d, q))] print('Examples of parameter combinations for Seasonal ARIMA...') print('SARIMAX: {} x {}'.format(pdq[1], seasonal_pdq[1])) print('SARIMAX: {} x {}'.format(pdq[1], seasonal_pdq[2])) print('SARIMAX: {} x {}'.format(pdq[2], seasonal_pdq[3])) print('SARIMAX: {} x {}'.format(pdq[2], seasonal_pdq[4])) # In[18]: for param in pdq: for param_seasonal in seasonal_pdq: try: mod = sm.tsa.statespace.SARIMAX(y, order=param, seasonal_order=param_seasonal, enforce_stationarity=False, enforce_invertibility=False) results = mod.fit() print('ARIMA{}x{}12 - AIC:{}'.format(param, param_seasonal, results.aic)) except: continue # In[13]: mod = sm.tsa.statespace.SARIMAX(y, order=(1, 1, 1), seasonal_order=(1, 1, 0, 12), enforce_stationarity=False, enforce_invertibility=False) results = mod.fit() print(results.summary().tables[1]) # In[20]: results.plot_diagnostics(figsize=(16, 8)) plt.show() # In[14]: pred = results.get_prediction(start=pd.to_datetime('2017-01-01'), dynamic=False) pred_ci = pred.conf_int() ax = y['2014':].plot(label='observed') pred.predicted_mean.plot(ax=ax, label='One-step ahead Forecast', alpha=.7, figsize=(14, 7)) ax.fill_between(pred_ci.index, pred_ci.iloc[:, 0], pred_ci.iloc[:, 1], color='k', alpha=.2) ax.set_xlabel('Date') ax.set_ylabel('Furniture Sales') plt.legend() plt.show() # In[15]: y_forecasted = pred.predicted_mean y_truth = y['2017-01-01':] mse = ((y_forecasted - y_truth) ** 2).mean() print('The Mean Squared Error of our forecasts is {}'.format(round(mse, 2))) # In[16]: print('The Root Mean Squared Error of our forecasts is {}'.format(round(np.sqrt(mse), 2))) # In[17]: pred_uc = results.get_forecast(steps=100) pred_ci = pred_uc.conf_int() ax = y.plot(label='observed', figsize=(14, 7)) pred_uc.predicted_mean.plot(ax=ax, label='Forecast') ax.fill_between(pred_ci.index, pred_ci.iloc[:, 0], pred_ci.iloc[:, 1], color='k', alpha=.25) ax.set_xlabel('Date') ax.set_ylabel('Furniture Sales') plt.legend() plt.show() # In[22]: furniture = df.loc[df['Category'] == 'Furniture'] office = df.loc[df['Category'] == 'Office Supplies'] furniture.shape, office.shape # In[23]: cols = ['Row ID', 'Order ID', 'Ship Date', 'Ship Mode', 'Customer ID', 'Customer Name', 'Segment', 'Country', 'City', 'State', 'Postal Code', 'Region', 'Product ID', 'Category', 'Sub-Category', 'Product Name', 'Quantity', 'Discount', 'Profit'] furniture.drop(cols, axis=1, inplace=True) office.drop(cols, axis=1, inplace=True) furniture = furniture.sort_values('Order Date') office = office.sort_values('Order Date') furniture = furniture.groupby('Order Date')['Sales'].sum().reset_index() office = office.groupby('Order Date')['Sales'].sum().reset_index() furniture = furniture.set_index('Order Date') office = office.set_index('Order Date') y_furniture = furniture['Sales'].resample('MS').mean() y_office = office['Sales'].resample('MS').mean() furniture = pd.DataFrame({'Order Date':y_furniture.index, 'Sales':y_furniture.values}) office = pd.DataFrame({'Order Date': y_office.index, 'Sales': y_office.values}) store = furniture.merge(office, how='inner', on='Order Date') store.rename(columns={'Sales_x': 'furniture_sales', 'Sales_y': 'office_sales'}, inplace=True) store.head() # In[24]: plt.figure(figsize=(20, 8)) plt.plot(store['Order Date'], store['furniture_sales'], 'b-', label = 'furniture') plt.plot(store['Order Date'], store['office_sales'], 'r-', label = 'office supplies') plt.xlabel('Date'); plt.ylabel('Sales'); plt.title('Sales of Furniture and Office Supplies') plt.legend(); # In[25]: first_date = store.ix[np.min(list(np.where(store['office_sales'] > store['furniture_sales'])[0])), 'Order Date'] print("Office supplies first time produced higher sales than furniture is {}.".format(first_date.date())) # In[ ]:
true
3ac85fb428da23dee796134a6b3ddb322bd23aa5
Python
EnjiRouz/IntelligentSystems
/NeuralNetwork/neural_network.py
UTF-8
2,025
3.5
4
[]
no_license
import numpy as np # входной и выходной слои input_layer = np.array(([0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]), dtype=float) output_layer = np.array(([0], [1], [1], [0]), dtype=float) # логистическая активационная функция (функция активации сигмоиды) def sigmoid(t): return 1 / (1 + np.exp(-t)) # производная активационной функции def sigmoid_derivative(p): return p * (1 - p) class NeuralNetwork: def __init__(self, input_layer, output_layer): self.input = input_layer self.weights1 = np.random.rand(self.input.shape[1], 4) self.weights2 = np.random.rand(4, 1) self.output_layer = output_layer self.output = np.zeros(output_layer.shape) def feedforward(self): self.layer1 = sigmoid(np.dot(self.input, self.weights1)) self.layer2 = sigmoid(np.dot(self.layer1, self.weights2)) return self.layer2 def back_propagation(self): self.weights1 += np.dot(self.input.T, np.dot(2 * (self.output_layer - self.output) * sigmoid_derivative(self.output), self.weights2.T) * sigmoid_derivative(self.layer1)) self.weights2 += np.dot(self.layer1.T, 2 * (self.output_layer - self.output) * sigmoid_derivative(self.output)) def train(self): self.output = self.feedforward() self.back_propagation() if __name__ == '__main__': NN = NeuralNetwork(input_layer, output_layer) for i in range(1501): if i % 500 == 0: print("For iteration # " + str(i)) print("Input : \n" + str(input_layer)) print("Expected Output: \n" + str(output_layer)) print("Predicted Output: \n" + str(NN.feedforward())) print("Loss: " + str(np.mean(np.square(output_layer - NN.feedforward())))) print("Weights of the first layer:\n"+str(NN.weights1)+"\nWeights of the second layer:\n"+str(NN.weights2)) print("\n") NN.train()
true
99b3ee9d016348996f41de34379d66a5909a35f1
Python
Josephine-coding/Brazilian_ecommerce
/data.py
UTF-8
3,692
2.609375
3
[ "Apache-2.0" ]
permissive
import pandas as pd import mysql.connector import csv import sqlalchemy import pymysql engine = sqlalchemy.create_engine("mysql+pymysql://student:mdpSQL2021@localhost/e_commerce") #Connect to database mydb = mysql.connector.connect( host="localhost", user="student", password="mdpSQL2021", database='e_commerce' ) mycursor = mydb.cursor() # Data to Tables customers = pd.read_csv("data/olist_customers_dataset.csv") customers_df = pd.DataFrame(customers, columns= ['customer_id','customer_unique_id','customer_zip_code_prefix', 'customer_city', 'customer_state']) print(customers_df.shape) # we get rid of any duplicates on the customer_unique_id column customers_df.drop_duplicates(subset=['customer_unique_id'], inplace= True) print(customers_df.shape) # import the dataframe into sql table customers_df.to_sql('Customers', engine, if_exists='replace', index= False) geolocation = pd.read_csv("data/olist_geolocation_dataset.csv") geolocation_df = pd.DataFrame(geolocation, columns= ['geolocation_zip_code_prefix', 'geolocation_lat', 'geolocation_lng', 'geolocation_city', 'geolocation_state']) print(geolocation_df.shape) geolocation_df.drop_duplicates(subset=['geolocation_zip_code_prefix'], inplace= True) print(geolocation_df.shape) geolocation_df.to_sql('Geolocation', engine, if_exists='replace', index= False) order_items = pd.read_csv("data/olist_order_items_dataset.csv") order_items_df = pd.DataFrame(order_items, columns= ['order_id', 'order_item_id', 'product_id', 'seller_id', 'shipping_limit_date', 'price', 'freight_value']) print(order_items_df.shape) order_items_df.to_sql('Order_items', engine, if_exists='replace', index= False) order_payments = pd.read_csv("data/olist_order_payments_dataset.csv") payments_df = pd.DataFrame(order_payments, columns= ['order_id','payment_sequential', 'payment_type', 'payment_installments', 'payment_value']) print(payments_df.shape) payments_df.to_sql('Order_payments', engine, if_exists='replace', index= False) order_reviews = pd.read_csv("data/olist_order_reviews_dataset.csv") reviews_df = pd.DataFrame(order_reviews, columns= ['review_id','order_id', 'review_score', 'review_comment_title','review_comment_message', 'review_creation_date', 'review_answer_timestamp']) print(reviews_df.shape) reviews_df.to_sql('Order_reviews', engine, if_exists='replace', index= False) #print(reviews_df.describe()) orders = pd.read_csv("data/olist_orders_dataset.csv") orders_df = pd.DataFrame(orders, columns= ['order_id', 'customer_id', 'order_status', 'order_purchase_timestamp', 'order_approved_at', 'order_delivered_carrier_date', 'order_delivered_customer_date', 'order_estimated_delivery_date']) print(orders_df.shape) orders_df.drop_duplicates(subset=['order_id'], inplace= True) print(orders_df.shape) orders_df.to_sql('Orders', engine, if_exists='replace', index= False) products = pd.read_csv("data/olist_products_dataset.csv") products_df = pd.DataFrame(products, columns= ['product_id', 'product_category_name', 'product_name_lenght', 'product_description_lenght', 'product_photos_qty', 'product_weight_g', 'product_length_cm', 'product_height_cm', 'product_width_cm']) print(products_df.shape) products_df.drop_duplicates(subset=['product_id'], inplace= True) print(products_df.shape) products_df.to_sql('Products', engine, if_exists='replace', index= False) sellers = pd.read_csv("data/olist_sellers_dataset.csv") sellers_df = pd.DataFrame(sellers, columns= ['seller_id', 'seller_zip_code_prefix', 'seller_city', 'seller_state']) print(sellers_df.shape) sellers_df.drop_duplicates(subset=['seller_id'], inplace= True) print(sellers_df.shape) sellers_df.to_sql('Sellers', engine, if_exists='replace', index= False)
true
01ff5885130f13a6926944c70ab559330af69f62
Python
friedrich-schotte/Lauecollect
/serial_port_emulator_windows.py
UTF-8
3,664
3.0625
3
[]
permissive
#!/usr/bin/env python """ Setup: - Install the software package 'com0com' from https://sourceforge.net/projects/com0com - Run: Start > Programs > com0com > Setup - Create pairs of emulated com ports: COM3 & COM4, COM5 & COM6, .... Author: Friedrich Schotte Date created: 2021-10-03 Date last modified: 2021-10-03 Revision comment: First port of pair my be even or odd numbered """ __version__ = "1.0.1" import logging class serial_port_emulator: _port = None messages = [] @property def port(self): self.connect() return self._port def connect(self): from serial import Serial if self._port is None: port_names = emulator_port_names() if not port_names: self.error("Please install 'com0com' from https://sourceforge.net/projects/com0com.") else: for port_name in port_names: try: self._port = Serial(port_name) break except OSError: pass if self._port: logging.info(f"Using port pair {self.name} <-> {self.paired_name}") else: self.error(f"All available emulated serial port in use {port_names}.") self.error(f"Use Programs > com0com > Setup to add more.") def error(self, message): if message not in self.messages: logging.error(message) self.messages.append(message) def read(self): if self.port: data = self.port.read(1) n_bytes = self.port.in_waiting if n_bytes: data += self.port.read(n_bytes) else: data = b'' return data def write(self, data): if self.port: self.port.write(data) @property def name(self): if self._port: name = self._port.name else: name = "" return name @property def paired_name(self): if self._port: name = emulated_port_name(self._port.name) else: name = "" return name def check_available_ports(): import serial.tools.list_ports lst = serial.tools.list_ports.comports() for element in lst: print(element.device,element.description) def emulated_port_name_pairs(): port_names = all_emulated_port_names() n_pairs = len(port_names) // 2 port_names = port_names[0:n_pairs*2] pairs = list(zip(port_names[0::2], port_names[1::2])) return pairs def emulator_port_names(): """Ports available for the instrument simulator: COM3, COM5, ...""" names = [pair[0] for pair in emulated_port_name_pairs()] return names def emulated_port_names(): """Ports available for the user of an simulated instrument: COM4, COM6, ...""" names = [pair[1] for pair in emulated_port_name_pairs()] return names def emulated_port_name(emulator_port_name): """COM3 -> COM4, COM5 -> COM6""" name = "" for pair in emulated_port_name_pairs(): if emulator_port_name == pair[0]: name = pair[1] return name def all_emulated_port_names(): from serial.tools.list_ports import comports keyword = "serial port emulator" names = sorted([port.device for port in comports() if keyword in port.description]) return names if __name__ == '__main__': msg_format = "%(asctime)s %(levelname)s: %(message)s" logging.basicConfig(level=logging.DEBUG, format=msg_format) self = serial_port_emulator() print("emulated_port_names()") print("self.read()")
true
6a4c93792fd731bc03ed82f7304c5c032aa2b511
Python
RustPython/RustPython
/Lib/test/test_sys_setprofile.py
UTF-8
13,771
2.640625
3
[ "CC-BY-4.0", "MIT", "Python-2.0" ]
permissive
import gc import pprint import sys import unittest class TestGetProfile(unittest.TestCase): def setUp(self): sys.setprofile(None) def tearDown(self): sys.setprofile(None) def test_empty(self): self.assertIsNone(sys.getprofile()) def test_setget(self): def fn(*args): pass sys.setprofile(fn) self.assertIs(sys.getprofile(), fn) class HookWatcher: def __init__(self): self.frames = [] self.events = [] def callback(self, frame, event, arg): if (event == "call" or event == "return" or event == "exception"): self.add_event(event, frame) def add_event(self, event, frame=None): """Add an event to the log.""" if frame is None: frame = sys._getframe(1) try: frameno = self.frames.index(frame) except ValueError: frameno = len(self.frames) self.frames.append(frame) self.events.append((frameno, event, ident(frame))) def get_events(self): """Remove calls to add_event().""" disallowed = [ident(self.add_event.__func__), ident(ident)] self.frames = None return [item for item in self.events if item[2] not in disallowed] class ProfileSimulator(HookWatcher): def __init__(self, testcase): self.testcase = testcase self.stack = [] HookWatcher.__init__(self) def callback(self, frame, event, arg): # Callback registered with sys.setprofile()/sys.settrace() self.dispatch[event](self, frame) def trace_call(self, frame): self.add_event('call', frame) self.stack.append(frame) def trace_return(self, frame): self.add_event('return', frame) self.stack.pop() def trace_exception(self, frame): self.testcase.fail( "the profiler should never receive exception events") def trace_pass(self, frame): pass dispatch = { 'call': trace_call, 'exception': trace_exception, 'return': trace_return, 'c_call': trace_pass, 'c_return': trace_pass, 'c_exception': trace_pass, } class TestCaseBase(unittest.TestCase): def check_events(self, callable, expected): events = capture_events(callable, self.new_watcher()) if events != expected: self.fail("Expected events:\n%s\nReceived events:\n%s" % (pprint.pformat(expected), pprint.pformat(events))) class ProfileHookTestCase(TestCaseBase): def new_watcher(self): return HookWatcher() # TODO: RUSTPYTHON @unittest.expectedFailure def test_simple(self): def f(p): pass f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) # TODO: RUSTPYTHON @unittest.expectedFailure def test_exception(self): def f(p): 1/0 f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) # TODO: RUSTPYTHON @unittest.expectedFailure def test_caught_exception(self): def f(p): try: 1/0 except: pass f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) # TODO: RUSTPYTHON @unittest.expectedFailure def test_caught_nested_exception(self): def f(p): try: 1/0 except: pass f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) # TODO: RUSTPYTHON @unittest.expectedFailure def test_nested_exception(self): def f(p): 1/0 f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), # This isn't what I expected: # (0, 'exception', protect_ident), # I expected this again: (1, 'return', f_ident), ]) # TODO: RUSTPYTHON @unittest.expectedFailure def test_exception_in_except_clause(self): def f(p): 1/0 def g(p): try: f(p) except: try: f(p) except: pass f_ident = ident(f) g_ident = ident(g) self.check_events(g, [(1, 'call', g_ident), (2, 'call', f_ident), (2, 'return', f_ident), (3, 'call', f_ident), (3, 'return', f_ident), (1, 'return', g_ident), ]) # TODO: RUSTPYTHON @unittest.expectedFailure def test_exception_propagation(self): def f(p): 1/0 def g(p): try: f(p) finally: p.add_event("falling through") f_ident = ident(f) g_ident = ident(g) self.check_events(g, [(1, 'call', g_ident), (2, 'call', f_ident), (2, 'return', f_ident), (1, 'falling through', g_ident), (1, 'return', g_ident), ]) # TODO: RUSTPYTHON @unittest.expectedFailure def test_raise_twice(self): def f(p): try: 1/0 except: 1/0 f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) # TODO: RUSTPYTHON @unittest.expectedFailure def test_raise_reraise(self): def f(p): try: 1/0 except: raise f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) # TODO: RUSTPYTHON @unittest.expectedFailure def test_raise(self): def f(p): raise Exception() f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) # TODO: RUSTPYTHON @unittest.expectedFailure def test_distant_exception(self): def f(): 1/0 def g(): f() def h(): g() def i(): h() def j(p): i() f_ident = ident(f) g_ident = ident(g) h_ident = ident(h) i_ident = ident(i) j_ident = ident(j) self.check_events(j, [(1, 'call', j_ident), (2, 'call', i_ident), (3, 'call', h_ident), (4, 'call', g_ident), (5, 'call', f_ident), (5, 'return', f_ident), (4, 'return', g_ident), (3, 'return', h_ident), (2, 'return', i_ident), (1, 'return', j_ident), ]) # TODO: RUSTPYTHON @unittest.expectedFailure def test_generator(self): def f(): for i in range(2): yield i def g(p): for i in f(): pass f_ident = ident(f) g_ident = ident(g) self.check_events(g, [(1, 'call', g_ident), # call the iterator twice to generate values (2, 'call', f_ident), (2, 'return', f_ident), (2, 'call', f_ident), (2, 'return', f_ident), # once more; returns end-of-iteration with # actually raising an exception (2, 'call', f_ident), (2, 'return', f_ident), (1, 'return', g_ident), ]) # TODO: RUSTPYTHON @unittest.expectedFailure def test_stop_iteration(self): def f(): for i in range(2): yield i def g(p): for i in f(): pass f_ident = ident(f) g_ident = ident(g) self.check_events(g, [(1, 'call', g_ident), # call the iterator twice to generate values (2, 'call', f_ident), (2, 'return', f_ident), (2, 'call', f_ident), (2, 'return', f_ident), # once more to hit the raise: (2, 'call', f_ident), (2, 'return', f_ident), (1, 'return', g_ident), ]) class ProfileSimulatorTestCase(TestCaseBase): def new_watcher(self): return ProfileSimulator(self) # TODO: RUSTPYTHON @unittest.expectedFailure def test_simple(self): def f(p): pass f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) # TODO: RUSTPYTHON @unittest.expectedFailure def test_basic_exception(self): def f(p): 1/0 f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) # TODO: RUSTPYTHON @unittest.expectedFailure def test_caught_exception(self): def f(p): try: 1/0 except: pass f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident), ]) # TODO: RUSTPYTHON @unittest.expectedFailure def test_distant_exception(self): def f(): 1/0 def g(): f() def h(): g() def i(): h() def j(p): i() f_ident = ident(f) g_ident = ident(g) h_ident = ident(h) i_ident = ident(i) j_ident = ident(j) self.check_events(j, [(1, 'call', j_ident), (2, 'call', i_ident), (3, 'call', h_ident), (4, 'call', g_ident), (5, 'call', f_ident), (5, 'return', f_ident), (4, 'return', g_ident), (3, 'return', h_ident), (2, 'return', i_ident), (1, 'return', j_ident), ]) # TODO: RUSTPYTHON @unittest.expectedFailure # bpo-34125: profiling method_descriptor with **kwargs def test_unbound_method(self): kwargs = {} def f(p): dict.get({}, 42, **kwargs) f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident)]) # TODO: RUSTPYTHON @unittest.expectedFailure # Test an invalid call (bpo-34126) def test_unbound_method_no_args(self): def f(p): dict.get() f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident)]) # TODO: RUSTPYTHON @unittest.expectedFailure # Test an invalid call (bpo-34126) def test_unbound_method_invalid_args(self): def f(p): dict.get(print, 42) f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident)]) # TODO: RUSTPYTHON @unittest.expectedFailure # Test an invalid call (bpo-34125) def test_unbound_method_no_keyword_args(self): kwargs = {} def f(p): dict.get(**kwargs) f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident)]) # TODO: RUSTPYTHON @unittest.expectedFailure # Test an invalid call (bpo-34125) def test_unbound_method_invalid_keyword_args(self): kwargs = {} def f(p): dict.get(print, 42, **kwargs) f_ident = ident(f) self.check_events(f, [(1, 'call', f_ident), (1, 'return', f_ident)]) def ident(function): if hasattr(function, "f_code"): code = function.f_code else: code = function.__code__ return code.co_firstlineno, code.co_name def protect(f, p): try: f(p) except: pass protect_ident = ident(protect) def capture_events(callable, p=None): if p is None: p = HookWatcher() # Disable the garbage collector. This prevents __del__s from showing up in # traces. old_gc = gc.isenabled() gc.disable() try: sys.setprofile(p.callback) protect(callable, p) sys.setprofile(None) finally: if old_gc: gc.enable() return p.get_events()[1:-1] def show_events(callable): import pprint pprint.pprint(capture_events(callable)) if __name__ == "__main__": unittest.main()
true
77cbc7abd5ec5ae0d6be283131be27b2d816332c
Python
omnomnomot/bookmark-sync-kindle-tinycards
/kindleSync.py
UTF-8
645
2.53125
3
[]
no_license
from tinycards import Tinycards from tinycards.model import Deck from PyDictionary import PyDictionary import yaml, json, sys import config dictionary=PyDictionary() tinycards = Tinycards(config.TINY_CARDS_CREDENTIALS['email'], config.TINY_CARDS_CREDENTIALS['password']) deck = Deck('12 Rules Of Life') deck = tinycards.create_deck(deck) fh = open('words.txt') for word in fh: meaning = str(dictionary.meaning(word)) translation_table = dict.fromkeys(map(ord, '{}[]\''), None) meaning = meaning.translate(translation_table) print(meaning) deck.add_card((word, meaning)) fh.close() tinycards.update_deck(deck)
true
9d143e2ab98cad71f133f6d8664b6110f28d29c1
Python
chenjie5612816/japanese
/chapter1/cha2-1.py
UTF-8
681
4.0625
4
[]
no_license
# -*- coding: utf8 -*- # 根据给定的年月日以数字形式打印出日期 months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] endings = ['st','nd','rd'] + 17 * ['th']\ +['st','nd','rd'] +7 * ['th']\ +['st'] year = raw_input('Year:') month = raw_input('Month (1-12):') day = raw_input('Day(1-31):') month_number = int(month) day_number = int(day) month_name = months[month_number-1] ordinal = day + endings[day_number-1] print month_name + ' ' + ordinal + ', ' +year
true
d7695f3b6cd1c1a8aba03478f9e9c17c11bbffb3
Python
Joaodevgit/Reccomender-System
/AlgoritmoML/CleanAndTransformData.py
UTF-8
13,479
3.5
4
[ "MIT" ]
permissive
import csv import json import pandas as pd import ast def read_data(filename, qty_users): """ Method that reads from a csv file and returns a list movies rated from the users :param filename: csv file path where all user ratings are is located (this file must be in csv format and must contain the following columns: userId, movieId, rating) :type filename: string :param qty_users: quantity of users id's who rated movies :type qty_users: integer (between 1 and 200000) :return: list of transactions with all users' movies """ with open(filename, encoding='utf-8') as fp: reader = csv.reader(fp) next(reader, None) # skip the headers USERID, MOVIETITLE, RATING = 0, 1, 2 ratings_list = [] tot_users = str(qty_users + 1) for line in reader: if line[USERID] == tot_users: break new_line = [line[USERID], line[MOVIETITLE], line[RATING]] ratings_list.append(new_line) return ratings_list # print(read_data('datasets/movies.csv', qtyUsers)) def get_movies_dict(filename): """ Method that converts a csv file with the movies information (movieId, title, genres) into a dictionary :param filename: path where the csv file is located (this file must be in csv format and must contain the following columns: movieId, title, genres) :type filename: string :return: dictionary that contains the following format: { MovieId: { Title: ..., Genres = [] }, ... } """ with open(filename, encoding='utf-8') as fp: reader = csv.reader(fp) next(reader, None) # skip the headers movies_dict = {} # moviesDict = { MovieId: { Title: ... , Genres = [] } } MOVIEID, TITLE, GENRES = 0, 1, 2 for line in reader: genres = line[GENRES].split('|') if line[MOVIEID] in movies_dict.keys(): movies_dict[line[MOVIEID]].append({"Title": line[TITLE], "Genres": genres}) else: movies_dict[line[MOVIEID]] = {"Title": line[TITLE], "Genres": genres} return movies_dict # print(json.dumps(get_movies_dict('movies.csv'), ensure_ascii=False, indent=2)) def write_new_mov_csv_files(old_filename, new_filename, qty_users): """ Method that, from the csv file of original movielens user ratings (userId, movieId, rating, timestamp), will write to a new csv file (userId, movieTitle, rating) :param old_filename: path where the csv file is located (this file must be in csv format and must contain the following columns: userId, movieId, rating, timestamp) :type old_filename string :param new_filename: path where the new file will be located (this file must be in csv format) :type new_filename: string :param qty_users: quantity of users id's who rated movies :type qty_users: integer (between 1 and 200000) """ with open(new_filename, 'w', newline='', encoding='utf-8') as new_fp: items = read_data(old_filename, qty_users) write = csv.writer(new_fp) for line in items: write.writerow(line) new_fp.close() # 1º Descomentar esta linha # write_new_mov_csv_files('original_ratings.csv', 'new_ratings.csv') def write_sample_movies(original_filename, sampled_movies_filename, number_movies): """ Method that, from csv file of the original movielens movies (movieId, title, genres), will write to a new csv file containing sampled movies (reduced to a certain number of movies) :param original_filename: path where the csv file is located (this file must be in csv format and must contain the following columns: movieId, title, genres) :type original_filename: string :param sampled_movies_filename: path where the new file will be located (this file must be in csv format) :type sampled_movies_filename: string :param number_movies: number of movies to be sampled (reduced) :type number_movies: integer """ items = pd.read_csv(original_filename).sample(n=number_movies) items.to_csv(sampled_movies_filename, index=False) # write_sample_movies('movies.csv','movies_sampled.csv', 10000) def write_ratings_with_sampled_movies(original_ratings_filename, sampled_movies_filename, new_ratings_filename, qty_users): """ Method that, from csv file of the original movielens user ratings, will write user ratings made only in sampled movies :param original_ratings_filename: csv file path where all user ratings are is located (this file must be in csv format and must contain the following columns: userId, movieId, rating) :type original_ratings_filename: strin :param sampled_movies_filename: path where the csv file with sampled movies is located (this file must be in csv format and must contain the following columns: movieId, title, genres) :type sampled_movies_filename: string :param new_ratings_filename: path where the user ratings in sampled movies csv file will be located (this file must be in csv format) :type new_ratings_filename: string :param qty_users: quantity of users id's who rated movies :type qty_users: integer (between 1 and 200000) """ with open(new_ratings_filename, 'w', newline='', encoding='utf-8') as new_fp: USERID, MOVIEID, RATING = 0, 1, 2 movies_dict = get_movies_dict(sampled_movies_filename) items = read_data(original_ratings_filename, qty_users) write = csv.writer(new_fp) write.writerow(["userId", "movieTitle", "rating"]) for line in items: if line[MOVIEID] in movies_dict.keys(): movieTitle = movies_dict[line[MOVIEID]]["Title"] new_line = [line[USERID], movieTitle, line[RATING]] write.writerow(new_line) new_fp.close() # write_ratings_with_sampled_movies('new_ratings.csv', 'movies_sampled.csv', 'ratings_sampled.csv') def write_limited_users_ratings(filename, qty_users): """ Method that will write to a new csv file a certain number of user ratings (userRatings5k, 10k,...) :param filename: path where the new csv file with a certain quantity of users who rated movies will be located (this file must be in csv format) :type filename: string :param qty_users: quantity of users id's who rated movies :type qty_users: integer (between 1 and 200000) """ with open(filename, 'w', newline='', encoding='utf-8') as new_fp: USERID, MOVIEID, RATING = 0, 1, 2 movies_dict = get_movies_dict('movies.csv') items = read_data('../new_ratings.csv', qty_users) write = csv.writer(new_fp) write.writerow(["userId", "movieTitle", "rating"]) for line in items: movieTitle = movies_dict[line[MOVIEID]]["Title"] new_line = [line[USERID], movieTitle, line[RATING]] write.writerow(new_line) new_fp.close() # 2º Descomentar esta linha # write_data('../datasets/userRatings5k.csv') def write_modified_movies(user_ratings_filename, sampled_movies_filename, new_user_rating_genre_filename, qty_users): """ Method that, from the csv file where all user ratings are, will write a certain quantity of users who made only ratings in sampled movies :param user_ratings_filename: csv file path where all user ratings are is located (this file must be in csv format and must contain the following columns: userId, movieId, rating) :type user_ratings_filename: string :param sampled_movies_filename: path where the csv file with sampled movies is located (this file must be in csv format and must contain the following columns: movieId, title, genres) :type sampled_movies_filename: string :param new_user_rating_genre_filename: path where the user ratings with movies genre csv file will be located (this file must be in csv format and must contain the following columns: userId, movieTitle, genre,rating) :type new_user_rating_genre_filename: string :param qty_users: quantity of users id's who rated movies :type qty_users: integer (between 1 and 200000) """ with open(new_user_rating_genre_filename, 'w', newline='', encoding='utf-8') as new_fp: USERID, MOVIEID, RATING = 0, 1, 2 movies_dict = get_movies_dict(sampled_movies_filename) items = read_data(user_ratings_filename, qty_users) write = csv.writer(new_fp) write.writerow(["userId", "movieTitle", "genre", "rating"]) for line in items: if line[MOVIEID] in movies_dict.keys(): movie_title = movies_dict[line[MOVIEID]]["Title"] for i in range(len(movies_dict[line[MOVIEID]]["Genres"])): genre = movies_dict[line[MOVIEID]]["Genres"][i] new_line = [line[USERID], movie_title, genre, line[RATING]] write.writerow(new_line) new_fp.close() # write_modified_movies('../new_ratings.csv', '../movies_sampled.csv', 'userRatingsGenre.csv') def get_movies_genres_list(filename): """ Method that converts a csv file with the movies information (movieId, title, genres) into a list of strings :param filename: path where the csv file is located (this file must be in csv format and must contain the following columns: movieId, title, genres) :type filename: string :return: list of strings that contains all the movies genres """ with open(filename, encoding='utf-8') as fp: reader = csv.reader(fp) next(reader, None) # skip the headers genres_list = [] MOVIEID, TITLE, GENRES = 0, 1, 2 for line in reader: genres = line[GENRES].split('|') for genre in genres: if genre not in genres_list: genres_list.append(genre) return genres_list # print(get_movies_genres_list('datasets/movies.csv')) def write_movie_genres_files(movies_filename, genres_filename): """ Method that, from the csv file with the movies information (movieId, title, genres), will write to a new csv file (genreId, genre) :param movies_filename: path where the csv file is located (this file must be in csv format and must contain the following columns: movieId, title, genres) :type movies_filename string :param genres_filename: path where the new file will be located (this file must be in csv format) :type genres_filename: string """ with open(genres_filename, 'w', newline='', encoding='utf-8') as new_fp: items = get_movies_genres_list(movies_filename) write = csv.writer(new_fp) write.writerow(["genreId", "genre"]) i = 1 for item in items: write.writerow([i, item]) i += 1 new_fp.close() # write_movie_genres_files('datasets/movies.csv', 'datasets/movies_genres.csv') def get_users_id_list(filename): """ Method that converts a csv file with the movies information (userId, movieTitle, rating) into a list of strings :param filename: path where the csv file is located (this file must be in csv format and must contain the following columns: userId, movieTitle, rating) :type filename: string :return: list of strings that contains all the users id's """ with open(filename, encoding='utf-8') as fp: reader = csv.reader(fp) next(reader, None) # skip the headers users_list = [] USERID, MOVIETITLE, RATING = 0, 1, 2 for line in reader: if line[USERID] not in users_list: users_list.append(line[USERID]) return users_list # print(get_users_id_list('datasets/userRatings5k.csv')) def get_rules_movies(filename, has_id): with open(filename, encoding='utf-8') as fp: reader = csv.reader(fp) next(reader, None) # skip the headers ant_movies_list = [] cons_movies_list = [] if has_id: ID, ANTECEDENTS, CONSEQUENTS, ANTECEDENTSUPPORT, CONSEQUENTSUPPORT, SUPPORT, CONFIDENCE, KULC, IBRATIO = 0, 1, 2, 3, 4, 5, 6, 7, 8 else: ANTECEDENTS, CONSEQUENTS, ANTECEDENTSUPPORT, CONSEQUENTSUPPORT, SUPPORT, CONFIDENCE, KULC, IBRATIO = 0, 1, 2, 3, 4, 5, 6, 7 for line in reader: antecedents = ast.literal_eval(line[ANTECEDENTS]) consequents = ast.literal_eval(line[CONSEQUENTS]) for antecedent in antecedents: if antecedent not in ant_movies_list: ant_movies_list.append(antecedent) for consequent in consequents: if consequent not in cons_movies_list and consequent not in ant_movies_list: cons_movies_list.append(consequent) print("Antecedents no: " + str(len(ant_movies_list))) print(ant_movies_list) print("Consequents no: " + str(len(cons_movies_list))) print(cons_movies_list) print() # get_rules_movies('rulesCsv/rules5kUsersConfImp.csv', True) # get_rules_movies('rulesCsv/rules5kUsersConfExp.csv', False)
true
7b31b4c146006ab7f820d0af460a3ac44a45faaa
Python
Merrouni/Exercism
/python/bank-account/bank_account.py
UTF-8
1,375
3.453125
3
[]
no_license
STATUS_CLOSED = 'closed' STATUS_OPEN = 'open' class BankAccount(object): def __init__(self): self.status = STATUS_CLOSED self.transactions = [] pass def get_balance(self): if self.status == STATUS_CLOSED: raise ValueError("The account is closed !!!") return sum(self.transactions) def open(self): if self.status == STATUS_OPEN: raise ValueError("Account already open !!!") self.status = STATUS_OPEN self.transactions.append(0) def deposit(self, amount): if self.status == STATUS_CLOSED: raise ValueError("The account is closed !!!") if amount < 0: raise ValueError("Deposit amount cannot be negative !!!") self.transactions.append(amount) def withdraw(self, amount): if self.status == STATUS_CLOSED: raise ValueError("The account is closed !!!") if amount < 0: raise ValueError("Withdraw amount cannot be negative !!!") if sum(self.transactions) - amount < 0: raise ValueError("You can't withdraw more than diposited !!!") self.transactions.append(-amount) def close(self): if self.status == STATUS_CLOSED: raise ValueError("Account already closed !!!") self.status = STATUS_CLOSED self.transactions = []
true
b20980cbe53466ee0cedae71c9aaab54c1aac0fc
Python
josiane-sarda/CursoPythonHbsisProway
/Aulas Marcello/exercicio 49 - questao a mais.py
UTF-8
494
3.90625
4
[]
no_license
print('Média geral dos alunos') print('Qual a quantidade de alunos?') qtd_alunos = int(input()) print('Quantas notas por aluno?') qtd_notas = int(input()) soma_notas = 0 for aluno in range(0, qtd_alunos): # aluno [0, 1, 2] for nota in range(0, qtd_notas): # nota [0, 1] print('Aluno {} => Nota {}'.format(aluno, nota)) soma_notas = soma_notas + float(input()) media = soma_notas / (qtd_alunos * qtd_notas) print('Média feral = {}'.format(media))
true
5c92e308d8233bdcb5d8fa1863572967433535dd
Python
hodurie/Algorithm
/SWExpertAcademy/src/D2/SW_1984.py
UTF-8
177
3.484375
3
[]
no_license
T = int(input()) for t in range(T): lst = [int(n) for n in input().split()] lst.remove(max(lst)) lst.remove(min(lst)) print(f'#{t+1} {round(sum(lst)/len(lst))}')
true
862898176d7e6bf5a835141fa2b1315e7fcdf2ac
Python
sev-94/introPy
/39_decorators.py
UTF-8
450
4.21875
4
[]
no_license
#Decorators are used when a function is used as an argument for another function def my_decorator(func): def wrap_func(*args, **kwargs): print('*********') func(*args, **kwargs) print('*********') return wrap_func #This is a 'decorator' #Decorators are declared with a '@' in front of them #Decorators add extra functionality to existing functions @my_decorator def hello(greeting): print(greeting) hello('hiii')
true
78ac8919e8c7f0f5191b553d00c04a760985bfbc
Python
RNabel/InterviewPreparation
/Python/CTCI/ShortestReachInGraphBellmanFord.py
UTF-8
1,807
3.609375
4
[]
no_license
# Contains Bellman-Ford algorithm. import sys class Graph(object): def __init__(self, size): self.vertexes = [0] * size self.edges = [] self.size = size def find_all_distances(self, start_node_index): def add_if_not_in_set(q, s, el): if el not in s: q.append(el) s.add(el) distance = [sys.maxint] * self.size predecessor = [-1] * self.size distance[start_node_index] = 0 candidates = [start_node_index] candidate_set = {start_node_index} # Relax edges repeatedly. while len(candidates): u = candidates.pop(0) candidate_set.remove(u) for edge in self.edges: src, dst, weight = edge if not (src == u or dst == u): continue # Two checks as *undirected* graph, otherwise only one check required. if distance[src] + weight < distance[dst]: distance[dst] = distance[src] + weight predecessor[dst] = src add_if_not_in_set(candidates, candidate_set, dst) # TODO: detect negative cycles. del distance[start_node_index] # Print distances. output = " ".join([str(x) if x < sys.maxint else str(-1) for x in distance]) print output return distance def connect(self, source, dest): self.edges.append((source, dest, 6)) self.edges.append((dest, source, 6)) t = input() for i in range(t): n, m = [int(x) for x in raw_input().split()] graph = Graph(n) for i in xrange(m): x, y = [int(x) for x in raw_input().split()] graph.connect(x - 1, y - 1) s = input() graph.find_all_distances(s - 1)
true
1edf3c41f422d4e85af439e7cc44192ff623c733
Python
isi-nlp/unitok
/scripts/ffpredict2bio.py
UTF-8
2,306
2.515625
3
[]
no_license
#!/usr/bin/env python import argparse import sys import codecs if sys.version_info[0] == 2: from itertools import izip from collections import defaultdict as dd import re import os.path import gzip import tempfile import shutil import atexit scriptdir = os.path.dirname(os.path.abspath(__file__)) reader = codecs.getreader('utf8') writer = codecs.getwriter('utf8') def prepfile(fh, code): ret = gzip.open(fh.name, code) if fh.name.endswith(".gz") else fh if sys.version_info[0] == 2: if code.startswith('r'): ret = reader(fh) elif code.startswith('w'): ret = writer(fh) else: sys.stderr.write("I didn't understand code "+code+"\n") sys.exit(1) return ret def main(): parser = argparse.ArgumentParser(description="given integerized one output per line, original input, and dictionary, produce bio file for further processing", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--nnfile", "-n", nargs='?', type=argparse.FileType('r'), default=sys.stdin, help="nn file (integerized one output per line)") parser.add_argument("--origfile", "-g", nargs='?', type=argparse.FileType('r'), default=sys.stdin, help="original file (same chars as nn file has lines but multi per line") parser.add_argument("--vocabfile", "-v", nargs='?', type=argparse.FileType('r'), default=sys.stdin, help="vocab file") parser.add_argument("--outfile", "-o", nargs='?', type=argparse.FileType('w'), default=sys.stdout, help="output biofile") workdir = tempfile.mkdtemp(prefix=os.path.basename(__file__), dir=os.getenv('TMPDIR', '/tmp')) def cleanwork(): shutil.rmtree(workdir, ignore_errors=True) atexit.register(cleanwork) try: args = parser.parse_args() except IOError as msg: parser.error(str(msg)) nnfile = prepfile(args.nnfile, 'r') origfile = prepfile(args.origfile, 'r') vocabfile = prepfile(args.vocabfile, 'r') outfile = prepfile(args.outfile, 'w') vocab = [] for line in vocabfile: vocab.append(line.strip()) nnres = [] for line in nnfile: nnres.append(vocab[int(line.strip())]) for line in origfile: linelen = len(line.strip()) outfile.write(''.join(nnres[:linelen])+"\n") nnres = nnres[linelen:] if __name__ == '__main__': main()
true
d1b16e3971e86725bfd6469e71fbcc697bd98e83
Python
VinayagamD/PythonTrainingBatch1
/netwroking/server.py
UTF-8
997
3.609375
4
[]
no_license
# first of all import the socket library import socket # next create a socket object s = socket.socket() print("Socket successfully created") # reserve a port on your computer in our # case it is 12345 but it can be anything port = 12345 # Next bind to the port # we have not typed any ip in the ip field # instead we have inputted an empty string # this makes the server listen to requests # coming from other computers on the network s.bind(('127.0.0.1', port)) print("socket binded to %s" % port) # put the socket into listening mode s.listen(5) print("socket is listening") # a forever loop until we interrupt it or # an error occurs # Establish connection with client. c, addr = s.accept() print('Got connection from', addr) # send a thank you message to the client. c.send(b'Thank you for connecting') data = '' while data != 'exit': data = input('Enter your message to send or type exit to quit\n') c.send(bytes(data, encoding='utf8')) if data == 'exit': s.close()
true
bee76d0a7d3cb6ac57f6c742e74582c916acaeb4
Python
biotite-dev/biotite
/doc/examples/scripts/structure/leaflet.py
UTF-8
4,082
3.015625
3
[ "BSD-3-Clause", "MIT" ]
permissive
""" Identification of lipid bilayer leaflets ======================================== This script implements the *LeafletFinder* algorithm :footcite:`Michaud-Agrawal2011` used by *MDAnalysis*. The algorithm detects which lipid molecules belong to the same membrane leaflet, i.e. the same side of a lipid bilayer, irrespective of the shape of the bilayer. At first the algorithm creates an adjacency matrix of all lipid head groups, where the cutoff distance is smaller than the minimum distance between a head group of one leaflet to a head group of another leaflet. A graph is created from the matrix. Each leaflet is a connected subgraph. .. footbibliography:: """ # Code source: Patrick Kunzmann # License: BSD 3 clause from tempfile import NamedTemporaryFile import warnings import numpy as np import networkx as nx import biotite.structure as struc import biotite.structure.io as strucio # The bilayer structure file can be downloaded from # http://www.charmm-gui.org/archive/pure_bilayer/dppc.tar.gz PDB_FILE_PATH = "../../download/dppc_n128.pdb" def find_leaflets(structure, head_atom_mask, cutoff_distance=15.0, periodic=False): """ Identify which lipids molecules belong to the same lipid bilayer leaflet. Parameters ---------- structure : AtomArray, shape=(n,) The structure containing the membrane. May also include other molecules, e.g. water or an embedded protein. head_atom_mask : ndarray, dtype=bool, shape=(n,) A boolean mask that selects atoms from `structure` that represent lipid head groups. cutoff_distance : float, optional When the distance of two head groups is larger than this value, they are not (directly) connected in the same leaflet. periodic : bool, optional, If true, periodic boundary conditions are considered. This requires that `structure` has an associated `box`. Returns ------- leaflets : ndarray, dtype=bool, shape=(m,n) Multiple boolean masks, one for each identified leaflet. Each masks indicates which atoms of the input `structure` are in the leaflet. """ cell_list = struc.CellList( structure, cell_size=cutoff_distance, selection=head_atom_mask, periodic=periodic ) adjacency_matrix = cell_list.create_adjacency_matrix(cutoff_distance) graph = nx.Graph(adjacency_matrix) head_leaflets = [sorted(c) for c in nx.connected_components(graph) # A leaflet cannot consist of a single lipid # This also removes all entries # for atoms not in 'head_atom_mask' if len(c) > 1] # 'leaflets' contains indices to head atoms # Broadcast each head atom index to all atoms in its corresponding # residue leaflet_masks = np.empty( (len(head_leaflets), structure.array_length()), dtype=bool ) for i, head_leaflet in enumerate(head_leaflets): leaflet_masks[i] = struc.get_residue_masks(structure, head_leaflet) \ .any(axis=0) return leaflet_masks # Suppress warning that elements were guessed, # as this PDB file omits the 'chemical element' column with warnings.catch_warnings(): warnings.simplefilter("ignore") structure = strucio.load_structure(PDB_FILE_PATH) # We cannot go over periodic boundaries in this case, # because the input PDB does not define a box -> periodic=False # However, as we have a planer lipid bilayer, # periodicity should not matter leaflets = find_leaflets( structure, head_atom_mask=(structure.res_name == "DPP") & (structure.atom_name == "P") ) # Bilayer -> Expect two leaflets assert len(leaflets) == 2 # Mark leaflets using different chain IDs for chain_id, leaflet_mask in zip(("A", "B"), leaflets): structure.chain_id[leaflet_mask] = chain_id # Save marked lipids to structure file temp = NamedTemporaryFile(suffix=".pdb") strucio.save_structure(temp.name, structure) # Visualization with PyMOL... temp.close()
true
2531610341105a54c4e38b01f08bee4c6d017227
Python
ryutaro-kodama/kifu_app
/add_kifu/lib/conversion.py
UTF-8
2,131
3.1875
3
[]
no_license
class NumberConvert(): kansuji_list = ['0', '一', '二', '三', '四', '五', '六', '七', '八', '九'] zenkaku_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] @staticmethod def number2kansuji(num): return NumberConvert.kansuji_list[num] @staticmethod def number2zenkaku(num): return NumberConvert.zenkaku_list[num] @staticmethod def kansuji2number(kansuji): return NumberConvert.kansuji_list.index(kansuji) @staticmethod def zenkaku2number(zenkaku): return NumberConvert.zenkaku_list.index(zenkaku) class PieceConvert(): eigo_koma_list = {'Fu':'歩', 'To':'と', 'Kyo':'香', 'NariKyo':'成香', 'Kei':'桂', 'NariKei':'成桂', 'Gin':'銀', 'NariGin':'成銀', 'Kin':'金', 'Hisya':'飛', 'Ryu':'竜', 'Kaku':'角', 'Uma':'馬', 'Ou':'王'} nari_list = {'Fu':'To', 'Kyo':'NariKyo', 'Kei':'NariKei', 'Gin':'NariGin', 'Hisya':'Ryu', 'Kaku':'Uma'} my_formalize_list = {'杏': '成香','圭': '成桂', '全': '成銀', '龍': '竜', '玉': '王'} @staticmethod def eigo2koma(eigo): return PieceConvert.eigo_koma_list[eigo] @staticmethod def koma2eigo(koma): key = [k for k, v in PieceConvert.eigo_koma_list.items() if v == koma][0] return key @staticmethod def myFormalize(koma): if koma in PieceConvert.my_formalize_list: return PieceConvert.my_formalize_list[koma] else: return koma @staticmethod def promote(koma): if koma in PieceConvert.nari_list: return PieceConvert.nari_list[koma], 1 else: return koma, 0 @staticmethod def demote(koma): if koma in PieceConvert.nari_list.values(): key = [k for k, v in PieceConvert.nari_list.items() if v == koma][0] return key, 1 else: return koma, 0
true
bcd0155816eae8339c4e9967fba7242d3054121c
Python
kongjunli/Module-GRU-
/LSTM.py
UTF-8
4,415
2.53125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Thu Nov 02 11:08:57 2017 @author: kjl """ import gensim import numpy as np import pandas as pd import jieba import mysql.connector from gensim.models import word2vec import logging from sklearn.cross_validation import train_test_split from gensim.models.word2vec import Word2Vec from sklearn.linear_model import LinearRegression from keras import metrics import matplotlib.pyplot as plt # custom R2-score metrics for keras backend from keras import backend as K from keras.models import Sequential from keras.layers import Dense, Activation, Dropout, Embedding from keras.layers import LSTM from keras import regularizers from keras.preprocessing import sequence import datetime from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_absolute_error from sklearn.metrics import r2_score from sklearn import preprocessing starttime = datetime.datetime.now() #随机种子 seed = 6868 class GetData(): def Data(self): db=mysql.connector.connect(host='127.0.0.1',user='root',password='lkmn159357',database='spiderdb',charset='utf8') cursor=db.cursor() Content=[] sql='select day,authorscore,categoryscore,titlescore,summaryscore,titlepolarity,logscan from spiderdb.paper' cursor.execute(sql) data=cursor.fetchall() return data obj=GetData() datas=obj.Data() x=[] y=[] logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) for i in range(len(datas)): try: x.append(datas[i][0:6]) y.append(datas[i][6]) except: continue for train_ratio in [0.9,0.6,0.3]: RMSE = [] #均方根误差 MSE = [] MAE = [] R2 = [] print "\n train_ratio:",train_ratio for i in range(5): print "-----------------The",i+1,"Experiment-------------" x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=train_ratio,random_state=seed) #Normalization for train and test data set. http://scikit-learn.org/stable/modules/preprocessing.html #feature_range=(0, 1) print "min(y)",min(y) print "max(y)",max(y) print "original y train",y_train[0:10] min_max_scaler = preprocessing.MinMaxScaler(feature_range=(10, 15)) #1-3 10-12 y_train=np.array(y_train).reshape(-1,1) y_train = min_max_scaler.fit_transform(y_train) y_test=np.array(y_test).reshape(-1,1) y_test = min_max_scaler.transform((y_test)) #print "\n y train",y_train[0:10] #y_train = preprocessing.normalize(y_train, norm='l2').T #y_test = preprocessing.normalize(y_test, norm='l2').T print "x_train shape",x_train[0] # 建立模型 model = Sequential() model.add(Embedding(10000,128)) model.add(Dropout(0.25)) model.add(LSTM(128,dropout_U=0.25)) #,W_regularizer=regularizers.l2(10e-3) model.add(Dense(1)) model.add(Activation('relu')) model.compile(loss='mse',optimizer='RMSprop',metrics=['mean_absolute_error','mse']) batch_size = 2 #128,32,6,2 model.fit(x_train, y_train, batch_size=batch_size, nb_epoch=3,validation_data=(x_test,y_test)) scores = model.evaluate(x_test, y_test, batch_size=batch_size) print "Model Summary",model.summary() print "MAE:%s: %.5f" % (model.metrics_names[1], scores[1]) #mae print "MSE:%s: %.5f" % (model.metrics_names[2], scores[2]) #mse probabilities = model.predict(x_test) print "Probabilities:",probabilities print "y_test",y_test print "pro shape",len(probabilities) print "y_test shape",len(y_test) print "mean absolure error:",(mean_absolute_error(y_test,probabilities)) print "mean_squared_error:",(mean_squared_error(y_test,probabilities)) print "RMSE:%.5f"%(np.sqrt(scores[2])) #rmse print "r2_score:",(r2_score(y_test,probabilities)) RMSE.append(np.sqrt(scores[2])) MSE.append(mean_squared_error(y_test,probabilities)) MAE.append(mean_absolute_error(y_test,probabilities)) R2.append(r2_score(y_test,probabilities)) print "Average RMSE:",np.mean(RMSE) print "Average MSE:",np.mean(MSE) print "Average MAE:",np.mean(MAE) print "Average R2:",np.mean(R2) endtime = datetime.datetime.now() print (endtime - starttime).seconds
true
d74719d167ef15bf36b920955933c7b174096ea4
Python
tdstyrone/LeetCode-Solutions
/PythonSolutions/Medium/Sort-Characters-By-Frequency/sort_characters_frequencey_solution.py
UTF-8
180
2.953125
3
[]
no_license
class Solution: def frequencySort(self, s: str) -> str: from collections import Counter return "".join([char * freq for char, freq in Counter(s).most_common()])
true
13e119ac74f5831d411aeab9be68185e5e836f09
Python
imao03/Chapter-01
/su_cai_demo/test_select.py
UTF-8
685
2.625
3
[]
no_license
#!/usr/bin/env python3.7.9 # -*- coding:utf-8 -*- # @Time : 2021/10/9 14:11 # @Author : Kitty # @File : test_select.py # @SoftWare: PyCharm from selenium import webdriver from time import sleep driver = webdriver.Chrome() driver.maximize_window() driver.implicitly_wait(30) # 注册A.html url = "file:///Users/kitty/PycharmProjects/Chapter01/su_cai/%E6%B3%A8%E5%86%8CA.html" driver.get(url) """ 默认为 北京 暂停 定为上海 暂停 定为广州 """ sleep(2) driver.find_element_by_css_selector("#selectA > option:nth-child(2)").click() sleep(2) driver.find_element_by_css_selector("#selectA > option:nth-child(3)").click() sleep(2) driver.quit()
true
db73d76340c422ef718a00124287f5fd1006272a
Python
tatHi/common
/common/dataset/wordSegmentation.py
UTF-8
865
2.703125
3
[]
no_license
''' json for input: train: [{ text: abcdefgh label: [3,2,3] //lenth label: [0,0,1,0,1,0,0,1] //01 }] ''' from common.dataset import dataset class Dataset4WordSegmentation(dataset.Dataset): def __init__(self, path, labelType='length', useBEOS=False, vocab=None): if labelType not in ['length','01']: print('labelType should be length or 01') exit() super().__init__(path, useBEOS=useBEOS, vocab=vocab) # check for ty in self.data: for line in self.data[ty]: if len(line['text']) != sum(line['label']): print(line['text']) print(line['label']) exit() if labelType=='length': self.maxLength = max([l for line in self.data['train'] for l in line['label']])
true
495bf167d2e4e158d8adfbd1cbb33bb89b0969cb
Python
ali8261/Election_Analysis
/python_practice.py
UTF-8
81
3.34375
3
[]
no_license
counties = input ( " name of county ?") print(" name of county is " + counties )
true
fb300c3a76d8529b44def4bffe3ea15a6bdf2d4a
Python
cristianvalenz/Python
/Colecciones/Pilas.py
UTF-8
187
4.03125
4
[]
no_license
pila = [1,2,3] #Agregar elementos por el final pila.append(4) pila.append(5) print(pila) #Sacando elementos por el final n = pila.pop() print(f"Sacando el elemento : {n}") print(pila)
true
dd91c6bff83a7873b885c43d3fc118413f11d422
Python
ignaziocapuano/workbook_ex
/cap5/ex_126.py
UTF-8
776
3.390625
3
[]
no_license
#Dealing Hands of Cards from ex_125 import createDeck, shuffleDeck def deal(num_giocatori, carte_mano, mazzo): mani=[] top_mazzo=len(mazzo) for i in range(num_giocatori): mani.append([""]*carte_mano) #Assembla mani for j in range(carte_mano): for i in range(num_giocatori): mani[i][j]=mazzo[len(mazzo)-1] mazzo.pop() for i in range(num_giocatori): print(mani[i]) print(mazzo) print(len(mazzo)) def main(): num_gioc=int(input("Inserisci numero giocatori:")) num_carte=int(input("Inserisci numero carte per mano:")) mazzo=createDeck() mazzo=shuffleDeck(mazzo) deal(num_gioc,num_carte,mazzo) if __name__ == '__main__': main() """ Manca la validazione dell'input. """
true
9ee7e3bceec54223599c4f8a49d3e734cf2f2d32
Python
anupamkaul/deeplearning
/gans/exercises/6.ae_1.py
UTF-8
523
2.546875
3
[]
no_license
''' Exploring variational auto-encoders (https://arxiv.org/pdf/1312.6114.pdf) Let's first build a standard autoencoder and then a variational ae. VAEs are fundamental to building GANs. I will also highlight / pick apart both AEs and VAEs to understand how to build & manipulate autoencoder models an in particular VAEs from scratch to generate images (GANs) from my own training set. ''' ''' The first example follows from the N.Coder and D.Coder actors described in pages 61 - 66 in Generative Deep Learning '''
true
e202a56a3ff7190f0db88bfbc46cdf8795dc8273
Python
1Ricklu/Topology_Optimization
/comp_plot.py
UTF-8
1,263
3.03125
3
[]
no_license
import matplotlib.pyplot as plt class compliance(): ''' This module is to plot the change of compliance during optimization based on the Matlab calculation ''' def extract(module_name): for file_id in range(1,6): file_name = "m"+str(module_name)+"_"+str(file_id)+".txt" # load files results = [] with open(file_name) as inputfile: for line in inputfile: results.append(line.strip().split()) # extract the num of iteration and val of compliance results = [el for el in results if el] iter = [] comp = [] for each_row in results: if ("It.:" and "Obj.:") in each_row: iter_ix = each_row.index("It.:")+1 iter.append(each_row[iter_ix]) comp_ix = each_row.index("Obj.:")+1 comp.append(each_row[comp_ix]) labels = ["2:1", "1.5:1", "1:1", "1:1.5", "1:2"] # visualize plt.plot(iter, comp, label=labels[file_id-1]) plt.legend() plt.xlabel("Iteration") plt.ylabel("Compliance") plt.show()
true
81d02426e2f4d268458d1b351dff0986c4f3be1b
Python
jebrunnoe/Project-Euler
/problem6.py
UTF-8
847
4.25
4
[]
no_license
#PROBLEM: # 6 # #NAME: # "Sum Square Difference" # #PROMPT: # The sum of the squares of the first ten natural numbers is, # 1^2 + 2^2 + ... + 10^2 = 385. The square of the sum of the first # ten natural numbers is, (1 + 2 + ... + 10)^2 = 552 = 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. # #LINK: # https://projecteuler.net/problem=6 sum_of_squares = 0 sum = 0 # Iterate through the first 100 natural numbers for n in range(1, 101): sum_of_squares += n * n # Accumulate the square of each number sum += n # Keep a running sum to be squared afterward print sum * sum - sum_of_squares # Print the difference
true
1e59e5f65f2f57d7533c4b8120ec2fad676ccf4f
Python
tronje/mms
/Uebung_06/06.py
UTF-8
2,301
3.34375
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Aufgabe 2. a) def fft2(s): X = np.fft.fft(s,axis=0) Result = np.fft.fft(X,axis=1) return Result def Aufgabe2a(): x = np.arange(-np.pi, np.pi,0.1) y = np.arange(-np.pi, np.pi,0.1) X,Y = np.meshgrid(x,y) R = np.sqrt(X**2+Y**2) s = np.sin(R) fig = plt.figure() ax = fig.add_subplot(111,projection="3d") surf = ax.plot_surface(X,Y, s) plt.show() S1 = fft2(s) fig = plt.figure() ax = fig.add_subplot(221,projection="3d") ax.set_title("our fft2 magnitude") surf = ax.plot_surface(X,Y, np.abs(S1)) ax = fig.add_subplot(222,projection="3d") ax.set_title("our fft2 phase") surf = ax.plot_surface(X,Y, np.angle(S1)) S2 = np.fft.fft2(s) ax = fig.add_subplot(223,projection="3d") ax.set_title("numpy fft2 magnitude") surf = ax.plot_surface(X,Y, np.abs(S2)) ax = fig.add_subplot(224,projection="3d") ax.set_title("numpy fft2 phase") surf = ax.plot_surface(X,Y, np.angle(S2)) plt.show() error = np.sum(S1-S2) print("Total difference: " + str(error)) # Aufgabe 2. b) def CenteredAmplitudeAndPhase(S): Phase = np.angle(S) Amplitude = np.abs(S) return Amplitude, Phase def Aufgabe2c(): vert_image = vertical_edge_image() diag_image = diagonal_edge_image() plt.subplot(321) plt.imshow(vert_image, cmap='gray') plt.title('Vertical line') plt.subplot(322) plt.imshow(diag_image, cmap='gray') plt.title('Diagonal line') A, P = CenteredAmplitudeAndPhase(fft2(vert_image)) plt.subplot(323) plt.imshow(A) plt.title("Amplitude spectrum") plt.subplot(325) plt.imshow(P) plt.title("Phase spectrum") A, P = CenteredAmplitudeAndPhase(fft2(diag_image)) plt.subplot(324) plt.imshow(A) plt.title("Amplitude spectrum") plt.subplot(326) plt.imshow(P) plt.title("Phase spectrum") plt.show() def vertical_edge_image(): s = np.zeros((20, 20)) for i in range(20): s[i][10] = 255 return s def diagonal_edge_image(): s = np.zeros((20,20)) for i in range(20): s[i][i] = 255 return s if __name__ == "__main__": Aufgabe2a() Aufgabe2c()
true
ce8c8be2d4e7a8d40551552e439d4c5a732330b3
Python
Praveenk8051/python-scripts-projects
/scripts/rename_files.py
UTF-8
1,739
2.9375
3
[]
no_license
import ntpath import os import argparse from tensorflow.python.platform import gfile def create_file_list(path): """Create list of file paths Args: path: folder containing image files Returns: list: list of image file paths """ file_list = [] extensions = ['jpg', 'jpeg', 'JPG', 'JPEG', 'png'] for extension in extensions: file_glob = os.path.join(path, '*.' + extension) file_list.extend(gfile.Glob(file_glob)) return file_list def rename_files(file_list, save_path, file_name): """rename the files Args: file_list: list of image file paths save_path: path where renamed files to be saved file_name: the names of the file Returns: None """ count = 0 for i in range(len(file_list)): print(file_list[i]) _, tail = ntpath.split(file_list[i]) _, b = tail.split(".") trackName = file_name+str(count) os.rename(file_list[i], os.path.join(save_path, trackName + "." + b)) count = count + 1 if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--pick_files_path', type=str, default='', help='Path where files to be renamed reside' ) parser.add_argument( '--save_files_path', type=str, default='', help='Path where files are to be saved' ) parser.add_argument( '--name_of_the_file', type=str, default='', help='custom name to be given' ) args = parser.parse_args() file_list = create_file_list(args.pick_files_path) print(file_list) rename_files(file_list, args.save_files_path, args.name_of_the_file)
true
8537bd596b7722966c4b0c0f106fb44470953bb0
Python
s-christian/Schoolwork
/Introduction to Cryptography/RSA.py
UTF-8
1,237
3.640625
4
[]
no_license
def modular_exponentiation(base, exponent, n): # base^exponent (mod n) ans = 1 while exponent > 0: if exponent % 2 == 0: exponent /= 2 base = (base * base) % n else: exponent -= 1 ans = (ans * base) % n return ans def encrypt(m, e, n): return modular_exponentiation(m, e, n) def decrypt(c, d, n): return modular_exponentiation(c, d, n) def extended_euclid(a, b): r = [] q = [] x = [0, 1] y = [1, 0] while(b > 0): q.append(a // b) r.append(a % b) x.append(x[-2] - q[-1] * x[-1]) y.append(y[-2] - q[-1] * y[-1]) a, b = b, a % b return y[-2] p = 5336500541 q = 11037273967 n = p * q e = 65537 d = extended_euclid(e, (p - 1) * (q - 1)) print("e * d = 1 (mod (p-1)(q-1))") print("{0} * {1} = {2} (mod (p-1)(q-1))".format(e, d, (e * d) % ((p-1) * (q-1)))) message = 12122019 ciphertext = 19251455775916764152 encrypted = encrypt(message, e, n) decrypted = decrypt(encrypted, d, n) plaintext = decrypt(ciphertext, d, n) print("n =", n) print("Encrypted message: ", encrypted) print("Decrypted original message:", decrypted) print("Decrypted ciphertext: ", plaintext)
true
481b35b7e88d0be31ecba848718db9b22473000d
Python
saikumar3011/appointment
/hospitalapp/views.py
UTF-8
2,863
2.59375
3
[]
no_license
from django.shortcuts import render from django.contrib.auth import authenticate,login from .form import LoginForm from django.http import HttpResponse from rest_framework import viewsets from .models import * from .serializers import * from django.contrib.auth.models import User from datetime import datetime # Create your views here. def login_user(request): """ This function is for login page using default Django login views""" if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): retrived_data = form.cleaned_data user = authenticate(request, username = retrived_data['username'], password = retrived_data['password']) if user is not None : login(request,user) return HttpResponse('Authentication was successfull') else: return HttpResponse('Authentication failed, Please try again') else: form = LoginForm() return render(request,'login.html',{'form': form}) class PatientViewSet(viewsets.ModelViewSet): """queryset is used to get list of patient details serializer_class used to translate patient details from django to other formats like Json""" queryset = Patient.objects.all() serializer_class = PatientSerializer class DoctorViewSet(viewsets.ModelViewSet): """queryset is used to get list of doctor details, serializer_class used to translate doctor details from django to other formats like Json""" queryset = Doctor.objects.all() serializer_class = DoctorSerializer class AppointmentViewSet(viewsets.ModelViewSet): """queryset is used to get list of appointment details, serializer_class used to translate appointment details from django to other formats like Json""" queryset = Appointment.objects.all() serializer_class = AppointmentSerializer def perform_create(self, serializer): """doctor variable is used to get list of doctor details from models, patient variable is used to get list of patient details from models, today_date variable is used to get date of appointment from models, appointment_filter variable is used to patient canot take second appointmnet with same doctor on any particular day """ doctor = self.request.data["doctor"] patient = self.request.data["patient"] today_date = self.request.data["date_appointment"] appointment_filter = Appointment.objects.filter(doctor=doctor,patient=patient,date_appointment=today_date) if len(appointment_filter) > 0: print("Appointment already booked on ",today_date) else: print("Appointment booked successfully",today_date) serializer.save()
true
ddc30cf9b3063be7b81df6bfb5827c0ae18a2653
Python
Timothy-Kornish/MachineLearningPython
/machineLearning/TensorFlow_DeepLearning/bank_data_project.py
UTF-8
3,694
2.96875
3
[]
no_license
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np import tensorflow as tf import tensorflow.contrib.learn as learn from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusion_matrix from sklearn.ensemble import RandomForestClassifier #------------------------------------------------------------------------------- # Bank Note Data Tensor Flow Project #------------------------------------------------------------------------------- bank = pd.read_csv('bank_note_data.csv') print("\n-------------------------------------------------------------------\n") print(bank.head()) print("\n-------------------------------------------------------------------\n") #------------------------------------------------------------------------------- # Data Set Visualization #------------------------------------------------------------------------------- """ sns.countplot(x = 'Class', data = bank) plt.show() sns.pairplot(bank, hue = 'Class') plt.show() """ #------------------------------------------------------------------------------- # Data Preparation - Standard Scaling #------------------------------------------------------------------------------- scaler = StandardScaler() scaler.fit(bank.drop('Class', axis = 1)) scaled_features = scaler.transform(bank.drop("Class", axis = 1)) bank_features = pd.DataFrame(scaled_features, columns = bank.columns[:-1]) print(bank_features.head()) print("\n-------------------------------------------------------------------\n") #------------------------------------------------------------------------------- # Training Model Data #------------------------------------------------------------------------------- X = bank_features y = bank['Class'] X = X.as_matrix() y = y.as_matrix() X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3) #------------------------------------------------------------------------------- # fitting a DNN Classifier for predictions #------------------------------------------------------------------------------- feature_columns = [tf.contrib.layers.real_valued_column("", dimension=1)] classifier = learn.DNNClassifier(hidden_units = [10, 20, 10], n_classes = 2, feature_columns = feature_columns) classifier.fit(X_train, y_train, steps = 200, batch_size = 32) bank_predictions = classifier.predict(X_test, as_iterable = False) print("\n-------------------------------------------------------------------\n") print("Classification report for Deep Neural Network:\n", classification_report(y_test, bank_predictions)) print("\n-------------------------------------------------------------------\n") print("Confusion matrix for Deep Neural Network:\n", confusion_matrix(y_test, bank_predictions)) print("\n-------------------------------------------------------------------\n") #------------------------------------------------------------------------------- # fitting a Random Forest Classifier for predictions #------------------------------------------------------------------------------- rfc = RandomForestClassifier(n_estimators=200) rfc.fit(X_train,y_train) rfc_pred = rfc.predict(X_test) print("Classification report for Random Forest:\n", classification_report(y_test, rfc_pred)) print("\n-------------------------------------------------------------------\n") print("Confusion matrix for Random Forest:\n", confusion_matrix(y_test, rfc_pred)) print("\n-------------------------------------------------------------------\n")
true
f0004a71f6fe3fb5c0d77e30b4d5eddeb91b4c7b
Python
reyn0149/CST9279-Lab-6
/Test Program.py
UTF-8
1,222
3.390625
3
[]
no_license
from displayObject import displayObject x = 0 y = 0 inputInt = 1 inputString = "" f1 = [ [1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1], [0,1,1,1,1,1,1,0], [1,0,1,1,1,1,0,1], [1,0,0,1,1,0,0,1], [1,0,0,1,1,0,0,1], [0,0,0,1,1,0,0,0], [0,0,0,0,0,0,0,0] ] pm = [[0,0,0,1,1,1,1,1,0,0,0], [0,0,1,1,1,1,1,1,1,0,0], [0,1,1,1,1,1,1,1,1,1,0], [1,1,1,1,1,1,1,1,0,0,0], [1,1,1,1,1,1,1,0,0,0,0], [1,1,1,1,1,1,0,0,0,0,0], [1,1,1,1,1,1,0,0,0,0,0], [1,1,1,1,1,1,1,0,0,0,0], [1,1,1,1,1,1,1,1,0,0,0], [0,1,1,1,1,1,1,1,1,1,0], [0,0,1,1,1,1,1,1,1,0,0], [0,0,0,1,1,1,1,1,0,0,0] ] print("Hello! Welcome to the displayObject test program!") while inputInt != 0: print("Please make a selection below!") print("0: Quit") print("1: Display fighter ship") print("2: Display Pac-man") inputString =input("Make a selection now! ") inputInt =int(inputString) if inputInt == 0: print("Thanks for testing!") break x =input("What would you like the x coordinate of the object to be? ") y =input("What would you like the y coordinate of the object to be? ") if inputInt == 1: displayObject(f1,x,y) print("Here's a fighter jet! \n") elif inputInt == 2: displayObject(pm,x,y) print("Here comes Pacman! \n") else: print("Invalid input! \n")
true
ea766a6ac105ba1627f0dc98c4bc73b3ee1092e7
Python
IMDCGP105-1819/portfolio-ShmigabornDungiedoo
/ex5.py
UTF-8
283
3.6875
4
[]
no_license
beer= 99 while beer>0: print(str(beer) + " bottles of beer on the wall, " + str(beer) + " bottles of beer.") beer = beer -1 print("no more bottles of beer on the wall, no more bottles of beer.") print("Go to the store and buy some more, 99 bottles of beer on the wall...")
true
07869989b7de98acfc2b437471912da5de99182a
Python
ihlavsya/image_captioning
/helper.py
UTF-8
4,022
2.65625
3
[]
no_license
"""module with helper functions that are used in many places in project""" import os import numpy as np import torch import matplotlib.pyplot as plt from coco_dataset import CocoDataset, collate_fn from storage import Storage def get_imgs_dir_filename(data_dir, data_type): """get name of images directory""" imgs_dir = "{0}/images/{1}".format(data_dir, data_type) return imgs_dir def get_annotations_json_filename(data_dir, data_type, prefix=""): """get name of file for annotations to images""" captions_filename = "{0}/annotations/{1}captions_{2}.json".format( data_dir, prefix, data_type) return captions_filename def get_captions_json_filename(data_dir, data_type, prefix=""): """get name of file for annotations to images""" captions_filename = "{0}/captions/{1}captions_{2}.json".format( data_dir, prefix, data_type) return captions_filename def get_img_filename(data_dir, data_type, base_filename): """get name of file for annotations to images""" img_filename = os.path.join(data_dir, "images", data_type, base_filename) return img_filename def get_hdf5_filename(data_dir, data_type): """get name of file for hdf5 files that store images""" base_filename = "{}_images.hdf5".format(data_type) filename = os.path.join(data_dir, base_filename) return filename def plot_results(results, title): """display results""" fig = plt.figure() ax = fig.add_subplot(111) colors = ["red", "blue"] for i, label in enumerate(results.keys()): ax.plot(results[label], label=label, color=colors[i]) plt.legend(loc=2) plt.title(title) plt.show() plt.pause(50) def imshow(inp, title=None): """Imshow for Tensor.""" inp = inp.numpy().transpose((1, 2, 0)) mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) inp = std * inp + mean inp = np.clip(inp, 0, 1) plt.imshow(inp) if title is not None: plt.title(title) plt.pause(50) def save_checkpoint(loss_item, model_state_dict, checkpoint_path): """save model per checkpoint""" checkpoint_dict = { "model_state_dict": model_state_dict, "loss": loss_item, } torch.save(checkpoint_dict, checkpoint_path) def get_checkpoint_path(path, prefix, epoch): """get path for checkpoint""" checkpoint_filename = "{}.pt".format(epoch) checkpoint_path = os.path.join(path, prefix, checkpoint_filename) return checkpoint_path def get_dataloader(data_dir, data_type, wv): """get dataloader for specified data_loader/split""" images_dir = get_imgs_dir_filename(data_dir, data_type) ann_filename = get_annotations_json_filename(data_dir, data_type) dataset = CocoDataset(images_dir, ann_filename, wv, transform=Storage.DATA_TRANSFORMS) data_loader = torch.utils.data.DataLoader(dataset, batch_size=8, shuffle=True, collate_fn=collate_fn, num_workers=2) return data_loader def get_dataloaders(data_dir, data_types, wv): """get dataloaders for specified splits/data_types""" dataloaders = {} for data_type_key, data_type_value in data_types.items(): dataloader = get_dataloader(data_dir, data_type_value, wv) dataloaders[data_type_key] = dataloader return dataloaders def display_formatted_results(results): """display results in convenient format""" for key in sorted(results): rate_r, gamma_r = key val_accuracy, train_loss, lr, gamma, stats = results[(rate_r, gamma_r)] print("rate_r:{}, gamma_r:{}: val_accuracy:{}, train_loss:{}, lr:{}, gamma:{}".format( rate_r, gamma_r, val_accuracy, train_loss, lr, gamma )) plot_results(stats["losses"], "losses") plot_results(stats["accuracies"], "accuracies")
true
8b6ccdb6ff1d143fe0cd152e53b1789b34aad076
Python
ArjanVermeulen97/waterstanden
/waterstanden_melder.py
UTF-8
1,272
2.796875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Jul 31 23:13:01 2020 @author: Arjan """ import pandas as pd from datetime import date from pushtocal import push_event data = pd.read_csv('./waterstanden.csv', delimiter=';', index_col=False) for index in data.index: data['Meting'][index] = float(data['Meting'][index][1:-3]) today = date.today().strftime('%d/%m/%Y') data_today = (data[data['Datum'] == today].sort_values(by='Tijd')) agenda_string = "" for index in data_today.index: tijd = data_today.loc[index, 'Tijd'] HWLW = data_today.loc[index, 'Hoogwater/laagwater'] if 'H' in HWLW: HWLW = 'hoog' else: HWLW = 'laag' stand = data_today.loc[index, 'Meting'] if agenda_string: agenda_string = (f"{agenda_string}\n{tijd}, {HWLW}water {stand} cm") else: agenda_string = (f"{tijd}, {HWLW}water {stand} cm") event = { 'summary': f"Waterstand {today}", 'description': agenda_string, 'start': { 'date': date.today().strftime('%Y-%m-%d') }, 'end': { 'date': date.today().strftime('%Y-%m-%d') } } if date.today().isoweekday() == 6: response = push_event(event) print(response)
true
1fdb3a5036d3b5c3eb1b1ad60f9b97ba03ba2c46
Python
cenzwong/HackUST2021
/Sorting_Possible_Airport.py
UTF-8
2,746
2.75
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[4]: import pandas as pd import requests import json import datetime import time response = requests.get("https://raw.githubusercontent.com/mwgg/Airports/master/airports.json") raw_transport_code = json.loads(response.text) pd_raw_transport_code = pd.DataFrame(raw_transport_code) pd_airport_ICAO_code = pd_raw_transport_code pd_airport_ICAO_code = pd_airport_ICAO_code.T from math import sin, cos, sqrt, atan2, radians all_airport_lat = pd_airport_ICAO_code['lat'] all_airport_lon = pd_airport_ICAO_code['lon'] all_airport_lat = list(all_airport_lat) all_airport_lon = list(all_airport_lon) possible_airport_lat = 0 possible_airport_lon = 0 list_possible_airport_lon = [] list_possible_airport_lat = [] possible_airport_lat = float(possible_airport_lat) possible_airport_lon = float(possible_airport_lon) for i in range(len(all_airport_lat)): all_airport_lat[i] = float(all_airport_lat[i]) all_airport_lon[i] = float(all_airport_lon[i]) pd_airport_ICAO_code = pd_airport_ICAO_code.assign(float_lat = all_airport_lat) pd_airport_ICAO_code = pd_airport_ICAO_code.assign(float_lon = all_airport_lon) distance_from_airport = [] for i in range(len(all_airport_lat)): # approximate radius of earth in km R = 6373.0 lat_gps = radians(51.465003) lon_gps = radians(-0.470441) lat_airport_i = radians(all_airport_lat[i]) lon_airport_i = radians(all_airport_lon[i]) distance_lon = lon_airport_i - lon_gps distance_lat = lat_airport_i - lat_gps a = sin(distance_lat / 2)**2 + cos(lat_gps) * cos(lat_airport_i) * sin(distance_lon / 2)**2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = R * c if distance <= 10: distance_from_airport.append(distance) list_possible_airport_lat.append(all_airport_lat[i]) list_possible_airport_lon.append(all_airport_lon[i]) else: continue for i in range(len(distance_from_airport)): if len(distance_from_airport)==1: possible_airport_lat = list_possible_airport_lat[i] possible_airport_lon = list_possible_airport_lon[i] else: for j in range(len(distance_from_airport)): if distance_from_airport[i] < distance_from_airport[j]: possible_airport_lat = list_possible_airport_lat[i] possible_airport_lon = list_possible_airport_lon[i] else: continue print(possible_airport_lat,possible_airport_lon) departure_airport = pd_airport_ICAO_code[(pd_airport_ICAO_code['float_lat'] == possible_airport_lat) & (pd_airport_ICAO_code['float_lon'] == possible_airport_lon)] print(departure_airport) print(distance_from_airport) # In[ ]:
true
75e6f5d11b4db0b07a410858353181a41ae5a86a
Python
ZymHedy/code_practice
/offer/52match.py
UTF-8
4,935
3.828125
4
[ "MIT" ]
permissive
# -*- coding:utf-8 -*- class Solution: # s, pattern都是字符串 # 暴力法(用于帮助理解思路) # 虽然暴力法思路容易理解,但是当字符串过长,递归过深的时候复杂度极大,超出可运行时间 # 动态规划则不会出现这个问题,效率还是更高 def match(self, s, pattern): # write code here if not s and not pattern: return True elif s and not pattern: return False elif not s and pattern: if len(pattern) > 1 and pattern[1] == '*': return self.match(s, pattern[2:]) else: return False else: # s和pattern均不为空 # 区分pattern的下一个元素是否为* if len(pattern) > 1 and pattern[1] == '*': # s与pattern的第一个元素不同,相当于*前一个字符无法匹配,则pattern后羿两位 if s[0] != pattern[0] and pattern[0] != '.': return self.match(s, pattern[2:]) else: # s[0]==pattern[0]分为三种情况 # 1、*前的字符出现0次:s不变,直接忽略pattern的x*前两位,让字符串从后面几位开始匹配 # 2、*前的字符出现1次:s后移一位,pattern后移2位,eg:a与a*匹配 # 3、*前的字符出现n次:s后移一位,pattern不变 return self.match(s, pattern[2:]) or self.match(s[1:], pattern[2:]) or self.match(s[1:], pattern) else: if s[0] == pattern[0] or pattern[0] == '.': return self.match(s[1:], pattern[1:]) else: return False # 动态规划,找最优子结构,找状态转移方程,理论上来说复杂度更低 def isMatch(self, s, p): if not p: return not s # s空,p只有一个字符,一定是不匹配的 if not s and len(p) == 1: return False # 两种情况需要判断 # 1、s空p是长度大于1的非空字符串 # 2、s,p均为非空 # 找状态转移方程,要根据具体情况判定,if else # 初始化状态转移矩阵dp[i][j]:s的前i个字符与p的前j个字符相匹配 # 为了状态转移访问之前的状态,行列都多1 row = len(s) + 1 col = len(p) + 1 dp = [[False for j in range(col)] for i in range(row)] dp[0][0] = True # 预备状态 # 为70行的那种情况做初始化用的,逻辑的可解释性很差 for c in range(2, col): j = c - 1 if p[j] == '*': dp[0][c] = dp[0][c - 2] # 依据题目逻辑判断状态转移矩阵 # i,j从0开始,r,c从1开始 for r in range(1, row): i = r - 1 for c in range(1, col): j = c - 1 # 这种思路下我们只考虑s,p的当前元素和前一个元素 if p[j] == s[i] or p[j] == '.': dp[r][c] = dp[r - 1][c - 1] elif p[j] == '*': # 区分,p[j-1]与s[i]是否匹配 if p[j - 1] != s[i] and p[j - 1] != '.': dp[r][c] = dp[r][c - 2] else: # 分为三种情况 # 1、*匹配0次s[i] # 2、*匹配1次s[i],不需要考虑这种情况了,p[j] == s[i]在第一个if分支已经考虑过了 # 3、*匹配n次s[i] dp[r][c] = dp[r][c - 2] or dp[r - 1][c] else: dp[r][c] = False return dp[row - 1][col - 1] # 仿照遍历法的思路不可行,主要因为字符串和矩阵的上界下界问题 # # 如果按照下一个元素是否是*这种方式,到达字符串上界的时候一定会溢出 # # 字符串下界的溢出已经通过矩阵从1开始遍历,且pattern的首个元素不等于* # # 区分p的下一个元素是否是* # if p[j + 1] == '*': # # 区分p中*的前一个字符是否与s的当前字符匹配 # # 因为pattern不会出现第一个字符是*的情况,所以p[j-1]不会越界 # if p[j - 1] != s[i] and p[j-1] != '.': # dp[r][c] = dp[r][c-2] # pass # else: # pass # else: # if p[j] == s[i] or p[j] == '.': # dp[r][c] = dp[r - 1][c - 1] so = Solution() s = 'aaaaaaaaaaaaab' pattern = 'a*a*a*a*a*a*a*a*a*a*c' # ans = so.match(s, pattern) ans1 = so.isMatch(s,pattern) # print(ans) print(ans1)
true
8104ba2324f6f7f8af81264802184ea7c6321cb4
Python
wiresboy/6.111-Minesweeper
/custom_fs/fs_write.py
UTF-8
1,698
2.8125
3
[]
no_license
import wave import sys from math import ceil from struct import pack filenames = sys.argv[1:] print("Loading files: ",filenames) #Open disk print("wmic diskdrive list brief") print("Did you check that \\\\.\\PhysicalDrive2 is the correct drive???? THIS CAN KILL YOUR LAPTOP!") a=input() if "yes" not in a: 1/0 sd = open("\\\\.\\PhysicalDrive2", mode="rb") sd.seek(0) original = sd.read(512) sd.close() if original[0:15] == b"Brandon'sFS 1.0": print("correct card found") else: print("card may not be formatted correctly...double check its the right one!") 1/0 sd = open("\\\\.\\PhysicalDrive2", mode="rb+") def sd_write_bytes(b): global sector_count, sd #sd.seek(sector_count*512) #blist = [b[n:n+512] for n in range(0,int(ceil(len(b)/512)),512 )] #for sect in blist: x = (b+b'\x00'*512)[:512] sd.write(x) sector_count += 1 waves_data=list() sector_count = 2 for name in filenames: w = wave.open(name, "r") waves_data.append( (name, sector_count, w.getnframes()) ) print("\n\nFile: ",name) print("Sample width: ",w.getsampwidth()) print("Sample rate: ", w.getframerate()) print("Num samples: ", w.getnframes()) sd.seek(sector_count*512) for z in range(int(ceil(w.getnframes()/512))): sd_write_bytes(w.readframes(512)) w.close() print(sector_count) print() sect0 = b"Brandon'sFS 1.0\x00" for w in waves_data: name = w[0] start_sector = w[1] samples = w[2] print(name,": start_sector=",start_sector,", samples=",samples) sect0 += pack('>I', start_sector*512) sect0 += pack('>I', samples) sect0 = (sect0+b'\x00'*512)[:512] sd.seek(0) sd.write(sect0)
true
ecbeaca584a4f8dfeddb5e1a240742282a5a5438
Python
olekmali/eTCP_Python
/30_intro_to_sockets/304_append_together.py
UTF-8
777
3.71875
4
[]
no_license
import sys """ This program demonstrates how to append data together and then how to split it using the first occurrence of an empty line """ buffer = b""; print( "Enter several lines of text followed by EOF character - Ctrl+Z") while True: data = bytes( sys.stdin.readline(), 'UTF-8' ) # data chunk, e.g. from a TCP socket if not data: break buffer += data print( "Data received:\r\n", buffer ) print( "\r\n\r\nAttempting to split the buffer using the first empty line:\r\n" ) header, page = buffer.split(b"\n\n", 1) # use with console test #header, body = buffer.split(b"\r\n\r\n", 1) # use with TCP socket and HTTP protocol test print( "Header:\r\n", str(header, 'UTF-8') ) print( "Page:\r\n", str(page, 'UTF-8') )
true
6cfe8a340a12bc40816b0a3584c475104ec8db4a
Python
Rusllan/PyxelTest
/PyxelTest.py
UTF-8
3,955
3.25
3
[]
no_license
import pyxel COL_BACKGROUND = 0 TILE_SIZE = 8 SCREEN_WIDTH = 160 SCREEN_HEIGHT = 120 def draw_tile(x, y, image_num, color): i = image_num // 10 j = image_num % 10 pyxel.pal(7, color) pyxel.blt(x*TILE_SIZE, y*TILE_SIZE, 0, j*TILE_SIZE, i*TILE_SIZE, TILE_SIZE, TILE_SIZE) pyxel.pal() class Object: last_id = 0 def __init__(self, x, y, color=0, sprite=0, solid=True, behavior=None): self.id = Object.last_id Object.last_id += 1 self.color = color self.sprite = sprite self.x = x self.y = y self.solid = solid self.image_x = (sprite % 10)*TILE_SIZE self.image_y = (sprite // 10)*TILE_SIZE self.solid = solid self.behavior = behavior @classmethod def from_name(cls, x, y, name, color=0, sprite=1, solid=True, behavior=None): if name == 'player': color = 8 sprite = 82 behavior = 'player' elif name == 'wall': color = 2 sprite = 1 elif name == 'stairs_down': color = 2 sprite = 12 solid = False return Object(x, y, color=color, sprite=sprite, solid=solid, behavior=behavior) def draw(self): draw_tile(self.x, self.y, self.sprite, self.color) def make_a_move(): in_game_keys = [pyxel.KEY_W, pyxel.KEY_A, pyxel.KEY_S, pyxel.KEY_D] if any(pyxel.btnp(key) for key in in_game_keys): return True else: return False class ObjectHandler: def __init__(self): self.objects = [] self.generate_location() def generate_location(self): self.objects.append(Object.from_name(13, 5, 'player')) self.objects.append(Object.from_name(4, 4, 'stairs_down')) for i in range(SCREEN_WIDTH // TILE_SIZE): self.objects.append(Object.from_name(i, 0, 'wall')) for i in range(SCREEN_WIDTH // TILE_SIZE): self.objects.append(Object.from_name(i, SCREEN_HEIGHT // TILE_SIZE - 1, 'wall')) for i in range(1, SCREEN_HEIGHT // TILE_SIZE-1): self.objects.append(Object.from_name(0, i, 'wall')) for i in range(1, SCREEN_HEIGHT // TILE_SIZE-1): self.objects.append(Object.from_name(SCREEN_WIDTH // TILE_SIZE - 1, i, 'wall')) def passable(self, x, y): for obj in self.objects: if obj.x == x and obj.y == y and obj.solid is True: return False return True def perform_moves(self): for obj in self.objects: if obj.behavior == 'player': if pyxel.btnp(pyxel.KEY_W) and self.passable(obj.x, obj.y - 1): obj.y = (obj.y - 1) % SCREEN_HEIGHT elif pyxel.btnp(pyxel.KEY_A) and self.passable(obj.x - 1, obj.y): obj.x = (obj.x - 1) % SCREEN_WIDTH elif pyxel.btnp(pyxel.KEY_S) and self.passable(obj.x, obj.y + 1): obj.y = (obj.y + 1) % SCREEN_WIDTH elif pyxel.btnp(pyxel.KEY_D) and self.passable(obj.x + 1, obj.y): obj.x = (obj.x + 1) % SCREEN_WIDTH class App: def __init__(self): pyxel.init(SCREEN_WIDTH, SCREEN_HEIGHT) pyxel.image(0).load(0, 0, 'minirogue-c64-all.png') self.objectHandler = ObjectHandler() pyxel.run(self.update, self.draw) def update(self): if make_a_move(): self.objectHandler.perform_moves() def draw(self): pyxel.cls(COL_BACKGROUND) for i in range(SCREEN_HEIGHT // TILE_SIZE): for j in range(SCREEN_WIDTH // TILE_SIZE): pyxel.rectb(j * TILE_SIZE, i * TILE_SIZE, (j + 1) * TILE_SIZE - 1, (i + 1) * TILE_SIZE - 1, 5) for obj in self.objectHandler.objects: obj.draw() if pyxel.btn(pyxel.KEY_T): for i in range(128): draw_tile(i % 10 + 1, i // 10 + 1, i, 1 + i % 14) App()
true
00eb00c411b7fe4a8ca5ce3964aff627e48fdf10
Python
sahilkamboj3/research
/localguides/user_info/csv_funcs.py
UTF-8
3,092
2.6875
3
[]
no_license
import pandas as pd from os import path import os users_columns = [ 'id', 'name', 'level', 'total_messages_posted', 'total_likes_received', 'total_likes_given', 'description', # None means no description 'total_badges', 'badges' # array ] likes_given_to_posts_columns = [ 'id', 'name', 'author', 'author_url', 'author_id', 'post_title', 'post_type', 'total_replies', 'total_likes', 'icon', 'date_posted' ] likes_received_for_posts_columns = [ 'id', 'name', 'post_title', 'post_type', 'total_replies', 'total_likes', 'icon', 'date_posted', ] likes_received_from_users_columns = [ 'to_id', 'to_name', 'from_username', 'from_id', 'from_url', 'from_level', 'from_likes', ] likes_given_to_users_columns = [ 'from_id', 'from_name', 'to_username', 'to_id', 'to_url', 'to_level', 'to_likes', ] titles_arr = [ users_columns, likes_given_to_posts_columns, likes_received_for_posts_columns, likes_given_to_users_columns, likes_received_from_users_columns, ] FILENAMES_checkpoint = { 'users.csv': 'id', 'likes_given_to_posts.csv': 'id', 'likes_received_for_posts.csv': 'id', 'likes_given_to_users.csv': 'from_id', 'likes_received_from_users.csv': 'to_id', } def df_drop_duplicates(): ABS_PATH = path.dirname(__file__) for filename in FILENAMES_checkpoint: ABS_PATH = path.dirname(__file__) + '/csv_files/' + filename df = pd.read_csv(ABS_PATH) print(filename) print("old: ", len(df)) new_df = df.drop_duplicates() print("new: ", len(new_df)) new_df.to_csv(ABS_PATH, index=False) def print_file_lengths(): ABS_PATH = path.dirname(__file__) for filename in FILENAMES_checkpoint: ABS_PATH = path.dirname(__file__) + '/csv_files/' + filename df = pd.read_csv(ABS_PATH) print(f"{filename}: {len(df)}") def get_users_csv_length(): for filename in FILENAMES_checkpoint: if filename == 'users.csv': ABS_PATH = path.dirname(__file__) + '/csv_files/' + filename df = pd.read_csv(ABS_PATH) print("users.csv: ", len(df)) def get_timeout_txt_length(): count = 0 filename = 'timeout_ids_3.txt' with open(filename, 'r') as f: for line in f: content = line[:-1] if content != 'Anonymous': count += 1 print("Timeout errors: ", count) def check_uniques_txt_files(): print("here") seen = {} filename = 'timeout_ids_3.txt' with open(filename, 'r') as f: for line in f: content = line[:-1] if content != 'Anonymous': if content not in seen: # print(f"{content} unique") seen[content] = 1 else: print(f"{content} duplicated") # get_timeout_txt_length() # print_file_lengths() # df_drop_duplicates() check_uniques_txt_files()
true
68ee32332e1335a133a94008794a7494ed228a26
Python
CollinJ/Robin
/Robin/Simulation/Graph.py
UTF-8
6,462
3.015625
3
[]
no_license
import pygraphviz as pgv from ucb import interact class Graph: def __init__(self, *nodes): self.nodes = list(nodes) self.G = pgv.AGraph(resolution="75", overlap='scale', splines="True") def __iter__(self): return self.nodes.__iter__() def __repr__(self): string = "" for node in self: string += str(node) + '\n' return string def summary2(self, this_node): max_edges = 0 shortest_path_dict = dict() #Key = Node.id : Value = len(shortest path from HOST to KEY) out_edges_dict = dict() #Key = Node.id : Value = list of nodes that are outward from it votes_dict = dict() #Key = Node.id : Value = number of votes they have. for node in self: # This builds the shortest_path_dict by the length each node is away from the HOST node if this_node.id != node.id: path = this_node.shortestPathTo(node) if path is not None: shortest_path_dict[node.id] = len(path) else: shortest_path_dict[node.id] = 0 for node in self: #Builds the out_edges_dict by calculating how many connecting nodes are at least as far away from host as this node if this_node.id != node.id: #Don't look at host node for edge_node_id in node.trusts: #check each node connected to this one if edge_node_id != this_node.id: if shortest_path_dict[edge_node_id] > shortest_path_dict[node.id]: #if they are farther away from host than we are, we give them some votes if node.id in out_edges_dict: #add ourself to the list of nodes that are outward from the node we are looking at out_edges_dict[node.id] += [edge_node_id] else: out_edges_dict[node.id] = [edge_node_id] max_edges = len(max(out_edges_dict.values(), key=len)) #unused now const_vote_percent = .1 #percent of votes it gives to each ouward edge <------THIS IS SOMETHING YOU CAN CHANGE queue = [] #BF distribution of votes for edge_id in this_node.trusts: #Populate the immediate friends vote counts votes_dict[edge_id] = 100/len(this_node.trusts) queue.append(edge_id) while len(queue) != 0: const_vote_percent = .1 node_id = queue.pop(0) if node_id in out_edges_dict: num_nodes = len(out_edges_dict[node_id]) if num_nodes * const_vote_percent > .7: # <----- CHANGE THIS .5 const_vote_percent = .7/num_nodes # <------ AND THIS .5 TO THE SAME NUMBER for edge_node_id in out_edges_dict[node_id]: if edge_node_id == this_node.id: continue votes_dict[edge_node_id] = const_vote_percent * votes_dict[node_id] queue.append(edge_node_id) votes_dict[node_id] -= const_vote_percent * votes_dict[node_id]*len(out_edges_dict[node_id]) print(str(out_edges_dict)) return votes_dict def summary(self, this_node): total_unique_paths = 0 unique_paths_by_node = {} # <- Collin can't name things. This is # node.id: list of path lengths real_unique_paths_by_node = {} for node in self: if node != this_node: paths = this_node.pathsTo(node) real_unique_paths_by_node[node.id] = paths unique_paths_by_node[node.id] = [len(path) for path in paths] total_unique_paths += sum(unique_paths_by_node[node.id]) ## print(unique_paths_by_node) ## print(total_unique_paths) summary = dict((node, sum([(total_unique_paths*1.0)/i for i in unique_paths_by_node[node]])) for (node) in unique_paths_by_node.keys()) max_trust = max(summary.values()) summary = dict((node, (summary[node]*1.0)/max_trust) for (node) in unique_paths_by_node.keys()) newSum = {} for nodeId in real_unique_paths_by_node.keys(): Paths = real_unique_paths_by_node[nodeId] print("Paths: ", Paths) if Paths == []: continue pathNodes = real_unique_paths_by_node[nodeId][0].getNodes() print("This node: ", this_node.id) print("Path Nodes: ", pathNodes) print("Summary Keys: ", summary.keys()) invertedPathNodePhase1TrustValues = [] for path_node in pathNodes: if (path_node.id != this_node.id): invertedPathNodePhase1TrustValues.append(summary[path_node.id]**(-1)) newSum[nodeId] = sum(invertedPathNodePhase1TrustValues) ## for node in summary.keys(): ## print(str(node) + " : " + str(summary[node])) return newSum def drawMe(self, this_node=None): if this_node is not None: summary = self.summary2(this_node) for node in self.nodes: for trust in node.trusts: if this_node == None: self.G.add_edge(node.id, trust) elif node.id == this_node.id: self.G.add_edge(this_node.id, str(trust) + ":" + str(round(summary[trust], 6))) elif this_node.id == trust: self.G.add_edge(this_node.id, str(node.id) + ":" + str(round(summary[node.id], 6))) else: self.G.add_edge(str(node.id) + ":" + str(round(summary[node.id], 6)), str(trust) + ":" + str(round(summary[trust], 6))) else: for node in self.nodes: for trust in node.trusts: if trust is not node.id: self.G.add_edge(node.id, trust) print("Creating graf") self.G.layout(prog='dot') self.G.draw('graph.png') def printSummary(self, node): summary = self.summary(node) for node in summary.keys(): print(str(node) + " : " + str(summary[node])) def add(self, node): self.nodes.append(node)
true
08b372e35c21d27e477980c88333cd6771415ead
Python
israel-dryer/woodberry-chapel-interface
/src/controllers/mixins.py
UTF-8
532
3.046875
3
[]
no_license
import webbrowser import tkinter as tk from tkinter.ttk import Widget class Navigation: """A mix-in class to enable control view and web navigation""" @staticmethod def navigate_to_url(url: str): """Open url in a new browser tab""" webbrowser.open(url, new=2) @staticmethod def navigate_to_view(current_view: Widget, target_view: str): current_view.pack_forget() target = current_view.master.nametowidget(target_view) target.pack(pady=10, fill=tk.BOTH, expand=tk.YES)
true
7dae33c9d101a1be473d76b9a8a3a3fe3dd8ff11
Python
Vladis466/Homework
/Spring 2016/CS 325/HW1/fibo.py
UTF-8
835
3.859375
4
[]
no_license
import time def fiboIterative(x): num1 = 0 num2 = 1 temp = 0 if x == 0: return 0 elif x == 1: return 1 else: for i in xrange(2, x): temp = num2 num2 += num1 num1 = temp return num2 def fiboRecursive(x): if x == 0: return 0 elif x == 1: return 1 else: return fiboRecursive(x-1) + fiboRecursive(x-2) def in_the_forest(duck): print(duck.quack()) def main(): print "insert a number representing the index of the fibbonacci number to iterate up to please" num = int(raw_input()) print "insert i for iterative or r for recursive" choice = raw_input() if choice == 'i': start_time = time.time() ans = fiboIterative(num) if choice == 'r': start_time = time.time() ans = fiboRecursive(num) print("--- %s seconds ---" % (time.time() - start_time)) if __name__ == "__main__": main()
true
803c880a9cffc6f77f526808650afbd79d8ea6e9
Python
Hyun-mo/2021-Data-Analysis
/merge_dust_month.py
UTF-8
928
2.9375
3
[]
no_license
import os import pandas as pd def mergeDust(filePath): print(filePath) data = pd.read_csv(filePath) data.fillna(0, inplace=True) out = {} for idx in range(len(data)): day = data.iloc[idx][0] dust = data.iloc[idx][1] day = str(day) if day in out: out[day[0:6]][0] += dust out[day[0:6]][1] += 1 else: out[day[0:6]] = [dust,1] for key, value in out.items(): out[key] = round(value[0]/value[1], 2) return out def init(): Dir = './전처리/일별/대기오염도' fileList = os.listdir(Dir) out = {} for File in sorted(fileList): filePath = '/'.join([Dir, File]) out.update(mergeDust(filePath)) out_file = pd.DataFrame(list(out.items()), columns=['month', 'dust']) out_file.to_csv('./전처리/월별/dust.csv', index=False) if __name__ == '__main__': init()
true
fc04dfaa1a0db559d134e03dbf9579b7a30965fd
Python
phantom-5/ANN_Parameter_Tuning
/parameter_tuning.py
UTF-8
2,066
2.96875
3
[]
no_license
#data preprocessing #classification into whether or not a person buys from into age,sal #imports import numpy as np import matplotlib.pyplot as plt import pandas as pd #getting dataset dataset=pd.read_csv('Churn_Modelling.csv') X=dataset.iloc[:,3:13].values Y=dataset.iloc[:,13].values #mising data - fine #categorical to numerical from sklearn.preprocessing import LabelEncoder,OneHotEncoder labelencoder_X1=LabelEncoder() X[:,1]=labelencoder_X1.fit_transform(X[:,1]) labelencoder_X2=LabelEncoder() X[:,2]=labelencoder_X2.fit_transform(X[:,2]) onehotencoder=OneHotEncoder(categorical_features=[1]) X=onehotencoder.fit_transform(X).toarray() X=X[:,1:] labelencoder_Y=LabelEncoder() Y=labelencoder_Y.fit_transform(Y) #splitting from sklearn.model_selection import train_test_split X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=0) #scaling from sklearn.preprocessing import StandardScaler sc_X=StandardScaler() X_train=sc_X.fit_transform(X_train) X_test=sc_X.transform(X_test) #Training and Evaluating the ANN using K-Fold Cross Validation #Step -1 Imports from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import GridSearchCV from keras.models import Sequential from keras.layers import Dense def build_classifier(optimizer): classifier=Sequential() classifier.add(Dense(output_dim=6,input_dim=11,init='uniform',activation='relu')) classifier.add(Dense(output_dim=6,init='uniform',activation='relu')) classifier.add(Dense(output_dim=1,init='uniform',activation='sigmoid')) classifier.compile(optimizer=optimizer,loss='binary_crossentropy',metrics=['accuracy']) return classifier classifier=KerasClassifier(build_fn=build_classifier) parameters={'batch_size':[25,32], 'epochs':[100,500], 'optimizer':['adam','rmsprop']} grid_search=GridSearchCV(estimator=classifier,param_grid=parameters,scoring='accuracy',cv=10) grid_search=grid_search.fit(X=X_train,y=Y_train) best_parameters=grid_search.best_params_ best_accuracy=grid_search.best_score_
true
c97b310321b7d6d6d7732f7d96e024e42c9f8257
Python
qijiamin/learn-python
/test2-1.py
GB18030
552
2.890625
3
[]
no_license
# -*- coding:utf-8 -*- #########ѧϢ############ #: #ѧ:1403050116 #༶ͨ14-1 ##############Ŀ############### #12.8 ############################# import math p,k,T,M,NA,n,m,R=1.013e5,1.38e-23,300.15,32e-3,6.022e23,2.45e25,5.31e-26,8.31 n=p/(k*T) print 'n=p/(k*T)=',n n=M/NA print 'n=M/NA=',n rho=n*m print 'rho=n*m=',rho v=math.sqrt(3*R*T/M) print 'v=math.sqrt(3*R*T/M)=',math.sqrt(v**2) epsilonk=3/2*k*T print 'epsilonk=3/2*k*T=',epsilonk epsilon=m/M*5/2*R*T print 'epsilon=m/M*5/2*R*T=',epsilon
true
8e583e3761c49c4abb6871252fd774e68888392e
Python
andrewfandy/time_mover
/movetimeV2.py
UTF-8
2,771
3.71875
4
[]
no_license
def leapYear(year): if year%400 == 0: return False if year%100 == 0: return False if year%4 == 0: return False return True def checkMonth(day, month, year): if day > 31 and (month in [1, 3, 5, 7, 8, 10, 12]): return False elif day > 30 and (month in [4, 6, 9, 11]): return False elif day > 28 and month == 2 and leapYear(year): return False elif day > 29 and month == 2: return False return True def listMonth(month): monthList = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'] return monthList[month-1] def subMonth (day, month, year): if month in [1,3,5,7,8,10,12]: return 31 elif month in [4,6,9,11]: return 30 elif month == 2 and leapYear(year): return 28 elif month == 2: return 29 def moveForward(day, month, year): try: forDay = int(input('Majukan berapa hari?, input: ')) except: print('Invalid input') return moveForward(day, month, year) day += forDay while day > 1 and not checkMonth(day, month, year): day -= subMonth(day, month, year) month += 1 if month > 12: month = 1 year += 1 return '\n\nHasil : %d %s %d C.E'%(day, listMonth(month), year) def moveBackward(day, month, year): try: backDay = int(input('Mundurkan berapa hari?, input: ')) except: print('Invalid input') return moveBackward(day, month, year) day -= backDay while day < 1 and checkMonth(day, month, year): month -= 1 if month < 1: month = 12 year -= 1 day += subMonth(day, month, year) if year < 0: return '\n\nHasil : %d %s %d B.C'%(day, listMonth(month), abs(year)) return '\n\nHasil : %d %s %d C.E'%(day, listMonth(month), year) def main(): day = int(input('Input tanggal : ')) month = int(input('Input bulan : ')) year = int(input('Input tahun : ')) if checkMonth(day, month, year): while True: forward_backward_input = int(input('[1] Majukan hari\n[2] Mundurkan hari\nInput :')) if forward_backward_input == 1: return moveForward(day, month, year) elif forward_backward_input == 2: return moveBackward(day, month, year) else: print('Pilih 1 atau 2') else: print('Invalid input') return main() print('-'*5+'SELAMAT DATANG'+'-'*(5)+'\n'*5) print(main())
true
9a4cfd2c41a92a47b04efc8e4dd447da98a95e3e
Python
quinzel25/Capstone-Week-3
/camelCase.py
UTF-8
972
4.375
4
[]
no_license
# Lab 1 Part 3 import re # function to convert a string into camelCase def camelCase(snake_str): components = snake_str.split(' ') # capitalize the first letter of each component except the first one # with the 'title' method and join them together. return components[0] + ''.join(x.title() for x in components[1:]) # This code taken from stacked overflow but the original splits it based on "_" # and I changed it to work with a ' ' (blank space) to work for this instance def display_banner(): """ Display program name in banner """ msg = 'AWESOME camelCaseGenerator program' stars = '*' * len(msg) print(f'\n {stars} \n {msg} \n {stars} \n') def main(): display_banner() print('Just type in any sentence regardless of case and this program will convert it into camelCase! \n') sentence = input('Enter your sentence: ') output = camelCase(sentence) print(output) if __name__ == '__main__': main()
true
43e3f972ae84781d4f30d6bd73456fe87b93f068
Python
TadejPanjtar/GrowRoom
/pyzapiski.py
UTF-8
1,703
2.6875
3
[]
no_license
LOGGING=True def log(msg): if LOGGING: print strftime("%Y-%m-%d %X"), msg from time import strftime,sleep from stgs import stgs lightHours=[] lightOldOn=False # read light status LIGHT_HOURS_LEAP=24 LIGTH_HOURS_START=stgs.lightStart LIGTH_HOURS_DURATION=stgs.lightDuration tenMinutesRun=False blinkTick=0 if (LIGTH_HOURS_START+LIGTH_HOURS_DURATION > LIGHT_HOURS_LEAP): lightHours = range(LIGTH_HOURS_START,LIGHT_HOURS_LEAP) + range(0, LIGTH_HOURS_START+LIGTH_HOURS_DURATION-LIGHT_HOURS_LEAP) else: lightHours = range(LIGTH_HOURS_START, LIGTH_HOURS_START+LIGTH_HOURS_DURATION) def handle_light(): global lightOldOn currentHour=int(strftime("%S")) #int(strftime("%H")) lightOn=True if currentHour in lightHours else False if lightOldOn!=lightOn: s=' OFF ' if lightOn==True: s=' ON ' log('Turning lights'+s) lightOldOn=lightOn print 'lightHours', lightHours def tenMinutesCheck(): global tenMinutesRun, blinkTick tenMinutes=(strftime("%S")[1]=='0') # every 10 minutes if tenMinutesRun!=tenMinutes: print "10 minutes" #if tenMinutes: # handle_light() # handle_heating() # handle_pomp2() # handle_pomp() blinkTick=0 tenMinutesRun=tenMinutes t=None; h=None; moisture=33; while True: if blinkTick % 3 == 0: print "sensor 1" if blinkTick % 3 == 1: print "sensor 2" if blinkTick % 3 == 2: print "sensor 3" # TODO implement sleep(1) t=None; h=None; moisture=33; if t: # handle empty variable temperature=t if h: humidity=h if blinkTick % 2== 0: print 'Temp={0:0.1f}*C Humidity={1:0.1f}% Moisture={1:0.1f}%' .format(temperature, humidity, moisture) blinkTick=blinkTick+1
true
74cafb2bee5b280cdff113d19e94ec73e063dd7d
Python
everett-j/python_stack_2
/flask/flask_fundamentals/understanding_routing/understanding.py
UTF-8
637
3.09375
3
[]
no_license
from flask import Flask app = Flask(__name__) #KEEP THIS CODE ABOVE @app.route('/') def hello_world(): return 'Hello World!' @app.route('/dojo') def success(): return 'Dojo!' @app.route('/say/<name>') def hello(name): return (f"Hi {name} !") @app.route('/repeat/<rep>/<phrase>') def repeater(phrase, rep): rep = int(rep) return(f"{phrase}\n" * rep) @app.route("/<name>/<times>") def hello_person(name, times) print(name) return render_template ("play.html". some_name=name, num_times=int(times)) #KEEP THIS CODE BELOW if __name__=="__main__": app.run(debug=True)
true
25118c4481fe1d53d82f84470cd5a6a6d727db97
Python
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/bob/6c55cbd247b7409598fdf547f06b2368.py
UTF-8
279
3.46875
3
[]
no_license
import string def hey(what): if what.strip() == "": return "Fine. Be that way!" if any(c in string.ascii_letters for c in what) and what.isupper(): return "Whoa, chill out!" if what.endswith("?"): return "Sure." return "Whatever."
true
acd2bb18e10dce1b7271eb749e3f2619106c118c
Python
visHUSTLE/Asynchronous_Message_Server
/socket_client.py
UTF-8
6,591
2.84375
3
[]
no_license
#Vishnu Raju Nandyala #ID: 1001670678 # socket connection reference : https://www.journaldev.com/15906/python-socket-programming-server-client #https://github.com/YashAvlani009/Sockets-and-Thread-Management #https://www.geeksforgeeks.org/socket-programming-multi-threading-python/ from tkinter import * from tkinter import scrolledtext import tkinter.scrolledtext as ScrolledText from email.utils import formatdate import os import socket from tkinter import simpledialog import tkinter import tkinter as tk from socket_server import connections import threading # Connection Process host = socket.gethostname() # as both code is running on same pc port = 5000 # socket server port number client_socket = socket.socket() # instantiate def parse_http_message(message): # parse HTTP message data = message.decode().split('\r\n')[-1] data = data.replace('DATA:', '') return data def get_http_message(message): # encode HTTP message http_format = 'POST /test HTTP/1.1\r\n'\ 'Host: localhost\r\n'\ 'Date: #DATE#\r\n'\ 'User-Agent: client_application\r\n'\ 'Content-Type: application/x-www-form-urlencoded\r\n'\ 'Content-Length: #LEN#\r\n'\ '\r\n'\ 'DATA:' + message http_format = http_format.replace('#LEN#', str(len(message))) date = formatdate(timeval=None, localtime=False, usegmt=True) http_format = http_format.replace('#DATE#', date) return http_format class EntryWithPlaceholder(tk.Entry): # Class to Put placeholder in Entry def __init__(self, master=None, placeholder="PLACEHOLDER", color='grey'): super().__init__(master) self.placeholder = placeholder self.placeholder_color = color self.default_fg_color = self['fg'] self.bind("<FocusIn>", self.foc_in) self.bind("<FocusOut>", self.foc_out) self.put_placeholder() def put_placeholder(self): self.insert(0, self.placeholder) self['fg'] = self.placeholder_color def foc_in(self, *args): if self['fg'] == self.placeholder_color: self.delete('0', 'end') self['fg'] = self.default_fg_color def foc_out(self, *args): if not self.get(): self.put_placeholder() def client_program(): # client pro print("CLient Program Called") print('Number of Connections ', len(connections)) if len(connections) < 3: try: while True: data = parse_http_message(client_socket.recv(1024)) # receive response from server if data: print('Received from server: ' + data) # show in terminal scrolledtextLogs.insert(INSERT, data + '\n') # insert message in scrollerText except Exception as e: print(e) finally: print("Entered in finally ===> CLIENT") scrolledtextLogs.insert(INSERT, 'An existing connection with SERVER forcibly closed.') # window.destroy() else: print("Max Client Reached") def quit_Manual(): print("Byee") os._exit(0) def on_closing(): quit_Manual() def send_message(): # function to send message for 1to1 and 1toN print('MSG: ',e1.get()) print('DEstin :',e2.get()) if e2.get() != "Destination Client" and e2.get() != "": # check Destination is not empty if e1.get() != "Message" and e1.index("end") != 0: # check message is not empty # message = "BUZZ!!" print("Destination Client Name is :", e2.get()) message = e2.get() + ':' + e1.get() #concatinate destination and message with : client_socket.send(get_http_message(message).encode()) # send message scrolledtextLogs.insert(INSERT, message + '\n') e1.delete(0, 'end') else: print("Retrieved message") else: destName = e2.get() print('Enter the destination client:' + destName) client_socket.connect((host, port)) # connect to the server application_window = tkinter.Tk() # Dialogue to GET the UserName username = simpledialog.askstring("Input", "Enter the UserName", parent=application_window) threading.Thread(target=client_program).start() if username is not None: client_socket.send(get_http_message(username).encode()) # send message print("Your first name is ", username) master = Tk() lbl = Label(master, text=username) # declaring a label lbl.grid(row=0) e1 = EntryWithPlaceholder(master, "Message") # declaring message entry e1.grid(row=4, column=1) e2 = EntryWithPlaceholder(master, "Destination Client") # declaring Destination Client entry e2.grid(row=4, column=0) btn = Button(master, text='Send', command=send_message) # declaring Send button btn.grid(row=4, column=2) # declaring Quit button Button(master, text='Quit', command=quit_Manual).grid(row=0, column=2, sticky=W, pady=4) scrolledtextLogs = ScrolledText.ScrolledText(master) # scrollText for client logs scrolledtextLogs.grid(row=2) master.protocol("WM_DELETE_WINDOW", on_closing) master.mainloop() else: print("You don't have a first name?") # def client_program(): # # if len(connections)<3: # # print("Enter message to ne sent with destination ClientName") # # message = input(" -> ") # take input # # dest_client_name = message.split(':')[0] # # print("Destination Client Name is :", dest_client_name) # # # # # # while message.lower().strip() != 'bye': # # client_socket.send(message.encode()) # send message # # data = client_socket.recv(1024).decode() # receive response # # # # print('Received from server: ' + data) # show in terminal # # print('Waiting for input') # # client_socket.close() # close the connection # print("Continue") # # while True: # # data = client_socket.recv(1024).decode() # receive response # # if data: # # print('Received from server: ' + data) # show in terminal # # msg = data.split(':')[0] # # st.insert(INSERT, msg + '\n') # # else: # # print("Max Client Reached") # if __name__ == '__main__': print("Main") # client_program() # threading.Thread(target=check_new_message).start()
true
93f1788c3bd7096f2a2a5c379ba93ef918d3f59e
Python
StevenJW/some-cscircles-solutions
/chap7/string-shaving.py
UTF-8
38
2.90625
3
[]
no_license
x = input() print(x[1:int(len(x)-1)])
true
774828a11053e1b7f2e4bb10c63b38b2545ecbee
Python
ThomasZumsteg/project-euler
/problem_0006.py
UTF-8
275
3.78125
4
[]
no_license
#!/usr/bin/python def sum_square_difference(the_list): sum_square = 0 square_sum = 0 for i in the_list: square_sum += i**2 sum_square += i return sum_square**2 - square_sum if __name__ == "__main__": the_list = range(1,101) print(sum_square_difference(the_list))
true
dbd72848fb99fbd29a20f0321bbaad377eecad69
Python
kvantetore/PyProp
/examples/combined/hd+_vibration/constants.py
UTF-8
443
2.6875
3
[]
no_license
#Physical constants eV_to_au = 0.036764706 au_to_eV = 27.2114 inverse_cm_to_au = 4.5563276e-06 au_to_inverse_cm = 219475. volt_per_metre_to_au = 1.944689e-12 femtosec_to_au = 41.36338 def ReducedMass(M1, M2): return M1 * M2 / (M1 + M2) mass_proton_au = 1836.152666 mass_deuteron_au = 3670.482954 hdp_reduced_mass_au = ReducedMass(mass_proton_au, mass_deuteron_au) def wavelength_to_frequency(nm): return inverse_cm_to_au/(nm*1e-7)
true
be9820ffd3b67288510bc2e7cda21b0a545e490a
Python
ptasior/tal
/tools/dataGenerator/bin2cpp.py
UTF-8
1,478
2.5625
3
[]
no_license
#!/usr/bin/env python3 import binascii import sys, os from string import Template templateHederStart = Template('''// File auto generated #pragma once namespace EmbeddedData { extern const unsigned char $varName[]; extern const uint32_t ${varName}_size; } ''') templateStart = Template('''// File auto generated #include <cstdint> #include "$outFileName.h" namespace EmbeddedData { const unsigned char $varName[] = { ''') templateStop = Template(''' }; const uint32_t ${varName}_size = sizeof($varName)/sizeof(char); } ''') inFileName = None outFileName = None try: inFileName = sys.argv[1] outFileName = sys.argv[2] varName = sys.argv[3] except: pass if not inFileName or not outFileName or not varName: print("Usage: "+sys.argv[0]+"[binary file to convert] [output file name] [variable name]") sys.exit(-1) ifile = open(inFileName, 'rb') ofile = open(outFileName+'.cpp', 'wb') outFileBaseName = os.path.basename(outFileName) ofile.write(templateStart.substitute(varName=varName, outFileName=outFileBaseName).encode('ascii')) idx = 0 for c in ifile.read(): ofile.write((hex(c)+', ').encode('ascii')) idx = idx + 1 if idx == 20: ofile.write(('\n').encode('ascii')) idx = 0 ofile.write(templateStop.substitute(varName=varName).encode('ascii')) ifile.close() ofile.close() ohdrfile = open(outFileName+'.h', 'wb') ohdrfile.write(templateHederStart.substitute(varName=varName).encode('ascii')) ohdrfile.close()
true
0af28267cb872a902a05ea1e00ae8103c1a46287
Python
mleitejunior/urionlinejudge
/python/iniciante/uri1014.py
UTF-8
83
3.453125
3
[]
no_license
x = input() y = input() km_l = int(x)/float(y) print ("{:.3f} km/l".format(km_l))
true
a006796ed19d0a1700de16cecf638e648efc9298
Python
DanielFabian/DataStructuresAndAlgorithms
/Python/main.py
UTF-8
168
3.671875
4
[ "Apache-2.0" ]
permissive
__author__ = 'Daniel' print("Hello World") def sum_of_n(n): result = 0 for i in range(1, n + 1): result += i return result print(sum_of_n(10))
true
77d998470835397b6bc14a70f72f987240fecccc
Python
VivekPandey09032002/coding_setup
/eyantra/countChar.py
UTF-8
388
3.53125
4
[]
no_license
#count character if __name__ == '__main__': t=int(input()) while t>0: s=input() l=list(s.split(" ")) print(l) for i in range(0,len(l)): if i==0: print(len(l[i])-1,end=",") elif i==len(l)-1: print(len(l[i]),end="\n") else: print(len(l[i]),end=",") t=t-1
true
2cf139eea372d3ada917619626da83191c11dd99
Python
4rth4S/qradar4py
/qradar4py/endpoints/api_endpoint.py
UTF-8
2,751
3.09375
3
[ "MIT" ]
permissive
import requests class QRadarAPIEndpoint: """" The parent class for a QRadar API endpoints providing a constructor and several classmethods. """ def __init__(self, baseurl, header, verify): self._baseurl = baseurl self._header = header self._verify = verify def get_header(self): """ Return the header to use in API calls. :return: The header defined while constructing the class. """ return self._header def _call(self, method, url, response_type='json', **kwargs): """ Wrapper around the requests request method. :param method: The HTTP method to use. :param url: The url to query. :param kwargs: The arguments to pass to requests. :return: The status code and the response in JSON. """ header = self._header.copy() header.update(kwargs.pop('headers', {})) header.update(kwargs.pop('mime_type', {})) if response_type == 'json': response = requests.request(method, url, headers=header, verify=self._verify, **kwargs) return response.status_code, response.json() header.update({'Accept': response_type}) response = requests.request(method, url, headers=header, verify=self._verify, **kwargs) return response.status_code, response.text def header_vars(*valid_header_fields): """ Decorator maker to assign variables to the header field. :param valid_header_fields: The variables to move from **kwargs to header. :return: A decorator that checks for the passed variables and moves them to the header var. """ def decorator(func): def wrapped(self, *args, **all_args): header = all_args.pop('headers', {}) valid_header = {key: all_args[key] for key in all_args if key in valid_header_fields} header.update(valid_header) return func(self, *args, headers=header, **all_args) return wrapped return decorator def request_vars(*valid_param_fields): """ Decorator maker to assign variables to the params field. :param valid_param_fields: The variables to move from **kwargs to params. :return: A decorator that checks for the passed variables and moves them to the params var. """ def decorator(func): def wrapped(self, *args, **all_args): params = all_args.pop('params', {}) valid_params = {key: all_args[key] for key in all_args if key in valid_param_fields} params.update(valid_params) return func(self, *args, params=params, **all_args) return wrapped return decorator
true
9717f39fcc1f52c07f5e13bb0af65ace751c45a2
Python
kekemuyu/linewatch
/ports/esp32/extracttar.py
UTF-8
542
2.515625
3
[ "MIT" ]
permissive
import sys import os import shutil import utarfile import time def run(src,dest_dir): t = utarfile.TarFile(src) prefix=dest_dir for i in t: i.name=i.name.rstrip('/') print(i,i.name) i.name=prefix+i.name print(i.name) if i.type == utarfile.DIRTYPE: try: os.mkdir(i.name) except OSError as e: if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR: raise e else: f = t.extractfile(i) print(i.name) shutil.copyfileobj(f, open(i.name, "wb+"))
true
156fcbdf724ca90aa0a3ca27ca58fa90f60bded5
Python
lizhuoxuan/TensorFlow
/TensorFlow-Course/第一部分:TensorFlow深度学习的第一课 【季老师】/第三章:卷积介绍 【季老师】/cnn_how.py
UTF-8
1,920
2.875
3
[]
no_license
import cv2 import numpy as np from scipy import misc import matplotlib.pyplot as plt i = misc.ascent() plt.grid(False) plt.gray() plt.axis('off') plt.imshow(i) plt.show() i_transformed = np.copy(i) size_x = i_transformed.shape[0] size_y = i_transformed.shape[1] print(i_transformed.shape) my_filter = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]] weight = 1 for x in range(1, size_x - 1): for y in range(1, size_y - 1): convolution = 0.0 convolution = convolution + (i[x - 1, y - 1] * my_filter[0][0]) convolution = convolution + (i[x, y - 1] * my_filter[0][1]) convolution = convolution + (i[x + 1, y - 1] * my_filter[0][2]) convolution = convolution + (i[x - 1, y] * my_filter[1][0]) convolution = convolution + (i[x, y] * my_filter[1][1]) convolution = convolution + (i[x + 1, y] * my_filter[1][2]) convolution = convolution + (i[x - 1, y + 1] * my_filter[2][0]) convolution = convolution + (i[x, y + 1] * my_filter[2][1]) convolution = convolution + (i[x + 1, y + 1] * my_filter[2][2]) convolution = convolution * weight if convolution < 0: convolution = 0 if convolution > 255: convolution = 255 i_transformed[x, y] = convolution plt.gray() plt.grid(False) plt.imshow(i_transformed) # plt.axis('off') plt.show() new_x = int(size_x / 2) new_y = int(size_y / 2) newImage = np.zeros((new_x, new_y)) for x in range(0, size_x, 2): for y in range(0, size_y, 2): pixels = [] pixels.append(i_transformed[x, y]) pixels.append(i_transformed[x + 1, y]) pixels.append(i_transformed[x, y + 1]) pixels.append(i_transformed[x + 1, y + 1]) newImage[int(x / 2), int(y / 2)] = max(pixels) # Plot the image. Note the size of the axes -- now 256 pixels instead of 512 plt.gray() plt.grid(False) plt.imshow(newImage) # plt.axis('off') plt.show()
true
0c655157825ce06ee0a0f9b396bc108364d0043f
Python
Praneeth33/Hindi-Medium
/Scripts/audiosplit.py
UTF-8
679
2.625
3
[]
no_license
from pydub import AudioSegment import os import wave import contextlib from math import ceil def audiosplit(): fname = './audio.wav' if not os.path.exists('./Splits/'): os.mkdir('Splits') with contextlib.closing(wave.open(fname,'r')) as f: frames = f.getnframes() rate = f.getframerate() duration = frames / float(rate) duration *= 1000 duration = int(ceil(duration)) print(duration) t1 = 0 #Works in milliseconds t2 = 5000 newAudio = AudioSegment.from_wav("audio.wav") i = 1 while(1): if(t1>duration): break newAudio2 = newAudio[t1:t2] newAudio2.export('./Splits/'+str(i)+'.wav', format="wav") t1 += 5000 t2 += 5000 i+=1
true
21064b4048cf6e3dc2eea0ef7e1b14801f60dfbf
Python
u1i/azure-appservice-sample-api-app
/routes.py
UTF-8
455
2.53125
3
[ "MIT" ]
permissive
""" Routes and views for the bottle application. """ from bottle import route, view, response from datetime import datetime from random import randint @route('/') @route('/home') @view('index') def home(): """Renders the home page.""" return dict( year=datetime.now().year ) @route('/api-request') def returnarray(): rv = [{ "id": 1, "random": randint(1000,9999)}, { "id": 2, "random": randint(1000,9999) }] return dict(data=rv)
true
f6024c539d30e1e9aa309e699950c4f0a1a09385
Python
shen-huang/selfteaching-python-camp
/19100402/cjh20040088/d10/mymodule/stats_word.py
UTF-8
644
3.1875
3
[]
no_license
import jieba import collections import re def stats_text_en(txt,count): if type(txt)==str: txt=re.sub('[^A-Za-z]','',txt) txt=txt.lower() txt=txt.split() print(collections.Counter(txt).most_common(count)) else: raise ValueError def stats_text_cn(txt,count): if type(txt)==str: txt=re.sub('[^\u4e00-\u9fa5]','',txt) txt=txt.strip() txt=[x for x in jieba.cut_for_search(txt) if len(x)>=2] print(collections.Counter(txt).most_common(count)) else: raise ValueError def stats_text(txt,count): stats_text_en(txt,count) stats_text_cn(txt,count)
true
bb3ea3282093ea447cd85b04d9e7c19d28b40456
Python
KinoriSR/Deep-Learning
/Speech_to_Text/models.py
UTF-8
21,282
2.609375
3
[]
no_license
import torch import numpy as np import torch.nn as nn import torch.nn.utils as utils from torch.nn.functional import softmax, pad, gumbel_softmax # log_softmax from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence, pad_sequence from util import plot_attn_flow, plot_grad_flow from torch.utils.data import DataLoader from dataloader import load_data, collate_train, collate_test, transform_letter_to_index, Speech2TextDataset DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu' # LockedDropout module from torchnlp docs class LockedDropout(nn.Module): """ LockedDropout applies the same dropout mask to every time step. **Thank you** to Sales Force for their initial implementation of :class:`WeightDrop`. Here is their `License <https://github.com/salesforce/awd-lstm-lm/blob/master/LICENSE>`__. Args: p (float): Probability of an element in the dropout mask to be zeroed. """ def __init__(self, p=0.5): self.p = p super().__init__() def forward(self, x): """ Args: x (:class:`torch.FloatTensor` [sequence length, batch size, rnn hidden size]): Input to apply dropout too. """ if not self.training or not self.p: return x x = x.clone() mask = x.new_empty(1, x.size(1), x.size(2), requires_grad=False).bernoulli_(1 - self.p) mask = mask.div_(1 - self.p) mask = mask.expand_as(x) return x * mask def __repr__(self): return self.__class__.__name__ + '(' \ + 'p=' + str(self.p) + ')' class Attention(nn.Module): ''' Attention is calculated using key, value and query from Encoder and decoder. Below are the set of operations you need to perform for computing attention: energy = bmm(key, query) attention = softmax(energy) context = bmm(attention, value) ''' def __init__(self): super(Attention, self).__init__() def forward(self, query, key, value, lens): ''' :param query :(batch_size, hidden_size) Query is the output of LSTMCell from Decoder :param keys: (batch_size, max_len, encoder_size) Key Projection from Encoder :param values: (batch_size, max_len, encoder_size) Value Projection from Encoder :return context: (batch_size, encoder_size) Attended Context :return attention_mask: (batch_size, max_len) Attention mask that can be plotted ''' energy = torch.bmm(key, query.unsqueeze(2).to(DEVICE)) # mask using lens when getting softmax create mask... found a faster way than looping somewhere online mask = (torch.arange(energy.shape[1])[None,:] >= lens[:,None]).to(DEVICE) # < for positive mask mask=mask.unsqueeze(2) energy.masked_fill_(mask, -1e10) attention = energy.softmax(1)#.softmax(-1) # last dim or dim=1 context = torch.bmm(attention.permute(0,2,1), value) return context.squeeze(1), attention.squeeze(2) ''' For Pyramid LSTM: ASSUME `data` is a packed sequence ''' def scale_down_prep(data, lens=None): if type(data).__name__ == "PackedSequence": data, lens = pad_packed_sequence(data) data = data.permute(1,2,0) else: data = data.permute(0,2,1) if data.shape[2]%2==1: data = pad(data, (0,1,0,0,0,0)) # because of padding, time should be divisible by 2 # the lens should be able to be rounded which for the odd case would round up because the last one was concatenated with padding return data, torch.round(torch.true_divide(lens,2)) # NOTE: TA downsizing a short sequence can cause lens to become short which may cause attention softmax to give NaNs this should be 1 at the minimum though... # Conv Layers class pBLSTM_conv(nn.Module): ''' Pyramidal BiLSTM The length of utterance (speech input) can be hundereds to thousands of frames long. The Paper reports that a direct LSTM implementation as Encoder resulted in slow convergence, and inferior results even after extensive training. The major reason is inability of AttendAndSpell operation to extract relevant information from a large number of input steps. ''' def __init__(self, input_dim, hidden_dim): super(pBLSTM_conv, self).__init__() # self.conv1d self.downsample = nn.AvgPool1d(kernel_size=2, stride=2) self.blstm = nn.LSTM(input_size=input_dim, hidden_size=hidden_dim, num_layers=1, bidirectional=True) def forward(self, x, lens): ''' :param x :(N, T) input to the pBLSTM :return output: (N, T, H) encoded sequence from pyramidal Bi-LSTM ''' x, lens = scale_down_prep(x, lens) x = self.downsample(x) # B, Ch, T # enforce_sorted=True right now - originally False, batch_first=True - originally False x = pack_padded_sequence(x.permute(0,2,1), lengths=lens, batch_first=True, enforce_sorted=True) outputs, (hidden, context) = self.blstm(x) return outputs, hidden, context, lens # Concatenate class pBLSTM(nn.Module): ''' Pyramidal BiLSTM The length of utterance (speech input) can be hundereds to thousands of frames long. The Paper reports that a direct LSTM implementation as Encoder resulted in slow convergence, and inferior results even after extensive training. The major reason is inability of AttendAndSpell operation to extract relevant information from a large number of input steps. ''' def __init__(self, input_dim, hidden_dim): super(pBLSTM, self).__init__() self.blstm = nn.LSTM(input_size=input_dim, hidden_size=hidden_dim, num_layers=1, bidirectional=True) def forward(self, x, lens, isTrain=True): ''' :param x :(N, T) input to the pBLSTM :return output: (N, T, H) encoded sequence from pyramidal Bi-LSTM ''' if type(x).__name__ == "PackedSequence": x, lens = pad_packed_sequence(x) x = x.permute(1,0,2) # (T, B, H) => (B, T, H) if x.shape[1]%2==1: x = pad(x, (0,0,0,1,0,0)) # (B, T+1, H) x = x.reshape((x.shape[0], x.shape[1]//2, x.shape[2]*2)) # (B, T/2, H*2) lens = torch.ceil(torch.true_divide(lens,2)) # round -> ceil # enforce_sorted=True right now - originally False, batch_first=True - originally False if isTrain: x = pack_padded_sequence(x, lengths=lens, batch_first=True, enforce_sorted=True) else: x = pack_padded_sequence(x, lengths=lens, batch_first=True, enforce_sorted=False) outputs, (hidden, context) = self.blstm(x) return outputs, hidden, context, lens class Encoder(nn.Module): ''' Encoder takes the utterances as inputs and returns the key and value. Key and value are nothing but simple projections of the output from pBLSTM network. ''' def __init__(self, input_dim, hidden_dim, value_size=128,key_size=128, isAttended=False): super(Encoder, self).__init__() # self.input_dropout = LockedDropout(0.15) # self.conv1d = nn.Conv1d(input_dim, hidden_dim, kernel_size=5, stride=1, padding=2) self.lstm = nn.LSTM(input_size=input_dim, hidden_size=hidden_dim, num_layers=1, bidirectional=True) # self.lstm = nn.LSTM(input_size=input_dim, hidden_size=hidden_dim, num_layers=1, bidirectional=True) self.plstm1 = pBLSTM(hidden_dim*4, hidden_dim) # (hidden_dim*4, hidden_dim) if using LSTM # self.batchnorm1 = nn.BatchNorm1d(hidden_dim*2) self.dropout1 = LockedDropout(0.2) self.plstm2 = pBLSTM(hidden_dim*4, hidden_dim) # self.batchnorm2 = nn.BatchNorm1d(hidden_dim*2) self.dropout2 = LockedDropout(0.2) self.plstm3 = pBLSTM(hidden_dim*4, hidden_dim) self.isAttended = isAttended if self.isAttended: self.key_network = nn.Linear(hidden_dim*2, value_size) self.value_network = nn.Linear(hidden_dim*2, key_size) else: self.output = nn.Linear(hidden_dim*2, key_size) def forward(self, x, lens, isTrain=True, input_dropout=0): # rnn_inp = utils.rnn.pack_padded_sequence(x, lengths=lens, batch_first=False, enforce_sorted=True) # outputs = self.lstm(rnn_inp)[0] # if input_dropout: # x = x.permute(1,0,2) # self.input_dropout.p = input_dropout # x = self.input_dropout(x) # x = x.permute(1,0,2) # x = x.permute(0,2,1) # x = self.conv1d(x) # x = x.permute(0,2,1) if isTrain: x = pack_padded_sequence(x, lengths=lens, batch_first=True, enforce_sorted=True) else: x = pack_padded_sequence(x, lengths=lens, batch_first=True, enforce_sorted=False) x = self.lstm(x)[0] # print("ENCODER START") outputs, hidden, context, lens = self.plstm1(x, lens, isTrain=isTrain) # outputs, _ = pad_packed_sequence(outputs) # outputs = outputs.permute(1,2,0) # (T,B,H) -> (B,H,T) # outputs = self.batchnorm1(outputs) # (B,H,T) # outputs = outputs.permute(2,0,1) # (B,H,T) -> (T,B,H) # self.dropout1.p = input_dropout # outputs = self.dropout1(outputs) # (T,B,H) # outputs = outputs.permute(1,0,2) # (T,B,H) -> (B,T,H) # print("(B,T,H)", outputs.shape) outputs, hidden, context, lens = self.plstm2(outputs, lens, isTrain=isTrain) # outputs, _ = pad_packed_sequence(outputs) # outputs = outputs.permute(1,2,0) # (T,B,H) -> (B,H,T) # outputs = self.batchnorm2(outputs) # (B,H,T) # outputs = outputs.permute(2,0,1) # (B,H,T) -> (T,B,H) # self.dropout2.p = input_dropout # outputs = self.dropout2(outputs) # (T,B,H) # outputs = outputs.permute(1,0,2) # (T,B,H) -> (B,T,H) outputs, hidden, context, lens = self.plstm3(outputs, lens, isTrain=isTrain) outputs, lens = pad_packed_sequence(outputs) outputs = outputs.permute(1,0,2) # print("Encoder outputs: {}, hidden: {}, context: {}".format(outputs.shape, hidden.shape, context.shape)) #------------------- if self.isAttended: keys = self.key_network(outputs) value = self.value_network(outputs) return keys, value, lens, outputs else: outputs = self.output(outputs) return outputs, lens class Decoder(nn.Module): ''' As mentioned in a previous recitation, each forward call of decoder deals with just one time step, thus we use LSTMCell instead of LSLTM here. The output from the second LSTMCell can be used as query here for attention module. In place of value that we get from the attention, this can be replace by context we get from the attention. Methods like Gumble noise and teacher forcing can also be incorporated for improving the performance. ''' def __init__(self, vocab_size, value_size=128, key_size=128, isAttended=False): super(Decoder, self).__init__() self.hidden_dim = key_size + value_size self.key_size = key_size # print(key_size, value_size, self.hidden_dim) self.embedding = nn.Embedding(vocab_size, self.hidden_dim) #, padding_idx=0) self.lstm1 = nn.LSTMCell(input_size=self.hidden_dim + value_size, hidden_size=key_size) self.lstm2 = nn.LSTMCell(input_size=key_size, hidden_size=key_size) self.isAttended = isAttended if (isAttended == True): self.attention = Attention() self.character_prob = nn.Linear(key_size + value_size, vocab_size) # , bias=False) # Weight tying - acts as regularization self.character_prob.weight = self.embedding.weight def forward(self, values, key, teacher_force_rate=1., lens=None, text=None, isTrain=True, validate=False, plot_attn=False): ''' :param key :(N, T, key_size) Output of the Encoder Key projection layer :param values: (N, T, value_size) Output of the Encoder Value projection layer :param text: (N, text_len) Batch input of text with text_length :param isTrain: Train or eval mode :return predictions: Returns the character prediction probability ''' # print("key", key) # print("values",values) batch_size = values.shape[0] # [1] if isTrain: embeddings = self.embedding(text) if self.isAttended: if (isTrain == True): max_len = text.shape[1] elif validate: max_len = text.shape[1] else: max_len = 600 else: max_len = values.shape[1] predictions = [] hidden_states = [None, None] prediction = ((torch.ones(batch_size,)*33).long()).to(DEVICE) # TODO: TA change from torch.zeros # [a b c <eos>] -> <sos>->a, a->b if plot_attn: attn = [] cntxt = [] # print("Decoder text:", text.shape) # print("Decoder max_len:", max_len) #---------------------- if self.isAttended: initial_query = torch.zeros((batch_size, self.key_size)) # print(initial_query.shape, self.key_size) # initial_query = torch.ones((batch_size, self.hidden_dim)) # TODO: this may be better # print("initial_query", initial_query) # print("lens",lens) context, attention = self.attention(initial_query, key, values, lens) # context = values[:,-1,:] # TODO may try this # print("CONTEXT",context) for i in range(max_len): # * Implement Gumbel noise and teacher forcing techniques # TODO TA edit word "Gumble" # * When attention is True, replace values[i,:,:] with the context you get from attention. # * If you haven't implemented attention yet, then you may want to check the index and break # out of the loop so you do not get index out of range errors. if i==0: char_embed = self.embedding(prediction) # first one will be 33 = <sos> else: if (isTrain): # Teacher forcing teacher_force = np.random.binomial(1, teacher_force_rate) # if i == 0: # char_embed = self.embedding(sos) # else: # if use above then embeddings[:,i-1,:] if teacher_force: char_embed = embeddings[:,i-1,:] # TA check student's character inputs else: # NOTE can random sample here # TODO should I random sample here? so softmax? or softmax output? char_embed = self.embedding(prediction.argmax(dim=-1)) else: # if i==0: # char_embed = self.embedding(prediction) # for the tensor of 33s for first time in iteration # else: char_embed = self.embedding(prediction.argmax(dim=-1)) # print(char_embed.shape, max_len, values.shape, outputs.shape) if self.isAttended: inp = torch.cat([char_embed, context], dim=1) # values[i,:,:] else: inp = torch.cat([char_embed, values[:,i,:]], dim=1) # values[i,:,:] hidden_states[0] = self.lstm1(inp, hidden_states[0]) inp_2 = hidden_states[0][0] hidden_states[1] = self.lstm2(inp_2, hidden_states[1]) ### Compute attention from the output of the second LSTM Cell ### output = hidden_states[1][0] if self.isAttended: context, attention = self.attention(output, key, values, lens) # print(attention[0:1,:]) C = context else: C = values[:,i,:] # values[i,:,:] # print(attention_mask[0:1,:].shape) # assert(False)#------------------------ # attention plotting if plot_attn: attn.append(attention[0:1,:]) cntxt.append(context[0:1,:]) # print("Kinori", attention_mask[0:1,:,0].shape) prediction = self.character_prob(torch.cat([output, C], dim=1)) # prediction = gumbel_softmax(prediction) # prediction = prediction.softmax(2) predictions.append(prediction.unsqueeze(1)) if plot_attn: return torch.cat(predictions, dim=1), torch.cat(attn, dim = 0), torch.cat(cntxt, dim = 0) return torch.cat(predictions, dim=1) class Seq2Seq(nn.Module): ''' We train an end-to-end sequence to sequence model comprising of Encoder and Decoder. This is simply a wrapper "model" for your encoder and decoder. ''' def __init__(self, input_dim, vocab_size, hidden_dim, value_size=128, key_size=128, isAttended=True): super(Seq2Seq, self).__init__() self.isAttended = isAttended self.encoder = Encoder(input_dim, hidden_dim, value_size=value_size, key_size=key_size, isAttended=self.isAttended) self.decoder = Decoder(vocab_size, value_size=value_size, key_size=key_size, isAttended=self.isAttended) def forward(self, speech_input, speech_len, text_input=None, isTrain=True, teacher_force_rate=1., validate=False, plot_attn=False, input_dropout=0): if self.isAttended: key, value, lens, outputs = self.encoder(speech_input, speech_len, isTrain=isTrain, input_dropout=input_dropout) else: value, lens = self.encoder(speech_input, speech_len, isTrain=isTrain, dropout=dropout) key = None if (isTrain == True): predictions = self.decoder(value, key, teacher_force_rate, lens, text_input, plot_attn=plot_attn) elif validate: predictions = self.decoder(value, key, lens=lens, text=text_input, isTrain=False, validate=validate, plot_attn=plot_attn) else: predictions = self.decoder(value, key, lens=lens, text=None, isTrain=False, plot_attn=plot_attn) return predictions if __name__ == "__main__": from dataloader import collate_test, collate_train LETTER_LIST = ['<pad>', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', \ 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '-', "'", '.', '_', '+', ' ','<sos>','<eos>'] batch_size = 32 # print("Encoder-Decoder Attended Test:") # x=[] # for i in range(batch_size): # x.append(torch.rand((torch.randint(100, 200, (1,)),40))) # B,100,Ch # x, x_lens = collate_test(x) # print(x.shape, x_lens) # encoder = Encoder(input_dim=40, hidden_dim=128, isAttended=True) # , value_size=128,key_size=128) # key, value, lens, outputs = encoder.forward(x, x_lens) # print(key.shape, value.shape, outputs.shape) # print(lens) # decoder = Decoder(len(LETTER_LIST), hidden_dim=128, isAttended=True).to(DEVICE) # predictions, attn = decoder(value.to(DEVICE), key.to(DEVICE), lens=lens, isTrain=False, plot_attn=True) # print(predictions.shape, attn.shape) # plot_attn_flow(attn.detach().to('cpu'), './testimage.png') # print("Encoder-Decoder Not Attended Test:") # encoder = Encoder(input_dim=40, hidden_dim=128, isAttended=False) # , value_size=128,key_size=128) # outputs, lens = encoder.forward(x, x_lens) # print(outputs.shape) # print(lens) # decoder = Decoder(len(LETTER_LIST), hidden_dim=128, isAttended=False).to(DEVICE) # # must pass None for key when not attended # predictions = decoder(outputs.to(DEVICE), None, lens=lens, isTrain=False) # print(predictions.shape) print("Seq2Seq Test:") transcript_valid = np.load('./dev_transcripts.npy', allow_pickle=True,encoding='bytes') character_text_valid = transform_letter_to_index(transcript_valid, LETTER_LIST) speech_valid = np.load('dev.npy', allow_pickle=True, encoding='bytes') batch_size = 16 valid_dataset = Speech2TextDataset(speech_valid, text=character_text_valid) result = collate_train([valid_dataset[0],valid_dataset[1]]) valid_loader = DataLoader(valid_dataset, batch_size=batch_size, shuffle=True, collate_fn=collate_train) # loop through loader for i, (x,y, x_len, y_len) in enumerate(valid_loader): print("Input shapes:", x.shape, x_len.shape, "\t", y.shape, y_len.shape) print() model = Seq2Seq(input_dim=40, vocab_size=len(LETTER_LIST), hidden_dim=128).to(DEVICE) out, attn, context = model.forward(x.to(DEVICE), x_len, text_input=y.to(DEVICE), plot_attn=True, input_dropout=0.2) plot_attn_flow(attn.detach().to('cpu'), './testimage.png') print() print(out.shape) # print("\t\t", i, x.shape, x_len.shape, y.shape, y_len.shape) if i==0: break # x=[] # for i in range(batch_size): # l = torch.randint(100, 200, (1,)) # x.append((torch.rand((l,40)), torch.randint(34, (l,)))) # B,100,Ch # x, y, x_lens, y_lens = collate_train(x)
true
474bae745b0c49d7ba38f7219978cef4f7a48eec
Python
jangocheng/Beijing-Subway-System
/get_timecost.py
UTF-8
2,757
2.890625
3
[]
no_license
# -*- coding: utf-8 -*- # @Author: MarkJiYuan # @Date: 2019-05-28 21:13:47 # @Last Modified by: MarkJiYuan # @email: zhengjiy16@163.com # @Last Modified time: 2019-05-29 14:06:30 # @Abstract: import json def get_time_cost(f): for id in range(0, 20): line_name = response.xpath('//div[@id="sub' + str(id) + '"]/div/table/thead/tr[1]/td/text()').extract()[0] f.write('&' + line_name + '\n') for i in range(0, 5): xpath_route = '//div[@id="sub' + str(id) + '"]/div/table/tbody/tr/td[' + str(i) + ']/text()' l = response.xpath(xpath_route).extract() strip = lambda i:i.strip() l = list(map(strip, l)) f.write(json.dumps(l)) f.write('\n') def time_minus(time1:str, time2:str) -> int: time1 = time1.split(':') time2 = time2.split(':') hour1 = int(time1[0]) hour2 = int(time2[0]) minute1 = int(time1[1]) minute2 = int(time2[1]) dif = (hour1 * 60 + minute1) - (hour2 * 60 + minute2) dif = abs(dif) return dif def calculate_time_cost(l:list) -> list: timecost = [] for i in range(len(l)-1): dif = time_minus(l[i], l[i+1]) timecost.append(dif) return timecost def timecost_exception(dic): dic['2号线'][0] = 2 dic['2号线'][9] = 2 dic['4号线/大兴线'][10] = 2 dic['4号线/大兴线'][9] = 3 dic['4号线/大兴线'].reverse() dic['6号线'][5] = 3 dic['6号线'][24] = 2 dic['8号线(北段)'][2] = 3 dic['10号线'][25] = 2 dic['10号线'][41] = 3 dic['13号线'][8] = 4 dic['15号线'][7] = 3 dic['昌平线'][9] = 2 if __name__=='__main__': line_map = {} timecost = {} '读入线站表,顺序与首末班对应' with open('subway_map.txt', 'r') as f: for line in f.readlines(): if line.strip() != '': if line[0] == '&': line_name = line.strip()[1:] line_map[line_name] = [] else: station_name = line.strip() line_map[line_name].append(station_name) '读入首班车时间表' with open('timecost.txt', 'r') as f: for line in f.readlines(): if line[0] == '&': line_name = line.strip()[1:] else: timecost[line_name] = json.loads(line.strip()) '根据首班车时间表计算站间时长' for line_name in timecost: time_list = timecost[line_name] a = calculate_time_cost(time_list) timecost[line_name] = a '处理异常' timecost_exception(timecost) '将时间表与线站表相结合,生成乘车用时文件,机场线特殊情况直接手动处理了' with open('timecost_list.txt', 'w') as f: for line_name in line_map: stations = line_map[line_name] for i in range(len(stations)-1): start = stations[i] end = stations[i+1] time = timecost[line_name][i] f.write(start + ' ' + end + ' ' + str(time) + '\n') f.write(end + ' ' + start + ' ' + str(time) + '\n') print('done!')
true
0bee479c13183ad8686e2cd8ebb90c69ed09e47e
Python
jmcharter/advent_of_code_2020
/day_04/day_04_part_one.py
UTF-8
372
2.671875
3
[ "MIT" ]
permissive
required = [ 'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid' ] with open("day_04/day_04.txt", "r") as f: data = f.read().strip().split('\n\n') count = 0 for entry in data: valid = True for item in required: if not item in entry: valid = False if valid == True: count+=1 print(count) # Answer = 222
true
b9717ba3f5a16a771cb4ac77d385f64f45d86eef
Python
jschmacht/xtandem_result_analyzer
/SearchAccessions.py
UTF-8
3,771
2.609375
3
[]
no_license
import gzip import re import logging from pathlib import Path import multiprocessing as mp class SearchAccessions: def __init__(self, path_to_db, db): """ :param path_to_xml: path to the protein database :param db: database format, 'ncbi' or 'uniprot' ) """ self.path_to_file = Path(path_to_db) self.db = db self.acc_dict = {} self.accs = [] # ncbi peptide database def read_ncbi_mp(self, chunk): """ :param chunk: tuple of numbers, chunk[0]=entry point in database file, chunk[1]= size to be readed """ f = open(str(self.path_to_file), "rb") f.seek(chunk[0]) part_dict={} for line in f.read(chunk[1]).decode("utf-8").splitlines(): fields = [item.strip('\t') for item in line.split('\t')] if fields[0] in accessionIDs: part_dict[fields[0]]= fields return part_dict def read_nr_mp(self, chunk): """ :param chunk: tuple of numbers, chunk[0]=entry point in database file, chunk[1]= size to be readed """ f = open(str(self.path_to_file), "rb") f.seek(chunk[0]) part_dict={} for line in f.read(chunk[1]).decode("utf-8").splitlines(): if line.startswith('>'): if '\x01' in line: line = line[1:] accs = [item.split(' ')[0] for item in line.split('\x01')] part_dict[accs[0]] = accs return part_dict def read_in_chunks(self, size=1024 * 1024): f = open(str(self.path_to_file), "rb") f.readline() while True: start = f.tell() f.seek(size + start) s = f.readline() end = (f.tell() - start) f.seek(start + end) yield start, end if not s: f.close() break # divide database file in chunks for parallel processing def divide_into_chunks(self): chunks = [] print('Start dividing database file in chunks.') for chunk in self.read_in_chunks(): chunks.append(chunk) print('Database divided into %d chunks.' % len(chunks)) return chunks # read database and store position information in list (value) to taxon_ID # if database is without taxon IDs, before matching scientifc name to ID def read_database(self, accessions, threads=None): """ :param accessions: set of accessionIDs matching searched taxon IDs (for ncbi db) """ if not threads: threads = mp.cpu_count() global accessionIDs accessionIDs = set() for i in accessions: accessionIDs.update(set(i)) print('Set accessions length %d' % len(accessionIDs)) chunks = self.divide_into_chunks() pool = mp.Pool(threads) # here multiprocessing starts i, j = 0, 0 ten = int(len(chunks) / 10) if self.db == 'ncbi': for part_dict in pool.imap_unordered(self.read_ncbi_mp, chunks): if i == ten: j += 1 print('%d0%% readed.' % j) i = -1 self.acc_dict.update(part_dict) i += 1 if self.db == 'uniprot': for part_dict in pool.imap_unordered(self.read_nr_mp, chunks): if i == ten: j += 1 print('%d0%% readed.' % j) i = 0 self.acc_dict.update(part_dict) i += 1 pool.close() pool.join()
true
bf13f566d2836e8eb7c5fcafc225bf2c994026d1
Python
marc2982/pypark
/pypark/peep.py
UTF-8
3,279
3.171875
3
[]
no_license
import random from constants import BLUE, TILE_SIZE, RED, PATH_COLOUR from vector import Vector2d import pygame class Peep(object): def __init__(self, position): # position is world coordinates self.position = position self.destination_tile = None self.path = None self.speed = 1 self.acting_at_destination = True self.acting_ticks = 0 @property def current_tile(self): return self.position / TILE_SIZE def update(self, world): """Called every tick to update peep.""" if self.acting_at_destination: self.acting_ticks += 1 if self.acting_ticks == 60: # arbitrary waiting period self.acting_ticks = 0 self.acting_at_destination = False elif self.destination_tile: self._move_along_path() else: self.choose_new_destination(world) def _move_along_path(self): """Move along the current path to the destination.""" current_tile = self.current_tile # calculate once if current_tile != self.destination_tile and not self.path: raise Exception('no path to destination :(') next_tile = self.path[0] if current_tile == next_tile: # TODO: go to middle of tile only if destination coords aren't set tile_middle = next_tile * TILE_SIZE + TILE_SIZE/2 # TODO: won't work with speed != 1 cause of overshooting if self.position == tile_middle: if current_tile == self.destination_tile: self.destination_tile = None self.path = None self.acting_at_destination = True return # get new tile self.path.pop(0) normal_vector = None else: normal_vector = ( tile_middle - self.position).normalized().intify() else: normal_vector = next_tile - current_tile # move if necessary if normal_vector: self.position += normal_vector * self.speed def choose_new_destination(self, world): """Choose a new destination tile.""" if world.directory.shops: destination = random.choice(world.directory.shops) # TODO: Compute target tile to be the path that touches it. # Currently hardcoded tile directly below shop to be target tile # (because you can't walk on shop tile). self.destination_tile = destination.position + Vector2d(0, 1) # TODO: add destination coords self.path = world.pathfinder.compute( self.current_tile, self.destination_tile) # debug draw for tile in world.iter_tiles(): if tile.is_path: tile.colour = PATH_COLOUR for node in self.path: world[node.x][node.y].colour = RED def draw(self, camera, screen): if camera.rect.collidepoint(self.position.tuple): screen_pos = self.position - camera.position pygame.draw.circle( screen, BLUE, (screen_pos.x, screen_pos.y), 5, 0)
true
5ca76314319a578485d5deece45c472c3ad76a37
Python
SuzyQuant/randomWalk_v2
/randomWalk_plot.py
UTF-8
5,324
2.75
3
[ "MIT" ]
permissive
#!/usr/bin/env python import matplotlib import numpy as np from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt data = np.loadtxt('quantitiesVStime2.txt') time = data[:, 0] + 1 MSDth = time #<x^2> analytical ; ALSO THE SECOND COLUMN MSDnum = data[:, 1] #<x^2> numerical / computer simulated MSDerr = data[:, 3] #error bar of <x^2> Fsq1 = data[:, 4] #F_s(q1,x(t)) Fsq1num = data[:, 10] #F_s(q1,x(t)) analytical Fsq1err = data[:, 7] #error bar of F_s(q1,x(t)) Fsq2 = data[:, 5] #F_s(q2,x(t)) Fsq2num = data[:, 11] #F_s(q1,x(t)) analytical Fsq2err = data[:, 8] #error bar of F_s(q2,x(t)) Fsq3 = data[:, 6] #F_s(q3,x(t)) Fsq3num = data[:, 12] #F_s(q1,x(t)) analytical Fsq3err = data[:, 9] #error bar of F_s(q2,x(t)) with PdfPages('RESULTS20106.pdf') as pdf: # ======== 1 log-log <x^2> VS time ============== plt.xlim([1,500]) # plt.ylim([,1.9]) plt.title('log-log plot: <x^2> VS time') plt.xlabel(r'$t$', fontsize=15) plt.ylabel(r'$MSD(t)$', fontsize=10) plt.xscale('log') plt.yscale('log') plt.plot( time , MSDnum, 'r-*',label= r'Numeric', linewidth=1) plt.plot( time , MSDth, 'c-',label= r'Theory', linewidth=1) plt.legend(loc=4) #plt.show() pdf.savefig() plt.close() # ======== 2 log-log <x^2> with error bars VS time ============== plt.xlim([1,500]) # plt.ylim([,1.9]) plt.title('log-log plot w/ error bars: <x^2> VS time') plt.xlabel(r'$t$', fontsize=15) plt.ylabel(r'$MSD(t)$', fontsize=10) plt.xscale('log') plt.yscale('log') plt.errorbar(time , MSDnum, MSDerr, color='r', label= r'Numeric', linewidth=1) plt.plot( time , MSDth, 'c-',label= r'Theory', linewidth=1) plt.legend(loc=4) #plt.show() pdf.savefig() plt.close() # ======== 3 log-log Fsq1 with error bars VS time ============== plt.xlim([1,500]) #plt.ylim([10**(-7),1.9]) plt.title('log-log plot w/ error bars: Fsq1 VS time') plt.xlabel(r'$t$', fontsize=8) plt.ylabel(r'$log F_s(q1, t)$', fontsize=8) plt.xscale('log') plt.yscale('log') plt.errorbar(time , Fsq1, Fsq1err, color='r', label= r'Numeric', linewidth=1) plt.plot( time , Fsq1num, 'c-',label= r'Theory', linewidth=1) plt.tight_layout() plt.legend(loc=4) #plt.show() pdf.savefig() plt.close() # ======== 4 log-log Fsq2 with error bars VS time ============== plt.xlim([1,500]) plt.ylim([10**(-7),1.9]) plt.title('log-log plot w/ error bars: Fsq2 VS time') plt.xlabel(r'$t$', fontsize=15) plt.ylabel(r'$log F_s(q2, t)$', fontsize=10) plt.xscale('log') plt.yscale('log') plt.errorbar(time , Fsq2, Fsq2err, color='r', label= r'Numeric', linewidth=1) plt.plot( time , Fsq2num, 'c-',label= r'Theory', linewidth=1) plt.legend(loc=4) #plt.show() pdf.savefig() plt.close() # ======== 5 log-log Fsq3 with error bars VS time ============== plt.xlim([1,500]) #plt.ylim([10**(-7),1.9]) plt.title('log-log plot w/ error bars: Fsq3 VS time') plt.xlabel(r'$t$', fontsize=15) plt.ylabel(r'$log F_s(q3, t)$', fontsize=10) plt.xscale('log') plt.yscale('log') plt.errorbar(time , Fsq3, Fsq3err, color='r', label= r'Numeric', linewidth=1) plt.plot( time , Fsq3num, 'c-',label= r'Theory', linewidth=1) plt.tight_layout() plt.legend(loc=4) #plt.show() pdf.savefig() plt.close() # ======== **** NO LOG PLOTS **** ============== # ======== 6 <x^2> VS time ============== plt.xlim([1,500]) # plt.ylim([,1.9]) plt.title('<x^2> VS time') plt.xlabel(r'$t$', fontsize=15) plt.ylabel(r'$MSD(t)$', fontsize=10) plt.plot( time , MSDnum, 'r-*',label= r'Numeric', linewidth=1) plt.plot( time , MSDth, 'c-',label= r'Theory', linewidth=1) plt.legend(loc=4) #plt.show() pdf.savefig() plt.close() # ======== 7 <x^2> with error bars VS time ============== plt.xlim([1,500]) # plt.ylim([,1.9]) plt.title('w/ error bars: <x^2> VS time') plt.xlabel(r'$t$', fontsize=15) plt.ylabel(r'$MSD(t)$', fontsize=10) plt.errorbar(time , MSDnum, MSDerr, color='r', label= r'Numeric', linewidth=1) plt.plot( time , MSDth, 'c-',label= r'Theory', linewidth=1) plt.legend(loc=4) #plt.show() pdf.savefig() plt.close() # ======== 8 Fsq1 with error bars VS time ============== plt.xlim([1,500]) plt.ylim([-0.5,1.2]) plt.title('w/ error bars: Fsq1 VS time') plt.xlabel(r'$t$', fontsize=15) plt.ylabel(r'$F_s(q1, t)$', fontsize=10) plt.errorbar(time , Fsq1, Fsq1err, color='r', label= r'Numeric', linewidth=1) plt.plot( time , Fsq1num, 'c-',label= r'Theory', linewidth=1) plt.legend(loc=4) #plt.show() pdf.savefig() plt.close() # ======== 9 Fsq2 with error bars VS time ============== plt.xlim([1,500]) plt.ylim([-0.5,0.5]) plt.title('w/ error bars: Fsq2 VS time') plt.xlabel(r'$t$', fontsize=15) plt.ylabel(r'$F_s(q2, t)$', fontsize=10) plt.errorbar(time , Fsq2, Fsq2err, color='r', label= r'Numeric', linewidth=1) plt.plot( time , Fsq2num, 'c-',label= r'Theory', linewidth=1) plt.legend(loc=4) #plt.show() pdf.savefig() plt.close() # ======== 10 Fsq3 with error bars VS time ============== plt.xlim([1,500]) plt.ylim([-0.5,0.5]) plt.title('w/ error bars: Fsq3 VS time') plt.xlabel(r'$t$', fontsize=15) plt.ylabel(r'$F_s(q3, t)$', fontsize=10) plt.errorbar(time , Fsq3, Fsq3err, color='r', label= r'Numeric', linewidth=1) plt.plot( time , Fsq3num, 'c-',label= r'Theory', linewidth=1) plt.legend(loc=4) #plt.show() pdf.savefig() plt.close()
true
8b942aff7f794c912cc3a6212efa7c96e64632e8
Python
souviksamanta95/machine_learning_examples
/tf2.0/xor3d.py
UTF-8
658
2.90625
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def get_label(x, i1, i2, i3): # x = sequence if x[i1] < 0 and x[i2] < 0 and x[i3] < 0: return 1 if x[i1] < 0 and x[i2] > 0 and x[i3] > 0: return 1 if x[i1] > 0 and x[i2] < 0 and x[i3] > 0: return 1 if x[i1] > 0 and x[i2] > 0 and x[i3] < 0: return 1 return 0 N = 2000 X = np.random.random((N, 3))*2 - 1 Y = np.zeros(N) for i in range(N): x = X[i] y = get_label(x, 0, 1, 2) Y[i] = y fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(X[:,0], X[:,1], X[:,2], c=Y) plt.show()
true
209e802539c822c1d974de6f3021b761eab9efd9
Python
FrenCompany/TastelessKingdom
/static/maps/level1.py
UTF-8
2,041
2.625
3
[]
no_license
from settings.GUI import SCREEN_HEIGHT, SCREEN_WIDTH, CANNON_SIZE, COIN_SIZE from settings.Game import CHAR_SPEED block_width = 30 platform_width = 200 platform_height = 6 height_fourth = (SCREEN_HEIGHT - 2 * block_width) / 4 floor3 = height_fourth + block_width floor2 = height_fourth * 2 + block_width floor1 = height_fourth * 3 + block_width width_fourth = (SCREEN_WIDTH - 2 * block_width) / 4 col1 = width_fourth + block_width col2 = width_fourth * 2 + block_width col3 = width_fourth * 3 + block_width level1 = { "blocks": [ { "width": block_width, "height": SCREEN_HEIGHT, "x": 0, "y": 0 }, { "width": SCREEN_WIDTH, "height": block_width, "x": 0, "y": 0 }, { "width": block_width, "height": SCREEN_HEIGHT, "x": SCREEN_WIDTH - block_width, "y": 0 }, { "width": SCREEN_WIDTH, "height": block_width, "x": 0, "y": SCREEN_HEIGHT - block_width }, ], "platforms": [ { "width": platform_width, "height": platform_height, "x": col2 - platform_width / 2, "y": floor2 }, { "width": platform_width, "height": platform_height, "x": col1 - platform_width / 2, "y": floor1 }, { "width": platform_width, "height": platform_height, "x": col3 - platform_width / 2, "y": floor1 }, { "width": platform_width, "height": platform_height, "x": col1 - platform_width / 2, "y": floor3 }, { "width": platform_width, "height": platform_height, "x": col3 - platform_width / 2, "y": floor3 }, ], "cannons": [ { "x": block_width, "y": SCREEN_HEIGHT - block_width - CANNON_SIZE, "x_speed": CHAR_SPEED + 1 }, ], "coins": [ { "x": block_width + 20, "y": block_width + 20 }, { "x": SCREEN_WIDTH - block_width - COIN_SIZE - 20, "y": block_width + 20 }, { "x": col1 - COIN_SIZE / 2, "y": SCREEN_HEIGHT - block_width - COIN_SIZE - 20 }, ] }
true
644f287b3a166cb6b5af6f8358b2c9289bd71340
Python
Hoseung/pyRamAn
/scripts/SAMI/lambda_mp_galaxy.py
UTF-8
15,224
2.53125
3
[ "MIT" ]
permissive
# coding: utf-8 import matplotlib.pyplot as plt def save_result(savedir, galid, data): """ parameters ---------- savedir : str galid : int """ # savedir = 'simulation/galaxyXXXX/' header = "NOUT ID X Y Z[Mpc] \ Vx Vy Vz[km/s] Reff[kpc] Mstar Mgas[Msun] Lambda_r" fmt = " %3i %5i %.5f %.5f %.5f %.4f %.4f %.4f %.3f %.f %.f %.6f" fname = savedir + "galaxy_" + str(galid).zfill(5) + '.txt' with open(fname, 'wb') as fout: np.savetxt(fout, [], header=header) # Header for data in dictout: np.savetxt(fout, np.c_[data['nout'], data['id'], data['xc'], data['yc'], data['zc'], data['vx'], data['vy'], data['vz'], data['rgal'], data['mstar'], data['mgas'], data['lambda_r']], fmt=fmt) # Append print("Save_result Done") def load_gal_txt(savedir, galid): fname = savedir+ str(galid).zfill(5) + '.txt' return np.loadtxt(fname, dtype = 'float, int', skiprows=0, unpack=True) def plot_result_pickle(fname, savedir): import pickle with open(fname, 'rb') as f: dd = pickle.load(f) # plot data fig, host = plt.subplots() fig.subplots_adjust(right=0.75) par1 = host.twinx() host.plot(nouts[::-1], dd['lambda_r']) par1.plot(nouts[::-1], dd['mstar'], 'r-') par1.set_ylabel("Stellar mass [M_{\odot}]") #plt.show() plt.savefig(savedir + + str(dd[0]).zfill(5) + '.png') plt.close() def plot_result_txt(savedir, galid): # Load data index, gal_id, xc, yc, zc, vx, vy,vz, rgal, mstar, mgas, lambda_r = \ load_gal_txt(savedir, galid) # plot data fig, host = plt.subplots() fig.subplots_adjust(right=0.75) par1 = host.twinx() host.plot(nouts[::-1], lambda_r[i]) par1.plot(nouts[::-1], mstar[i], 'r-') par1.set_ylabel("Stellar mass [M_{\odot}]") #plt.show() plt.savefig(savedir + + str(galid).zfill(5) + '.png') plt.close() def test_galaxy(galaxy, npart_min=1000): # Is it a galaxy? # minimum particles npart = len(galaxy.star.x) print("number of particles:", npart) if npart < npart_min: print("!! It has only {} particles. Not a galaxy.") return # Test coordinate origin # Test projection # Test population # Stellar particle # DarkMatter particle # Sink particle in DM? # Gas cell # Test unit # position # velocity # mass # Test for existances # normal vection # rotation matrix #%% def mk_gal(halodata, out_q, info, i, final_gal, save=False, rscale=0.3, verbose=False, galaxy_plot_dir='./', rscale_lambda=2.0, npix_lambda=50, npix=400): """ Direct plot, Create galaxy, Calculate lambda_r (using Cappellari 2003) Draw ed map of galaxy. """ from galaxymodule import galaxy import utils.sampling as smp import draw import matplotlib.pyplot as plt # print("IDs:", id(star), id(dm), id(cell)) # id_gal = halodata['id'] sid_gal = str(id_gal).zfill(5) sid_fgal = str(final_gal).zfill(5) snout = str(info.nout).zfill(5) gal_out = {"id":0, "xc":0.0, "yc":0.0, "zc":0.0, "vx":0.0, "vy":0.0, "vz":0.0, "mstar":0.0, "nstar":0.0, "mgas":0.0, "lambda_arr":[], "lambda_r":0, "rgal":0, "final":final_gal, "mhal":0.0, "rhal":0.0} # Direct plot --------------------------------------------------------- extent = (0, npix, 0, npix) region = smp.set_region(xc=halodata['x'], yc=halodata['y'], zc=halodata['z'], radius = halodata['rvir']) star_map = draw.pp.den2d(star['x'], star['y'], star['z'], star['m'], npix, region=region, cic=True, norm_integer=False) if star_map is not False: ls = np.zeros((npix,npix)) ii = star_map > 0 ls[ii] = np.log10(star_map[ii]) # Stellar map HAS empty pixels. ls[star_map <= 0] = np.floor(ls.min()) im1 = plt.imshow(ls, cmap="gray", interpolation='nearest', extent=extent) # One of two should be transposed. # But which one? gas_map = draw.pp.pp_cell(cell, npix, info, region=region, verbose=False) im2 = plt.imshow(np.transpose(np.log10(gas_map)), cmap="CMRmap", alpha=.5, interpolation='bilinear', extent=extent) rgal = region['radius'] * s.info.pboxsize * 1000 ax = plt.gca() ax.set_xlabel("position [kpc]") ax.set_xticks(np.linspace(0,npix,5)) xticks = ["{:.2f}".format(x) for x in np.linspace(-rgal, rgal, num=5)] ax.set_xticklabels(xticks) ax.set_ylabel("position [kpc]") ax.set_yticks(np.linspace(0,npix,5)) yticks = ["{:.2f}".format(y) for y in np.linspace(-rgal, rgal, num=5)] ax.set_yticklabels(yticks) fn_suffix = snout + "_" + sid_gal + "_" + sid_fgal +'.png' plt.savefig(galaxy_plot_dir + "2dmap_" + fn_suffix, dpi=144) plt.close() #Create galaxy --------------------------------------------------------- gal = galaxy.Galaxy(halodata, radius_method='simple', info=info) is_gal = gal.mk_gal(star=star, dm=dm, cell=cell, rscale=rscale, verbose=verbose) #----------------------------------------------------------------------- print(gal.id, "IS_GAL",is_gal) if not is_gal: print(gal.id, " Not a good galaxy") out_q.put(gal_out) else: # Save to catalog ----------------------------------------------------- gal.cal_lambda_r(npix=npix_lambda, method=1, rscale=rscale_lambda) # Calculate lambda_r ------------------------------------------------- gal.plot_gal(fn_save = galaxy_plot_dir + "galaxyplot" + fn_suffix, ioff=True) # gal.save_gal(base=wdir) # Instead of galaxy class, save them in a dict. gal_out['mstar'] = gal.mstar gal_out['mgas'] = gal.mgas gal_out['nstar'] = gal.nstar gal_out['id'] = gal.id gal_out['xc'] = gal.xc * info.pboxsize gal_out['yc'] = gal.yc * info.pboxsize gal_out['zc'] = gal.zc * info.pboxsize gal_out['vx'] = gal.vxc * info.kms gal_out['vy'] = gal.vyc * info.kms gal_out['vz'] = gal.vzc * info.kms gal_out['lambda_arr'] = gal.lambda_arr gal_out['lambda_r'] = gal.lambda_r gal_out['rgal'] = gal.reff# * info.pboxsize * 1000.0 # in kpc gal_out['mhal'] = halodata['mvir'] gal_out['rhal'] = halodata['rvir'] out_q.put(gal_out) print("mk_gal Done") return def plot_lambda(catalog, i_early, i_late, i_bad, out_dir='./'): import matplotlib.pyplot as plt plt.ioff() f = plt.figure() ax = f.add_subplot(111) #for i, val in enumerate(lambdar_arr): for i in i_early: a = np.asarray(catalog['lambda_arr'][i]) ax.plot(a, 'r-', alpha=0.5) # Red = Early for i in i_late: ax.plot(catalog['lambda_arr'][i], 'b-', alpha=0.3) # Red = Early #plt.xlabel() # in the unit of Reff ax.set_title(r"$\lambda _{R}$") ax.set_ylabel(r"$\lambda _{R}$") ax.set_xlabel("["+ r'$R/R_{eff}$'+"]") ax.set_xlim(right=9) ax.set_xticks([0, 4.5, 9]) ax.set_xticklabels(["0", "0.5", "1"]) plt.savefig(out_dir + "lambdar_disk.png") plt.close() #%% # import pickle # with open(fcat, 'rb') as f: # dd = pickle.load(f) # plot data def _get_data_dict(dictout): nouts = [] lambda_r = [] mstar =[] for dd in dictout: nouts.append(dd['nout']) lambda_r.append(dd['lambda_r']) mstar.append(dd['mstar']) return nouts, lambda_r, mstar def _get_data_catalog(catalog): return catalog['nout'],catalog['lambda_r'], catalog['mstar'] def plot_growth_history(data, nouts, idgal=None): zreds=[] aexps=[] import load nnouts = len(nouts) for nout in nouts: info = load.info.Info(nout=nout, base=wdir, load=True) aexps.append(info.aexp) zreds.append(info.zred) aexps = np.array(aexps) zreds = np.array(zreds) #%% def aexp2zred(aexp): return [1.0/a - 1.0 for a in aexp] def zred2aexp(zred): return [1.0/(1.0 + z) for z in zred] def lbt2aexp(lts): import astropy.units as u from astropy.cosmology import WMAP7, z_at_value zreds = [z_at_value(WMAP7.lookback_time, ll * u.Gyr) for ll in lts] return [1.0/(1+z) for z in zreds] # For a given list of nouts, # calculate a nice-looking set of zreds. # AND lookback times z_targets=[0, 0.2, 0.5, 1, 2, 3] z_target_str=["{:.2f}".format(z) for z in z_targets] a_targets_z = zred2aexp(z_targets) z_pos = [nout_ini + (1 - (max(aexps) - a)/aexps.ptp()) * nnouts for a in a_targets_z] lbt_targets=[0.00001,1,3,5,8,12] lbt_target_str=["{:.0f}".format(l) for l in lbt_targets] a_targets_lbt = lbt2aexp(lbt_targets) lbt_pos = [nout_ini + (1 - (max(aexps) - a)/aexps.ptp()) * nnouts for a in a_targets_lbt] nouts, lambda_r, mstar = _get_data_dict(data) fig, ax1 = plt.subplots() fig.subplots_adjust(right=0.75) fig.suptitle("ID: " + str(idgal).zfill(5), fontsize=18)#, y=1.01) fig.subplots_adjust(right=0.75) # label needed for legend() lns1 = ax1.plot(nouts, lambda_r, label=r"$\lambda_{R}$") ax1.set_xticks(z_pos) ax1.set_xticklabels(z_target_str) ax1.set_xlim([0,187]) ax1.set_ylim([0,1.0]) ax1.set_ylabel(r"$\lambda_{R}$") ax1.set_xlabel("redshift") ax2 = ax1.twinx() lns2 = ax2.plot(nouts, mstar, 'r-', label="stellar mass") ax2.set_ylim([0, 1.3*max(mstar)]) ax2.set_ylabel(r"Stellar mass $[M_{\odot}]$") ax3 = ax1.twiny() ax3.set_xlabel("Lookback time", labelpad=10) ax3.set_xticks(lbt_pos) ax3.set_xticklabels(lbt_target_str) # Because there are two axes superimposed, # manually gather labels of objects first. lns = lns1+lns2 labs = [l.get_label() for l in lns] ax1.legend(lns, labs, loc=0) plt.savefig(dir_gal + str(sidgal_final).zfill(5) + '.png') #plt.show() plt.close() #%% """ The processing pool needs to be instantiated in the main thread of execution. """ import multiprocessing as mp import load from tree import tmtree import numpy as np import utils.sampling as smp #import ctypes import tree.halomodule as hmo import os if __name__ == '__main__': # ncore = int(input("How many cores? \n")) # wdir = input("Working directory \n") #nout = int(input("nout? \n")) #wdir = './' wdir = '/home/hoseung/Work/data/05427/' ncore = 1 #ncore = 16 # 27 : z=4; 37 : z=3; 20 : ~ z=5 nout_ini = 186 nout_fi = 187 # 05427 galaxies: # [1600, 1612, 1645, 1648, 1664, 1665, 1669, 1681, 1686] gal_final = int(input("Galaxy ID")) mstar_min_plot = 1e9 rscale = 0.8 r_cluster_scale = 2.0 # maximum radius inside which galaxies are searched for npix=800 rscale_lambda = 3.0 npix_lambda = int(15 * rscale_lambda) lmax = 19 ptypes=["star id pos mass vel time metal", "dm id pos mass vel"] frefine= 'refine_params.txt' fnml = 'cosmo_200.nml' ## halo part ### dir_out = wdir + 'catalog/' # nout_halo = 122 == nout 10, nout_halo = 0 == nout 132 nouts = range(nout_fi, nout_ini -1, -1) Nnouts = len(nouts) tt = tmtree.load(work_dir=wdir, filename="halo/TMtree.fits") tfin = tt[np.where(tt['NOUT'] == 0)] tini = tt[np.where(tt['NOUT'] == nout_fi - nout_ini)] #%% info = load.info.Info(nout=nout_fi, base=wdir, load=True) hh = hmo.Halo(base=wdir, nout=nout_fi, halofinder='HM', info=info, load=True) i_center = np.where(hh.data['np'] == max(hh.data['np']))[0] i_satellites = smp.extract_halos_within(hh.data, i_center, scale=r_cluster_scale) print("Total {0} halos \n{1} halos are selected".format( len(i_satellites),sum(i_satellites))) #%% # ALL halos inside the cluster and have tree back to nout_ini halo_list = hh.data['id'][i_satellites] h_ind_ok, halo_ok = tmtree.check_tree_complete(tt, 0, nout_fi - nout_ini, halo_list) print(len(halo_ok), "halos left") igal = np.where(halo_ok[:,0] == gal_final)[0] # gal_final = halo_ok[igal,0] sidgal_final = str(gal_final).zfill(5) dir_gal = wdir + 'galaxy_' + str(gal_final).zfill(5) + '/' fcat = dir_gal +"catalog_" + sidgal_final + ".pickle" if os.path.isdir(dir_gal) is False: os.mkdir(dir_gal) m = mp.Manager() out_q = m.Queue() dictout=[] for inout, nout in enumerate(nouts): print(inout, nout) snout = str(nout) info = load.info.Info(nout=nout, base=wdir, load=True) hh = hmo.Halo(base=wdir, nout=nout, halofinder='HM', info=info, load=True) hind = np.where(hh.data['id'] == halo_ok[igal,inout]) region = smp.set_region_multi(xc=hh.data['x'][hind], yc=hh.data['y'][hind], zc=hh.data['z'][hind], radius = hh.data['rvir'][hind] * rscale) gal_id_now = hh.data['id'][hind] s = load.sim.Sim() s.setup(nout, wdir) s.set_ranges(region["ranges"]) s.show_cpus() s.add_part(ptypes) s.part.load(fortran=True) s.add_hydro() s.hydro.amr2cell(lmax=19) star = s.part.star dm = s.part.dm cell = s.hydro.cell nh = len(hind) mk_gal(hh.data[hind][0], out_q, s.info, 1, gal_final, galaxy_plot_dir=dir_gal, verbose=False, rscale_lambda=rscale_lambda, npix_lambda=npix_lambda) print("----------Done---------") dd = out_q.get(timeout=1) dd['nout'] = nout dictout.append(dd) save_result(dir_gal, gal_final, dictout) import pandas as pd catalog = pd.DataFrame(dictout).to_records() import pickle with open(fcat, 'wb') as f: pickle.dump(catalog, f) plot_growth_history(catalog, nouts, idgal=gal_final) # plot_merger_tree
true
c96656a9e9a79cbccc83f4b487a7b83e94b06c76
Python
jabc1/ProgramLearning
/python/python-Michael/ErrorPdbTest/err.py
UTF-8
3,446
4.15625
4
[]
no_license
# -*- coding: utf-8 -*- # 错误处理:Python内置了一套异常处理机制,来帮助我们进行错误处理 # 调试: Python的pdb可以让我们以单步方式执行代码。 # 测试:编写测试也很重要,可以在程序修改后反复运行,确保程序输出符合我们编写的测试 # 错误处理:高级语言通常都内置了一套try...except...finally...的错误处理机制 # 除零错误 try: print('try begin...') r = 1 / 0 #division by zero print('result:', r) except ZeroDivisionError as e: print('except: ', e) finally: print('finally...') print('END') # 当我们认为某些代码可能会出错时,就可以用try来运行这段代码,如果执行出错,则后续代码不会继续执行,而是直接 # 跳转至错误处理代码,即except语句块,执行完except后,如果有finally语句块,则执行finally语句块,至此,执行完毕。 ## 和java一样 # int()函数可能会抛出ValueError # 可以在except语句块后面加一个else,当没有错误发生时,会自动执行else语句: try: print('try...') r = 10 / int('2') print('result:', r) except ValueError as e: print('ValueError:', e) except ZeroDivisionError as e: print('ZeroDivisionError:', e) else: print('no error!') finally: print('finally...') print('END') # Python所有的错误都是从BaseException类派生的,常见的错误类型和继承关系看这里: # https://docs.python.org/3/library/exceptions.html#exception-hierarchy # 使用try...except捕获错误还有一个巨大的好处,就是可以跨越多层调用 # 不需要在每个可能出错的地方去捕获错误,只要在合适的层次去捕获错误就可以了 # Python内置的logging模块可以非常容易地记录错误信息: # err_logging.py import logging def foo(s): return 10 / int(s) def bar(s): return foo(s) * 2 def main(): try: bar('0') except Exception as e: logging.exception(e) main() print('END') # 通过配置,logging还可以把错误记录到日志文件里,方便事后排查 # 抛出错误 # 如果要抛出错误,首先根据需要,可以定义一个错误的class,选择好继承关系,然后,用raise语句抛出一个错误的实例: # err_raise.py class FooError(ValueError): pass def foo(s): n = int(s) if n==0: raise FooError('invalid value: %s' % s) return 10 / n foo('0') # 只有在必要的时候才定义我们自己的错误类型。如果可以选择Python已有的内置的错误类型(比如ValueError,TypeError),尽量使用Python内置的错误类型。 # err_reraise.py def foo(s): n = int(s) if n==0: raise ValueError('invalid value: %s' % s) return 10 / n def bar(): try: foo('0') except ValueError as e: print('ValueError!') raise # 处理错误后,继续上抛??? bar() # 捕获错误目的只是记录一下,便于后续追踪 # 由于当前函数不知道应该怎么处理该错误,所以,最恰当的方式是继续往上抛,让顶层调用者去处理 # raise语句如果不带参数,就会把当前错误原样抛出 # 在except中raise一个Error,还可以把一种类型的错误转化成另一种类型: # 转换逻辑需要合理,否则造成混乱 ## 应该在文档中写清楚可能会抛出哪些错误,以及错误产生的原因。
true
3a29db16fd30979c0e10e58dca635db6e766d1c0
Python
UAdenisyu/ANTLR4-parser
/main.py
UTF-8
905
2.6875
3
[]
no_license
#main.py from antlr4 import * from antlr4_files.TestLexer import TestLexer from antlr4_files.TestListener import TestListener from antlr4_files.TestParser import TestParser import sys class TestPrintListener(TestListener): def enterProg(self, ctx): print('Syntactic and lexical analyzes are completed.') input() def main(): f = open('program_example.pypas', 'r') sourceCode=f.read() f.close() lexer = TestLexer(InputStream(sourceCode)) #print(type(InputStream('test smth'))) stream = CommonTokenStream(lexer) parser = TestParser(stream) tree = parser.prog()#prog - назва початкового правила (метод класу 'Ім'я граматики'Parser) в 'Ім'я граматики'Parser.py printer = TestPrintListener() walker = ParseTreeWalker() walker.walk(printer, tree) if __name__ == '__main__': main()
true
753b9418054e3ba951604cc0375ba9dcc2ad09b1
Python
Thainahelena/python3-cursoEmVideo
/Mundo I/ex013.py
UTF-8
237
4.1875
4
[]
no_license
salario_0 = float(input('Digite o salário do funcionário: R$ ')) salario_1 = salario_0 * 1.15 print('Um funcionário que recebe um salário de R$ {:.2f}, passa a receber R$ {:.2f}, com um aumento de 15%!'.format(salario_0, salario_1))
true
c937565696aac2e187518df8250f65c089052e8c
Python
saifsm7877/QuestionNumber01_saif-momin
/Question03_saif momin
UTF-8
176
3.171875
3
[]
no_license
a = input() level = 0 count = 0 for step in a: if step == 'U': level += 1 if level == 0: count += 1 else: level -= 1 print(count)
true
e0d6d57d0a24c9e523fd8aa05adc274d07ebcd78
Python
mahehu/SGN-41007
/code/pca_example.py
UTF-8
9,257
2.59375
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """ Created on Tue Feb 16 13:41:05 2016 @author: hehu """ # -*- coding: utf-8 -*- """ Created on Tue Aug 4 11:01:16 2015 @author: hehu """ import matplotlib.pyplot as plt import numpy as np from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC, LinearSVC from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes from mpl_toolkits.axes_grid1.inset_locator import mark_inset from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import NullFormatter import pprint from sklearn.model_selection import cross_val_score, \ KFold, StratifiedShuffleSplit, \ LeaveOneOut from scipy.linalg import eig from scipy.stats import norm def gaussian(x, mu, sig): return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.))) def generate_data(N): X1 = np.random.randn(2,N) X2 = np.random.randn(2,N) M1 = np.array([[1.5151, -0.1129], [0.1399, 0.6287]]) M2 = np.array([[0.8602, 1.2461], [-0.0737, -1.5240]]) T1 = np.array([-1, 1]).reshape((2,1)) T2 = np.array([-5, 2]).reshape((2,1)) X1 = np.dot(M1, X1) + np.tile(T1, [1,N]) X2 = np.dot(M2, X2) + np.tile(T2, [1,N]) X1 = X1[::-1,:] X2 = X2[::-1,:] return X1, X2 if __name__ == "__main__": #plt.style.use('classic') plt.close("all") # Generate random training data N = 200 np.random.seed(2015) X1, X2 = generate_data(N) X = np.concatenate((X1.T, X2.T)) y = np.concatenate((np.ones(N), np.zeros(N))) X = X - np.tile(X.mean(axis = 0), [X.shape[0], 1]) plt.figure(figsize = [5,8]) plt.plot(X[:, 0], X[:,1], 'ro') #plt.plot(plt.xlim(), [0,0], 'k-') #plt.plot([0,0], plt.ylim(), 'k-') plt.axis('tight') #D, W = np.linalg.eig(np.cov(X, rowvar = False)) D, W = np.linalg.eig(np.matmul(X.T, X)) W = W[:, np.argsort(D)[::-1]] d = -5 plt.arrow(0, 0, d * W[0,0], d * W[1,0], zorder = 3, fc = 'k', width = 0.2, head_width=0.6, head_length=0.3) plt.arrow(0, 0, d * W[0,1], d * W[1,1], zorder = 3, fc = 'k', width = 0.2, head_width=0.6, head_length=0.3) plt.grid() plt.axis('equal') plt.annotate("First PC", 0.9 * d * W[:, 0], xytext=(-4, 5), size=13, bbox=dict(boxstyle="round4", fc="w", ec = "g"), arrowprops=dict(arrowstyle="simple", connectionstyle="arc3,rad=0.2", shrinkA = 0, shrinkB = 8, fc = "g", ec = "g"), horizontalalignment='center', verticalalignment='baseline') plt.annotate("Second PC", 0.7 * d * W[:, 1], xytext=(4, -1), size=13, bbox=dict(boxstyle="round4", fc="w", ec = "g"), arrowprops=dict(arrowstyle="simple", connectionstyle="arc3,rad=0.2", shrinkA = 0, shrinkB = 8, fc = "g", ec = "g"), horizontalalignment='center', verticalalignment='baseline') plt.savefig("../images/PCA_example.pdf", bbox_inches = "tight") print("First PC: %s" % str(-W[:, 0])) print("Second PC: %s" % str(-W[:, 1])) ######## Digits example from sklearn.datasets import load_digits from sklearn.preprocessing import Normalizer digits = load_digits() X = digits.data y = digits.target X = X - np.tile(X.mean(axis = 0), [X.shape[0], 1]) D, V = np.linalg.eig(np.cov(X, rowvar = False)) X_rot = np.matmul(X, V) fig, ax = plt.subplots(1,2,figsize = [5,3]) ax[0].imshow(digits.images[0], cmap = 'gray', interpolation = 'bilinear') ax[0].set_title("Original") ax[1].imshow(X_rot[0, :].reshape(8,8), interpolation = 'nearest') ax[1].set_title("PCA mapped") plt.savefig('../images/digits_pca_proj_example1.pdf', bbox_inches='tight') fig, ax = plt.subplots(1,2,figsize = [5,3]) ax[0].imshow(digits.images[800], cmap = 'gray', interpolation = 'bilinear') ax[0].set_title("Original") ax[1].imshow(X_rot[800, :].reshape(8,8), interpolation = 'nearest') ax[1].set_title("PCA mapped") plt.savefig('../images/digits_pca_proj_example2.pdf', bbox_inches='tight') plt.figure() plt.bar(np.arange(X_rot.shape[1]), np.var(X_rot, axis = 0)) plt.grid() plt.axis('tight') plt.title("Variances of principal components") plt.savefig('../images/digits_pca_proj_vars.pdf', bbox_inches='tight') plt.figure(figsize = [5,8]) labels = ['zeros', 'ones', 'twos', 'threes', 'fours', 'fives', 'sixes', 'sevens', 'eights', 'nines'] for k in range(10): plt.scatter(X_rot[y == k, 0], X_rot[y == k, 1], label = labels[k]) plt.legend(loc = 'best') plt.savefig('../images/digits_pca_proj.pdf', bbox_inches='tight') fig, ax = plt.subplots(4, 2, figsize = [3,7]) for k in range(4): for j in range(2): ax[k][j].imshow(V[:, k*2 + j].reshape(8,8), interpolation = 'bilinear') ax[k][j].set_title("Eigenimage %d" % (k*2 + j + 1)) plt.tight_layout() plt.savefig('../images/digits_eigenimages.pdf', bbox_inches='tight') #T-SNE ######## Digits example from sklearn.datasets import load_digits from sklearn.preprocessing import Normalizer from sklearn.manifold import TSNE digits = load_digits() X = digits.data y = digits.target X = X - np.tile(X.mean(axis = 0), [X.shape[0], 1]) tsne = TSNE(n_components=2, init='pca', random_state=0) X_tsne = tsne.fit_transform(X) plt.figure(figsize = [5,8]) labels = ['zeros', 'ones', 'twos', 'threes', 'fours', 'fives', 'sixes', 'sevens', 'eights', 'nines'] for k in range(10): plt.scatter(X_tsne[y == k, 0], X_tsne[y == k, 1], label = labels[k]) plt.legend(loc = 'best') plt.savefig('../images/digits_tsne_proj.pdf', bbox_inches='tight') ##################### from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.cross_validation import train_test_split from sklearn.metrics import accuracy_score from scipy.io import loadmat from sklearn.decomposition import PCA D = loadmat("arcene.mat") X_test = D["X_test"] X_train = D["X_train"] y_test = D["y_test"].ravel() y_train = D["y_train"].ravel() normalizer = Normalizer() normalizer.fit(X_train) X_train = normalizer.transform(X_train) X_test = normalizer.transform(X_test) pca = PCA() pca.fit(X_train) X_train = pca.transform(X_train) X_test = pca.transform(X_test) accuracies = [] for num_components in range(1, 99): clf = LinearDiscriminantAnalysis() clf.fit(X_train[:, :num_components], y_train) y_pred = clf.predict(X_test[:, :num_components]) accuracy = accuracy_score(y_test, y_pred) accuracies.append(accuracy) plt.figure() plt.plot(accuracies, linewidth = 2) topScore = np.max(accuracies) topIdx = np.argmax(accuracies) plt.annotate('Top score %.1f %%' % (100.0*topScore), xy=(topIdx + 1, topScore), xytext=(50, 0.65), size=13, bbox=dict(boxstyle="round4", fc="w", ec = "g"), arrowprops=dict(arrowstyle="simple", connectionstyle="arc3,rad=-0.2", shrinkA = 0, shrinkB = 8, fc = "g", ec = "g"), horizontalalignment='center', verticalalignment='middle') plt.annotate('100 components %.1f %%' % (100.0*accuracies[-1]), xy=(99, accuracies[-1]), xytext=(70, 0.6), size=13, bbox=dict(boxstyle="round4", fc="w", ec = "g"), arrowprops=dict(arrowstyle="simple", connectionstyle="arc3,rad=0.2", shrinkA = 0, shrinkB = 8, fc = "g", ec = "g"), horizontalalignment='center', verticalalignment='middle') plt.grid() plt.title("Classification accuracy") plt.xlabel("Number of PCA components") plt.ylabel("Accuracy / %") plt.savefig('../images/arcene_pca.pdf', bbox_inches='tight')
true
8ecf500026b370e19cd97aa9d1ab6767a025d0f9
Python
VorTECHsa/python-sdk
/vortexasdk/endpoints/attributes.py
UTF-8
3,448
2.75
3
[ "Apache-2.0" ]
permissive
""" Try me out in your browser: [![Binder](https://img.shields.io/badge/try%20me%20out-launch%20notebook-579ACA.svg?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFkAAABZCAMAAABi1XidAAAB8lBMVEX///9XmsrmZYH1olJXmsr1olJXmsrmZYH1olJXmsr1olJXmsrmZYH1olL1olJXmsr1olJXmsrmZYH1olL1olJXmsrmZYH1olJXmsr1olL1olJXmsrmZYH1olL1olJXmsrmZYH1olL1olL0nFf1olJXmsrmZYH1olJXmsq8dZb1olJXmsrmZYH1olJXmspXmspXmsr1olL1olJXmsrmZYH1olJXmsr1olL1olJXmsrmZYH1olL1olLeaIVXmsrmZYH1olL1olL1olJXmsrmZYH1olLna31Xmsr1olJXmsr1olJXmsrmZYH1olLqoVr1olJXmsr1olJXmsrmZYH1olL1olKkfaPobXvviGabgadXmsqThKuofKHmZ4Dobnr1olJXmsr1olJXmspXmsr1olJXmsrfZ4TuhWn1olL1olJXmsqBi7X1olJXmspZmslbmMhbmsdemsVfl8ZgmsNim8Jpk8F0m7R4m7F5nLB6jbh7jbiDirOEibOGnKaMhq+PnaCVg6qWg6qegKaff6WhnpKofKGtnomxeZy3noG6dZi+n3vCcpPDcpPGn3bLb4/Mb47UbIrVa4rYoGjdaIbeaIXhoWHmZYHobXvpcHjqdHXreHLroVrsfG/uhGnuh2bwj2Hxk17yl1vzmljzm1j0nlX1olL3AJXWAAAAbXRSTlMAEBAQHx8gICAuLjAwMDw9PUBAQEpQUFBXV1hgYGBkcHBwcXl8gICAgoiIkJCQlJicnJ2goKCmqK+wsLC4usDAwMjP0NDQ1NbW3Nzg4ODi5+3v8PDw8/T09PX29vb39/f5+fr7+/z8/Pz9/v7+zczCxgAABC5JREFUeAHN1ul3k0UUBvCb1CTVpmpaitAGSLSpSuKCLWpbTKNJFGlcSMAFF63iUmRccNG6gLbuxkXU66JAUef/9LSpmXnyLr3T5AO/rzl5zj137p136BISy44fKJXuGN/d19PUfYeO67Znqtf2KH33Id1psXoFdW30sPZ1sMvs2D060AHqws4FHeJojLZqnw53cmfvg+XR8mC0OEjuxrXEkX5ydeVJLVIlV0e10PXk5k7dYeHu7Cj1j+49uKg7uLU61tGLw1lq27ugQYlclHC4bgv7VQ+TAyj5Zc/UjsPvs1sd5cWryWObtvWT2EPa4rtnWW3JkpjggEpbOsPr7F7EyNewtpBIslA7p43HCsnwooXTEc3UmPmCNn5lrqTJxy6nRmcavGZVt/3Da2pD5NHvsOHJCrdc1G2r3DITpU7yic7w/7Rxnjc0kt5GC4djiv2Sz3Fb2iEZg41/ddsFDoyuYrIkmFehz0HR2thPgQqMyQYb2OtB0WxsZ3BeG3+wpRb1vzl2UYBog8FfGhttFKjtAclnZYrRo9ryG9uG/FZQU4AEg8ZE9LjGMzTmqKXPLnlWVnIlQQTvxJf8ip7VgjZjyVPrjw1te5otM7RmP7xm+sK2Gv9I8Gi++BRbEkR9EBw8zRUcKxwp73xkaLiqQb+kGduJTNHG72zcW9LoJgqQxpP3/Tj//c3yB0tqzaml05/+orHLksVO+95kX7/7qgJvnjlrfr2Ggsyx0eoy9uPzN5SPd86aXggOsEKW2Prz7du3VID3/tzs/sSRs2w7ovVHKtjrX2pd7ZMlTxAYfBAL9jiDwfLkq55Tm7ifhMlTGPyCAs7RFRhn47JnlcB9RM5T97ASuZXIcVNuUDIndpDbdsfrqsOppeXl5Y+XVKdjFCTh+zGaVuj0d9zy05PPK3QzBamxdwtTCrzyg/2Rvf2EstUjordGwa/kx9mSJLr8mLLtCW8HHGJc2R5hS219IiF6PnTusOqcMl57gm0Z8kanKMAQg0qSyuZfn7zItsbGyO9QlnxY0eCuD1XL2ys/MsrQhltE7Ug0uFOzufJFE2PxBo/YAx8XPPdDwWN0MrDRYIZF0mSMKCNHgaIVFoBbNoLJ7tEQDKxGF0kcLQimojCZopv0OkNOyWCCg9XMVAi7ARJzQdM2QUh0gmBozjc3Skg6dSBRqDGYSUOu66Zg+I2fNZs/M3/f/Grl/XnyF1Gw3VKCez0PN5IUfFLqvgUN4C0qNqYs5YhPL+aVZYDE4IpUk57oSFnJm4FyCqqOE0jhY2SMyLFoo56zyo6becOS5UVDdj7Vih0zp+tcMhwRpBeLyqtIjlJKAIZSbI8SGSF3k0pA3mR5tHuwPFoa7N7reoq2bqCsAk1HqCu5uvI1n6JuRXI+S1Mco54YmYTwcn6Aeic+kssXi8XpXC4V3t7/ADuTNKaQJdScAAAAAElFTkSuQmCC)](https://mybinder.org/v2/gh/VorTECHsa/python-sdk/master?filepath=docs%2Fexamples%2Ftry_me_out%2Fattributes.ipynb) """ from typing import List, Union from vortexasdk.endpoints.endpoints import ATTRIBUTES_REFERENCE from vortexasdk.endpoints.attributes_result import AttributeResult from vortexasdk.operations import Reference, Search from vortexasdk.utils import convert_to_list class Attributes(Reference, Search): """ Attributes endpoint. An Attribute is a reference value that corresponds to an ID associated with other entities. For example, a vessel object from the Vessel reference endpoint may have the following keys: ```json { "ice_class": "b09ed4e2bd6904dd", "propulsion": "3ace0e050724707b" } ``` These IDs represent attributes which can be found via the Attributes reference endpoint. When the attributes endpoint is searched with those ids as parameters: ```python >>> from vortexasdk import Attributes >>> df = Attributes().search(ids=["b09ed4e2bd6904dd", "3ace0e050724707b"]).to_df() ``` Returns | | id | type | label | |---:|:-----------------|:-----------|:---------| | 0 | b09ed4e2bd6904dd | ice_class | UNKNOWN | | 1 | 3ace0e050724707b | propulsion | DFDE | """ def __init__(self): Reference.__init__(self, ATTRIBUTES_REFERENCE) Search.__init__(self, ATTRIBUTES_REFERENCE) def load_all(self) -> AttributeResult: """ Load all attributes. """ return self.search() # noinspection PyShadowingBuiltins def search( self, type: str = None, term: Union[str, List[str]] = None, ids: Union[str, List[str]] = None, ) -> AttributeResult: """ Find all attributes matching given type. # Arguments type: The type of attribute we're filtering on. Type can be: `ice_class`, `propulsion`, `scrubber` # Returns List of attributes matching `type` # Examples Find all attributes with a type of `ice_class`. ```python >>> from vortexasdk import Attributes >>> df = Attributes().search(type="scrubber").to_df() ``` returns | | id | name | type | |---:|:-----------------|:-----------|:------------| | 0 | 14c7b073809eb565 | Open Loop | scrubber | | 1 | 478fca39000c49d6 | Unknown | scrubber | """ search_params = { "term": [str(e) for e in convert_to_list(term)], "ids": convert_to_list(ids), "type": type, } response = super().search_with_client( exact_term_match=False, response_type=None, headers=None, **search_params ) return AttributeResult( records=response["data"], reference=response["reference"] )
true
fcfaf4022d9f8f5632e10b0d39d8c0b757cd950d
Python
mironmiron3/SoftUni-Python-Advanced
/Comprehensions/Matrix-Modifications.py
UTF-8
1,137
3.125
3
[]
no_license
n = int(input()) matrix = [] for _ in range(n): matrix.append(input().split()) matrix = [[int(el) for el in sublist] for sublist in matrix] command = input() while not command == "END": if command.startswith("Add"): useless, row, col, value = command.split() row, col, value = int(row), int(col), int(value) if 0 <= row <= len(matrix)-1 and 0 <= col <= len(matrix)-1: matrix[row][col] += value else: print("Invalid coordinates") elif command.startswith("Subtract"): useless, row, col, value = command.split() row, col, value = int(row), int(col), int(value) if 0 <= row <= len(matrix) - 1 and 0 <= col <= len(matrix) - 1: matrix[row][col] -= value else: print("Invalid coordinates") command = input() #[print(num,end=" ") for sublist in matrix for num in sublist] for matrix_index in range(len(matrix)): matrix[matrix_index] = list(map(str, matrix[matrix_index])) [print(f"{' '.join(collection)}")for collection in matrix] a = zip([1,2,3],['a','b']) print(a)
true
5297c3dae55554c756de31190948d4134e0abb2a
Python
wayne2015/deeplearning
/dA.py
UTF-8
4,240
2.65625
3
[]
no_license
import numpy import theano import theano.tensor as T import cPickle,gzip import utils import Image from theano.tensor.shared_randomstreams import RandomStreams class dA(object): def __init__(self,input,n_visible,n_hidden, w_init=None,bVisible=None,bHidden=None): numpy_rng = numpy.random.RandomState(123) #randomFunc = RandomStreams(numpy_rng.randint(2**30)) if w_init == None: w_init = numpy.asarray( numpy_rng.uniform( size=(n_visible,n_hidden), low=-4 * numpy.sqrt(6. / (n_hidden + n_visible)), high=4 * numpy.sqrt(6. / (n_hidden + n_visible)) ), dtype = theano.config.floatX ) if bVisible == None: bVisible = theano.shared( value = numpy.zeros( n_visible, dtype = theano.config.floatX ), borrow = True ) if bHidden == None: bHidden = theano.shared( value = numpy.zeros( n_hidden, dtype = theano.config.floatX ), borrow=True ) if input == None: input = T.dmatrix(name='input') self.w = theano.shared(value=w_init,name='w',borrow=True) self.wT = self.w.T self.bVisible = bVisible self.bHidden = bHidden self.input = input self.params= (self.w,self.bVisible,self.bHidden) def GetHiddenValue(self,input): return T.nnet.sigmoid(T.dot(input,self.w)+self.bHidden) def GetReconstructedValue(self,selfOutput): return T.nnet.sigmoid(T.dot(selfOutput,self.wT)+self.bVisible) def CostFunction(self): corruptedData = self.GetCorrupted(self.input,level=0.2) selfOutput = self.GetHiddenValue(corruptedData) reStructedOutput = self.GetReconstructedValue(selfOutput) all_error = -T.sum(self.input*T.log(reStructedOutput)+(1-self.input)*T.log(1-reStructedOutput),axis=1) return T.mean(all_error) def GetCorrupted(self,input,level): numpy_rng = numpy.random.RandomState(123) theano_rng = RandomStreams(numpy_rng.randint(2**30)) return theano_rng.binomial(size=input.shape, n=1, p=1 -level) * input ####################################### ##global function def shared_dataset(data_xy): data_x, data_y = data_xy shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX)) shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX)) return shared_x, T.cast(shared_y, 'int32') def load_data(): f = gzip.open('mnist.pkl.gz','rb') train_set,valid_set,test_set = cPickle.load(f) f.close() train_x,train_y = shared_dataset(train_set) valid_x,valid_y = shared_dataset(valid_set) test_x,test_y = shared_dataset(test_set) return ((train_x,train_y),(valid_x,valid_y),(test_x,test_y)) if __name__ == '__main__': mydata = load_data() train_x,train_y = mydata[0] valid_x,valid_y = mydata[1] test_x,test_y = mydata[2] ##build model input = T.dmatrix("input") index =T.lscalar() learningRate = 0.1 batchSize = 20 nTrainBatch = train_x.get_value().shape[0]/batchSize epochs = 20 dAcode = dA(input,28*28,500) cost = dAcode.CostFunction() gparams = T.grad(cost,dAcode.params) updates = [(param,param-learningRate*gparam) for (param,gparam) in zip(dAcode.params,gparams)] train_model = theano.function( inputs = [index], outputs = cost, updates = updates, givens = {input:train_x[index*batchSize:(index+1)*batchSize]} ) for epoch in xrange(epochs+1): for currentBatch in xrange(nTrainBatch): error = train_model(currentBatch) print "epoch %i, bacth %i/%i, cost %f "%(epoch, currentBatch+1,nTrainBatch,error) image = Image.fromarray(utils.tile_raster_images(X=dAcode.w.get_value(borrow=True).T, img_shape=(28, 28), tile_shape=(10, 10), tile_spacing=(1, 1))) image.save('filters_corruption_30.png')
true
c45778084b8e62bce72eff4d0ced5bd55df4b69b
Python
ficksjr/programas-no-desktop
/Aula Python - Curso em video/Exercícios/desafiosiniciais/desafio053.py
UTF-8
557
4.46875
4
[]
no_license
# Exercício Python 53: Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os # espaços. Exemplos de palíndromos: frase = str(input('Digite a frase: ')).strip().upper() frase_separada = frase.split() print(frase_separada) frase_junta = ''.join(frase_separada) print(frase_junta) inverso = '' for letra in range(len(frase_junta)-1, -1, -1): inverso += frase_junta[letra] print('{}'.format(inverso)) if inverso == frase_junta: print('Temos um palíndromo') else: print('Não temos um palíndromo')
true
132c93735dfe9a60f514f6b8f28f26bf79d6e7f0
Python
JarvanIV4/pytest_hogwarts
/练习/CMB/02_04 list_dict_test/深拷贝与浅拷贝.py
UTF-8
1,285
3.640625
4
[]
no_license
import copy aList1=[2,3,["23",32]] aList2=aList1 #直接复制,aList2等同于aList1 aList3=copy.copy(aList1) #浅拷贝,aList3的地址与aList1不同,但是里面的所有元素的地址也是一样的 aList4=copy.deepcopy(aList1) #深拷贝,aList4的地址与aList1不同,里面的可变元素地址也不一样,不可变元素的地址一样 print("列表内存地址:",id(aList1),id(aList2),id(aList3),id(aList4)) print("列表可变元素地址:") print(id(aList1[2])) print(id(aList2[2])) print(id(aList3[2])) print(id(aList4[2])) print("列表不可变元素地址:") print(id(aList1[1])) print(id(aList2[1])) print(id(aList3[1])) print(id(aList4[1])) #改变列表中元素值 aList3[1]=0 #aList3改变了不可变元素的值,产生新值,改变后aList3[1]指向新地址,与aList1[1]已经不同 aList3[2][1]=4 #aList3改变了可变元素的值,未产生新的列表,改变后aList3[2]还是指向旧地址,与aList1[2]地址一样 aList4[2][1]=5 #aList4改变了可变元素的值,未产生新的列表,但是经过深拷贝后aList4[2]本来就和aList1[2]地址不一样,所以aList4[2]的变化与aList1[2]无关系 print("变化后列表的值:") print(aList1) print(aList2) print(aList3) print(aList4)
true
40bbcbb09a2c8e6f065e2b52eb4a90bc7beb6597
Python
ZordoC/How-to-Think-Like-a-ComputerScientist-Learning-with-Pytho3-and-Data-Structures
/alice.py
UTF-8
920
3
3
[]
no_license
import string import re with open('alice_in_wonderland.txt', 'r') as file: data = file.read().replace('\n', '') def remove_punctation(phrase): text_sans_punct = "" for letter in phrase: if letter not in string.punctuation: text_sans_punct += letter return text_sans_punct #data.translate(str.maketrans('', '', string.punctuation)) data = data.lower() #l = re.sub("[^\w]", " ", data) #re.sub(pattern, repl, string, count=0, flags=0) wordList = ([re.sub('[^a-z]+', '', _) for _ in data.split()]) print(wordList) #print(wordsList) wordcount = {} for word in wordList: if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 word_count_l = list(wordcount.items()) # word_count_l.sort() # word_count = dict(word_count_l) print(wordcount) # for key,value in word_count.items(): # print ( value, ":" , key )
true
bff4fc0573edba60b486d1cc105dff7572c44706
Python
mayankgureja/TwistedChatServerClient
/twistedChatClient.py
UTF-8
1,245
2.859375
3
[]
no_license
""" twistedChatClient.py Mayank Gureja 02/14/2013 ECEC 433 """ from twisted.internet import reactor, protocol, stdio from twisted.protocols.basic import LineReceiver class Server(LineReceiver): def connectionMade(self): self.factory = ChatClientFactory() self.connector = reactor.connectTCP('localhost', 22222, self.factory) def dataReceived(self, line): self.handle_CHAT(line) def handle_CHAT(self, message): if message and message.rstrip() != "quit()": self.connector.transport.write(message.rstrip() + '\r\n') else: print "\n* Goodbye! *\n" self.connector.transport.loseConnection() class ChatClient(LineReceiver): def connectionMade(self): print "INFO: Connected to server", self.transport.getPeer().host def lineReceived(self, line): print line class ChatClientFactory(protocol.ClientFactory): protocol = ChatClient def clientConnectionFailed(self, connector, reason): print "INFO: Connection failed - Goodbye!" reactor.stop() def clientConnectionLost(self, connector, reason): print "INFO: Connection lost - Goodbye!" reactor.stop() stdio.StandardIO(Server()) reactor.run()
true
e327f567713264b6d36f1b095f81af3651508834
Python
bemu/diagnosis_covid19
/radiomics/lasso_try.py
UTF-8
2,539
2.578125
3
[ "MIT" ]
permissive
import seaborn as sns import pandas as pd import matplotlib.pyplot as plt import numpy as np import matplotlib from sklearn.metrics import mean_squared_error from sklearn.linear_model import Lasso,LassoCV,LassoLarsCV from sklearn.model_selection import cross_val_score def rmse_cv(model): rmse= np.sqrt(-cross_val_score(model, df, cls, scoring="neg_mean_squared_error", cv = 3)) return(rmse) sns.set() #sns.load_dataset("flights") #df = sns.load_dataset("iris") # Load the brain networks example dataset df = pd.read_csv("R_withfake_features.csv",error_bad_lines=False) cls=df.pop('label') id=df.pop('id') #M=df.max()._values #m=df.min()._values #np.save('M.npy',M) #np.save('m.npy',m) #df=(df - df.min()) / (df.max() - df.min()) #id_small=id[0:id.size:20] lut = dict(zip(cls.unique(), "rbg")) row_colors = cls.map(lut) sns.clustermap(df, row_colors=row_colors,standard_scale=1,figsize=(20, 20)) plt.title('Cluster Heatmap of Features Before LASSO',x=10,y=1,fontsize=20) plt.savefig("BeforeCHM.jpg") corr = df.corr() f,ax= plt.subplots(figsize = (15, 15),nrows=1) # cubehelix mapÑÕÉ«/home/cwx/extra/MVI-R sns.heatmap(corr, ax = ax, vmax=1, vmin=-1) ax.set_title('Corr Matrix Before LASSO',fontsize=20) f.savefig('corr_heatmap_before.jpg', bbox_inches='tight') #plt.show() model = Lasso(alpha=0.6) model.fit(df._values, cls._values) coef = pd.Series(model.coef_, index = df.columns) coef[coef.abs()<1e-4]=0 print("Lasso picked " + str(sum(coef != 0)) + " variables and eliminated the other " + str(sum(coef == 0)) + " variables") #print(rmse_cv(model).mean()) after_df = df.iloc[:,(coef!=0)._values] # matplotlib colormap f,ax= plt.subplots(figsize = (7, 7),nrows=1) sns.heatmap(after_df.corr(), ax = ax, vmax=1, vmin=-1,) ax.set_title('Corr Matrix After LASSO',fontsize=20) f.savefig('corr_heatmap_after.jpg', bbox_inches='tight') #plt.show() sns.clustermap(after_df, row_colors=row_colors,standard_scale=1,figsize=(10, 20)) plt.title('Cluster Heatmap of Features After LASSO',x=10,y=1,fontsize=20) plt.savefig("After_CHM.jpg") imp_coef = coef[coef!=0] #imp_coef.sort() name=np.where(coef!=0)[0] co=imp_coef.values saving=np.save('coefs.npy',np.stack([name,co],-1)) #matplotlib.rcParams['figure.figsize'] = (8.0, 10.0) plt.figure(figsize=(10,6)) imp_coef.plot(kind = "barh",fontsize=7) print(imp_coef.keys()) plt.subplots_adjust(left=0.5, wspace=0.2, hspace=0.2) #print(imp_coef.values) plt.axis('tight') plt.title("Coefficients in the Lasso Model",fontsize=20) plt.savefig("CIM.jpg", bbox_inches='tight') #plt.show()
true
369a9d97fef179f3eec057598085dae206065326
Python
sotkahey/myfirstproject
/zadanie1.py
UTF-8
386
3.5
4
[]
no_license
import random b = input('введите число') a = random.randint(0, 50) if a<b: print('случайное число меньше пограничного') else: if ((a*3)>b): print('случайное число больше пограничного в 3 раза') else: print('случайное число больше пограничного')
true
d16a704922d3efe9726a8a921082db6001ac8e40
Python
Arun44/Fundamentals-Of-Computing-Specialization
/Course1/Week3/Guess-The-Number.py
UTF-8
2,852
3.875
4
[]
no_license
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random reset = 1; secret_number = 0; num_of_guess = 0; # helper function to start and restart the game def new_game(range): # initialize global variables used in your code here global reset; global secret_number; global num_of_guess; if (range == 1000): print "****New Game starts with Range [0,1000)****\n"; num_of_guess = 10; reset = 0; secret_number = random.randrange(0, 1000); print "Number of Remaining Guesses is", num_of_guess; elif (range == 100): print "****New Game starts with Range [0,100)****\n"; num_of_guess = 7; reset = 1; secret_number = random.randrange(0, 100); print "Number of Remaining Guesses is", num_of_guess; # print secret_number; print "\n"; # define event handlers for control panel def range100(): # button that changes the range to [0,100) and starts a new game print "The Game Range has been changed to Range[0,100)"; new_game(100); def range1000(): # button that changes the range to [0,1000) and starts a new game print "The Game Range has been changed to Range[0,1000)"; new_game(1000); def input_guess(guess): # main game logic goes here guess = int(guess); global num_of_guess; print "Guess was", guess if (guess > secret_number): num_of_guess = num_of_guess - 1; print "Number of Available Guesses is", num_of_guess; print "Lower\n"; if (num_of_guess == 0): print "Game Lost,Zero guesses available"; if (reset == 0): new_game(1000); else: new_game(100); elif (guess < secret_number): num_of_guess = num_of_guess - 1; print "Number of Available Guesses is", num_of_guess; print "Higher\n"; if (num_of_guess == 0): print "Game Lost,Zero guesses available"; if (reset == 0): new_game(1000); else: new_game(100); else: num_of_guess = num_of_guess - 1; print "Number of Available Guesses is", num_of_guess; print "Correct\n"; if (reset == 0): new_game(1000); else: new_game(100); # create frame frame = simplegui.create_frame("Guess the number Game", 250, 250); frame.add_input("Enter the number", input_guess, 100); frame.add_button("RANGE [0,100)", range100); frame.add_button("RANGE [0,1000)", range1000); # register event handlers for control elements and start frame frame.start(); # call new_game new_game(100); # always remember to check your completed program against the grading rubric
true
f4423c13680a8864c320325f934282c1ae26f685
Python
shen-huang/selfteaching-python-camp
/exercises/1901100100/take_num_from_string.py
UTF-8
2,626
3.3125
3
[]
no_license
import re symlist = ["/","*"] string=input("请输入运算等式") #re.findall(r"\d+\.?\d*",string) num = (re.findall(r"\d+\.?\d*",string)) #获取列式中的数字 print(num) sym = re.findall(r"\W*",string) #获取列式中的运算符 sym.remove("") for i in sym: sym.remove("") print(sym) #symbol = re.findall(r"\[/-]*",string) #print (re.findall(r"\\+?",string))list(set(a).difference(set(b))) def caculator(num,sym): num1 = num sym1 = sym #now I know the sentences is useless if len(num1) - len(sym1)!=1: return False while set(sym1).intersection(set(symlist))!=set(): #caculate until the symbol is none of * or / a = set(sym1).intersection(set(symlist)) #use it to debug ,it is also useless print(a) for i in sym1: print (i) #check the list is correct n = sym.index(i) if i == "*" or i == "/": #the multipy and the divided caculator is privilege if i == '*': num1[n] = str(float(num1[n]) * float(num1[n+1])) #multiply or divided print (num[n]) del num1[n+1] del sym[n] print(sym1) print(num1) elif i == '/': num1[n] = str(float(num[n]) / float(num[n+1])) #multiply or divided print (num[n]) del num1[n+1] del sym[n] print(sym1) print(num1) while sym1!=[]: #caculate until the symbol is none for i in sym1: print (i) #check the list is correct n = sym.index(i) if i == "+" or i == "-": if i == '+': num1[n] = str(float(num1[n]) + float(num1[n+1])) #plus or abtract print (num[n]) del num1[n+1] del sym[n] print(sym1) print(num1) if i == '-': num1[n] = str(float(num[n]) - float(num[n+1])) #plus or abtract print (num[n]) del num1[n+1] del sym[n] print(sym1) print(num1) return float(num1[0]) result = caculator(num,sym) print(result)
true
a6a39f4e91c0cee2444ce2028455a6dbe38f9a3c
Python
leducanh300795/c4e17-New-Cause-old-one-got-retk-so-bad-
/Fundamental/Session2/sum.py
UTF-8
115
3.203125
3
[]
no_license
n = int (input("Enter a number ? " )) a = range (n + 1) #khoang, day so b = sum(a) #khong chay: sum (0,n) print(b)
true
35e07ae72030c74215f81f9a696ab06797cd06c0
Python
hlku/ooxx-variation
/ooxx_ab.py
UTF-8
5,756
2.859375
3
[]
no_license
#!/usr/bin/python # -*- coding: UTF-8 -*- import random import sys difficulty = 0 def calculate(tsumeru, limit): for i in range(0, 9) : # optimization for only move if tsumeru[i] != 0 : continue pos = list(tsumeru) pos[i] = max(pos) + 1 if check(pos) : return i # win move! pos = list(tsumeru) pos[i] = max(pos) + 2 if check(pos) : return i # be ware! solution = set([9]) value = -100 for nx in expand(tsumeru) : v = findMin(nx, limit, 1, value) if value == v : solution.add(nx.index(max(nx))) elif value < v : solution = set([nx.index(max(nx))]) value = v print (solution, value) #for debug return list(solution)[random.randint(0, len(solution) - 1)] def findMin(tsumeru, limit, depth, MAX) : value = 100 if check(tsumeru) : return 99 - depth elif depth >= limit : return 0 for nx in expand(tsumeru) : value = min(value, findMax(nx, limit, depth + 1, value)) if value < MAX : return value return value def findMax(tsumeru, limit, depth, MIN) : value = -100 if check(tsumeru) : return -99 + depth elif depth >= limit : return 0 for nx in expand(tsumeru) : value = max(value, findMin(nx, limit, depth + 1, value)) if value > MIN : return value return value def expand(pos) : def rotate(t) : return [t[6], t[3], t[0], t[7], t[4], t[1], t[8], t[5], t[2]] def mirror(t) : return [t[2], t[1], t[0], t[5], t[4], t[3], t[8], t[7], t[6]] biggest = max(pos) ret = [] for i in range(0, 9) : if pos[i] == 0 : tmp = list(pos) tmp[i] = biggest + 1 fresh(tmp) if tmp.count(0) > 3 : if rotate(tmp) in ret or \ rotate(rotate(tmp)) in ret or \ rotate(rotate(rotate(tmp))) in ret or \ mirror(tmp) in ret or \ mirror(rotate(tmp)) in ret or \ mirror(rotate(rotate(tmp))) in ret or \ mirror(rotate(rotate(rotate(tmp)))) in ret : pass else : ret.append(tmp) else : ret.append(tmp) return ret def fresh(board) : if max(board) == 8 and board.count(2) == 0 : pass elif board.count(0) < 3 or (max(board) == 7 and board.count(2) == 0): tmp = list() for i in board: if i == 0 : tmp.append(99) else : tmp.append(i) board[tmp.index(min(tmp))] = 0 def check(board) : k = lambda a, b, c : True if \ (board[a] % 2 == board[b] % 2 == board[c] % 2) and \ board[a] != 0 and board[b] != 0 and board[c] != 0 \ else False if k(0, 1, 2) or k(3, 4, 5) or k(6, 7, 8) or k(0, 3, 6) or \ k(1, 4, 7) or k(2, 5, 8) or k(0, 4, 8) or k(2, 4, 6) : return True return False def play(board, step, add = 1) : board[step] = max(board) + add fresh(board) def display(board) : global difficulty q = list() for i in board : if i == 0 : q.append(' ') else : if difficulty < 3 : k = '%2d' % tuple([i]) if i % 2 == 1: k2 = '\033[1;32m' + k + '\033[0m' else : k2 = '\033[1;36m' + k + '\033[0m' q.append(k2) elif difficulty < 5 : q.append('%2d' % tuple([i])) else : if i % 2 == 1 : q.append('O') else : q.append('X') if max(board) != 0 : q[board.index(max(board))] = \ '\033[41m' + q[board.index(max(board))] + '\033[0m' p = '''\ +--+--+--+ |%s|%s|%s| +--+--+--+ |%s|%s|%s| +--+--+--+ |%s|%s|%s| +--+--+--+ ''' print '\n' + p % tuple(q), def main(): global difficulty while True: print "choose computer's level" print '\t3~4 play with 1 color, 5~6 play without numbers' print '\tlevel 0, computer thinks 3 steps' print '\twith each higher level, computer thinks more 2 steps' difficulty = int(raw_input('level : ')) if difficulty < 0 or difficulty > 6 : print 'error input!' continue else : hard = 3 + difficulty * 2 break while True: print '\nchoose a mode' print '\t-2 : computer start with 2 steps' print '\t-1 : computer go first' print '\t 0 : random' print '\t 1 : you go first' print '\t 2 : you start with 2 steps' mode = int(raw_input('mode : ')) if mode < -2 or mode > 2 : print 'error input!' continue else : break board = [0] * 9 if mode == -2 : play(board, calculate(board, hard)) play(board, calculate(board, hard), 2) elif mode == -1 : play(board, calculate(board, hard)) elif mode == 0 and random.randint(0, 1) == 0: play(board, calculate(board, hard)) while True: display(board) if check(board) : print 'computer win!' break elif max(board) >= 50 : print 'tie!' break step = int(raw_input('input the position (1-9): ')) - 1 if step < 0 or step > 8 or board[step] != 0 : print "illegal!!" continue if mode == 2 and max(board) == 1: play(board, step, 2) else : play(board, step) if mode == 2 and max(board) == 1: continue display(board) if check(board) : print 'you win!' break play(board, calculate(board, hard)) if __name__ == '__main__': main()
true
93a0b6ddc0fe94aa5bb6a8a47c6b84250c152708
Python
yeeSilver/mogja.github.io
/practice.py
UTF-8
190
2.71875
3
[]
no_license
lion_we_know = ['colin' ,'shawn', 'zayn mailk'] lion_meet = ['chris' , 'lion' ,'kelly'] for lion in lion_meet: if lion in lion_we_know: print("hi") else: print("harry potter")
true
ba362d5181f8d2c542911aa3ac10de0873882a25
Python
a7031x/e-net
/preprocess.py
UTF-8
5,466
2.6875
3
[]
no_license
import re import spacy import ujson as json import numpy as np import tensorflow as tf import config import pickle from tqdm import tqdm from collections import Counter from utils import mkdir, save_json nlp = spacy.blank("en") def remove_invalid_chars(text): return text.replace("''", '" ').replace("``", '" ') def word_tokenize(sent): doc = nlp(sent) return [token.text for token in doc] def convert_idx(text, tokens): current = 0 spans = [] for token in tokens: current = text.find(token, current) if current < 0: print("Token {} cannot be found".format(token)) raise Exception() spans.append((current, current + len(token))) current += len(token) return spans def string_features(passage, word_counter=None, char_counter=None): passage = remove_invalid_chars(passage) tokens = word_tokenize(passage) chars = [list(token) for token in tokens] if word_counter is not None: for token in tokens: word_counter[token] += 1 for char in token: char_counter[char] += 1 return passage, tokens, chars def process_word_embedding(word_counter): embedding_dict = {} with open(config.word_emb_file, 'r', encoding='utf8') as file: for line in file: array = line.split() word = ''.join(array[:-config.word_emb_dim]) if word in word_counter: vector = list(map(float, array[-config.word_emb_dim:])) assert(len(vector) == 300) embedding_dict[word] = vector words = sorted(embedding_dict.keys()) w2i = {token:idx for idx, token in enumerate(words, 2)} w2i[config.NULL] = 0 w2i[config.OOV] = 1 i2w = {k:v for v,k in w2i.items()} embedding_dict[config.NULL] = [0. for _ in range(config.word_emb_dim)] embedding_dict[config.OOV] = [0. for _ in range(config.word_emb_dim)] word_embeddings = [embedding_dict[i2w[i]] for i in range(len(embedding_dict))] return word_embeddings, w2i def process_char_embedding(char_counter): c2i = { config.NULL: 0, config.OOV: 1 } for char in char_counter: c2i[char] = len(c2i) char_embeddings = [np.random.normal(scale=0.01, size=config.char_emb_dim) for _ in range(len(c2i))] return char_embeddings, c2i def process_dataset(filename, word_counter, char_counter): examples = [] with open(filename, 'r', encoding='utf8') as file: source = json.load(file) for article in tqdm(source['data']): for para in article['paragraphs']: context, context_tokens, _ = string_features(para['context'], word_counter, char_counter) spans = convert_idx(context, context_tokens) for qa in para['qas']: _, question_tokens, _ = string_features(qa['question'], word_counter, char_counter) answers = [] cl_answers = [] for answer in qa['answers']: answer_text = answer['text'] answer_start = answer['answer_start'] answer_end = answer_start + len(answer_text) answer_span = [] for idx, span in enumerate(spans): if not (answer_end <= span[0] or answer_start >= span[1]): answer_span.append(idx) answer_span = answer_span[0], answer_span[-1] if answer_span not in answers: answers.append(answer_span) cl_answers.append((answer_start, answer_end)) example = { 'passage_tokens': context_tokens, 'question_tokens': question_tokens, 'answer_starts': [s for s,_ in answers], 'answer_ends': [s for _,s in answers], 'cl_answer_starts': [s for s,_ in cl_answers], 'cl_answer_ends': [s for _,s in cl_answers] } examples.append(example) return examples def build_features(examples, filename): with open(filename, 'wb') as file: pickle.dump(examples, file) if __name__ == '__main__': mkdir('./generate/squad') word_counter = Counter() char_counter = Counter() print('extracting examples...') train_examples = process_dataset(config.train_file, word_counter, char_counter) dev_examples = process_dataset(config.dev_file, word_counter, char_counter) dev_examples, test_examples = dev_examples[:len(dev_examples)//2], dev_examples[len(dev_examples)//2:] print('creating embeddings...') word_embeddings, w2i = process_word_embedding(word_counter) char_embeddings, c2i = process_char_embedding(char_counter) print('#word: {}, #char: {}'.format(len(word_embeddings), len(char_embeddings))) print('saving files...') build_features(train_examples, config.train_record_file) build_features(dev_examples, config.dev_record_file) build_features(test_examples, config.test_record_file) save_json(config.word_embeddings_file, word_embeddings) save_json(config.char_embeddings_file, char_embeddings) save_json(config.w2i_file, w2i) save_json(config.c2i_file, c2i) print('done.')
true
0613048efd949826945c95b4e873d86b8ac01716
Python
papaganesha/prog3
/Heranca/01/Gerente.py
UTF-8
427
3.046875
3
[]
no_license
from Funcionario import * class Gerente(Funcionario): def __init__(self, cod_func, nome, salario, departamento): Funcionario.__init__(self, cod_func, nome, salario) self.departamento = departamento def get_Gerente(self): print("Gerente:\n cod_func: {}\n nome: {}\n salario: R${}\n departamento: {}".format(self.cod_func, self.nome, self.salario, self.departamento))
true