repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
ThatTallProgrammer/firstdevops
https://github.com/ThatTallProgrammer/firstdevops
6ce0d6c1720dfb67f252b501fbd286f1d4518f7d
2c3e30d15cff451da05a5493ccc43c7b601838b2
f3060c8b6290c8c8e6e5fd259de599774427b79a
refs/heads/master
2023-03-01T15:59:54.654382
2021-01-25T00:25:02
2021-01-25T00:25:02
332,588,976
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7758620977401733, "alphanum_fraction": 0.7758620977401733, "avg_line_length": 28, "blob_id": "3f19517d165a4cbe49f7583e540e0a69508dd477", "content_id": "d3b579ba71aef94b14ea4ccd42926991c5c14aa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 116, "license_type": "no_license", "max_line_length": 43, "num_lines": 4, "path": "/firstapp/urls.py", "repo_name": "ThatTallProgrammer/firstdevops", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.urls import include, path\n\npath('firstapp/', include('firstapp.urls'))\n" } ]
1
SunneyF/github_trial
https://github.com/SunneyF/github_trial
06609d448f3e63a356a41ae4b66909a7743acefe
9adef8465790b895f31c77ed4c751a8c4bd0884c
ecb3d36f16e7f963e131e64851b09739fe3cb358
refs/heads/main
2022-12-25T20:31:55.968669
2020-10-02T09:24:59
2020-10-02T09:24:59
300,557,535
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.47029340267181396, "alphanum_fraction": 0.4965812563896179, "avg_line_length": 34.872703552246094, "blob_id": "b7124a7af5ee067517f10670bb0924aa057dffdd", "content_id": "2df33cc75094f915aa3dcb3ba7a62833fee4a065", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 30130, "license_type": "no_license", "max_line_length": 247, "num_lines": 817, "path": "/Accelerating_Benders_Classical_03_15_test.py", "repo_name": "SunneyF/github_trial", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 29 09:39:16 2020\r\n\r\n@author: sunney\r\n\"\"\"\r\n# Pseudocode for CCB algorithm \r\n# source:G. K. D. Saharidis et al. / Intl. Trans. in Op. Res. 17 (2010) 221–237\r\n#tic = time.time() \r\ndef switchLabel(x):\r\n return{\r\n 1:'LT',\r\n 2:'ST',\r\n 3:'T',\r\n 4:'LM',\r\n 5:'SM',\r\n 6:'MTC',\r\n 7:'D'\r\n }[x]\r\n\r\ndef unique(list1): \r\n \r\n # insert the list to the set \r\n list_set = set(list1) \r\n # convert the set to the list \r\n unique_list = (list(list_set)) \r\n return unique_list\r\n\r\n\r\nimport gurobipy as grb \r\nimport numpy as np\r\nimport csv\r\nT=3\r\nA=480\r\n# Extracting data from txt files ############################################\r\n\r\n# Inputs required ---------------------------------------------------------- \r\ncost_vector = [1,2,3,4] # qualification cost levels\r\n# -------- Machines ---------------------------------------------------------\r\n\r\n# 1. KO (ComponentArea) # dictionary\r\n# 2. Work_Center_ID (code for the work center)\r\n# 3. ComponentAreaToMachine till exempel: {1:[1,3,5,10], 2: [97, 74,...],....}\r\n # key is the code of the component area and values contain a vector of\r\n # all the machines in respective component area\r\n \r\n# 4. Categories = [1,2] refers to the machine category\r\n# 5. CategoriesToMachine = {1:[1,3,5,10], 2: [97, 74,...],....}\r\n# 6. Number of equipments per work center = {1:1,...., 5:21, ...}\r\n \r\nf= open(\"MachineData.txt\",\"r\")\r\nf1 = f.readlines()\r\nKO ={}\r\nWork_Center_ID = []\r\nComponentAreaToMachine = {}\r\nCategories = []\r\nCategoriesToMachine = {}\r\nMachineToCatTuple = grb.tuplelist()\r\nNumberofEquipments = {}\r\nNumberofComponentAreas = 10\r\n\r\nwith open('MachineData.txt') as csv_file:\r\n csv_reader = csv.reader(csv_file, delimiter=',')\r\n line_count = 0\r\n for row in csv_reader:\r\n# print(row[3])\r\n Work_Center_ID.append(int(row[0]))\r\n ComponentAreaToMachine[int(row[0])] = int(row[3])\r\n CategoriesToMachine[int(row[0])] = int(row[1])\r\n MachineToCatTuple+=[(int(row[0]),int(row[1]))] \r\n Categories.append(int(row[1]))\r\n NumberofEquipments[int(row[0])] = int(row[2])\r\nCategories = unique(Categories) \r\nComponentAreas = range(1,NumberofComponentAreas+1)\r\n \r\n# --------Part type--------------------------------------------------------\r\n# 6. PartType = [1:...]\r\n# JobTypeData = {'1': [100,400,500,600], '2':[100,200,300], '3':[100,200],...} \r\n# Pijk = grb.tuplelist([(1,100,work_center_id, 10.0),..,..]}\r\nPartType = []\r\n\r\n#dictLists = dict((key, []) for key in [\"xcg\", \"bsd\", ...])\r\n\r\nwith open('ProcessingTime.txt') as csv_file:\r\n csv_reader = csv.reader(csv_file, delimiter=',')\r\n line_count = 0\r\n for row in csv_reader:\r\n PartType.append(int(row[0]))\r\ncsv_file.close() \r\nPartType = unique(PartType) \r\nJobTypeData = dict((key, []) for key in PartType) \r\nPijk = grb.tuplelist() \r\n\r\nwith open('ProcessingTime.txt') as csv_file:\r\n csv_reader = csv.reader(csv_file, delimiter=',')\r\n line_count = 0\r\n for row in csv_reader:\r\n \r\n JobTypeData[int(row[0])].append(int(row[1]))\r\n Pijk+= [(int(row[0]),int(row[1]),int(row[2]),float(row[3]))]\r\ncsv_file.close()\r\n\r\nfor key in JobTypeData.keys():\r\n JobTypeData[key]= unique(JobTypeData[key])\r\n#-----------Qualification cost --------------------------------------------\r\n\r\n# set the qualification cost to zero for machines which have been used before\r\n \r\nOmega = grb.tuplelist() \r\nQualCost={}\r\nJobsToCategories = dict(((i,j), []) for i in PartType for j in JobTypeData[i] )\r\n\r\nfor i in PartType:\r\n for j in JobTypeData[i]:\r\n for k in Pijk.select(i,j,'*','*'):\r\n \r\n JobsToCategories[i,j].append(CategoriesToMachine[k[2]])\r\n Omega+=[(i,j,k[2])] # qualified machines(i,j,k)\r\n QualCost[i,j,k[2]] =0 \r\nfor key,value in JobsToCategories.items():\r\n \r\n JobsToCategories[key] = unique(value)\r\n\r\n# find set of machines for each i,j where Lambda_ijk =1 and Omega_ijk =0\r\nNotQualified = dict(((key1,key2), []) for key1 in PartType for key2 in JobTypeData[key1]) \r\n\r\nfor i in PartType:\r\n for j in JobTypeData[i]:\r\n K_qualified=[]\r\n for kk in Omega.select(i,j,'*'):\r\n #print(kk[2])\r\n K_qualified.append(kk[2])\r\n for k in Work_Center_ID:\r\n d = MachineToCatTuple.select(k,'*')\r\n \r\n if (d[0][1] in JobsToCategories[i,j]):\r\n \r\n if not(k in K_qualified):\r\n NotQualified[i,j].append(k) \r\n NotQualified[i,j] = unique(NotQualified[i,j])\r\n\r\nfor i,j in NotQualified.keys():\r\n for k in NotQualified[i,j]:\r\n QualCost[i,j,k]= np.random.permutation(cost_vector)[0]\r\n\r\nFeasibleMachines = dict(((key1,key2), []) for key1 in PartType for key2 in JobTypeData[key1])\r\n\r\nfor i in PartType:\r\n for j in JobTypeData[i]:\r\n for k in Pijk.select(i,j,'*','*'):\r\n FeasibleMachines[i,j].append(k[2])\r\n for k2 in NotQualified[i,j]:\r\n FeasibleMachines[i,j].append(k2)\r\nfor i in PartType:\r\n for j in JobTypeData[i]:\r\n FeasibleMachines[i,j] = unique(FeasibleMachines[i,j])\r\n# Demand data\r\nDemand = dict(((key1,key2,key3), []) for key1 in PartType for key2 in JobTypeData[key1] for key3 in range(1,T+1)) \r\ncnt=0 \r\n\r\n# create a dictionary for categories to machines\r\nCatMachList = dict(((key1), []) for key1 in Categories)\r\nfor c in Categories:\r\n for k in MachineToCatTuple.select('*',c):\r\n CatMachList[c].append(k[0])\r\n \r\nwith open('DemandData.txt') as csv_file:\r\n csv_reader = csv.reader(csv_file, delimiter=',')\r\n line_count = 0\r\n \r\n for row in csv_reader:\r\n if ((int(row[0]) not in PartType) or (int(row[1]) not in JobTypeData[int(row[0])]) or (int(row[4]) <= 0)): # for those where processing time too less\r\n \r\n cnt+=1\r\n continue\r\n if(int(row[3]) <= 3):\r\n if (int(row[2]) == 2016):\r\n Demand[int(row[0]),int(row[1]),1].append(int(row[4]))\r\n elif (int(row[2]) == 2017):\r\n Demand[int(row[0]),int(row[1]),1+4].append(int(row[4]))\r\n else:\r\n Demand[int(row[0]),int(row[1]),1+8].append(int(row[4]))\r\n \r\n elif((int(row[3]) >= 4) & (int(row[3]) <= 6)):\r\n if (int(row[2]) == 2016):\r\n Demand[int(row[0]),int(row[1]),2].append(int(row[4]))\r\n elif (int(row[2]) == 2017):\r\n Demand[int(row[0]),int(row[1]),2+4].append(int(row[4]))\r\n else:\r\n Demand[int(row[0]),int(row[1]),2+8].append(int(row[4]))\r\n \r\n elif((int(row[3]) >= 7) & (int(row[3]) <= 9)):\r\n \r\n if (int(row[2]) == 2016):\r\n Demand[int(row[0]),int(row[1]),3].append(int(row[4]))\r\n elif (int(row[2]) == 2017):\r\n Demand[int(row[0]),int(row[1]),3+4].append(int(row[4]))\r\n else:\r\n Demand[int(row[0]),int(row[1]),3+8].append(int(row[4]))\r\n elif((int(row[3]) >= 10) & (int(row[3]) <= 12)):\r\n if (int(row[2]) == 2016):\r\n Demand[int(row[0]),int(row[1]),4].append(int(row[4]))\r\n elif (int(row[2]) == 2017):\r\n Demand[int(row[0]),int(row[1]),4+4].append(int(row[4]))\r\n else:\r\n Demand[int(row[0]),int(row[1]),4+8].append(int(row[4])) \r\n \r\n\r\n \r\ncsv_file.close()\r\n\r\n \r\nfor key in Demand.keys():\r\n Demand[key] = sum(Demand[key])\r\n \r\n# Capacity\r\n\r\nCapacity = {} \r\nfactor=1 # % additional time\r\nfor t in range(1,T+1):\r\n Capacity[1,t] = 5*5000*(1/4)\r\n Capacity[9,t] = 21*5000*(1/4)\r\n Capacity[116,t]= 3*5000*(1/4)\r\n Capacity[49,t] = 2*5000*(1/4)\r\n\r\nfor i in set(set(Work_Center_ID)-{1,9,116,49}):\r\n for j in range(1,T+1):\r\n Capacity[i,j] = 5000*(1/4)\r\n\r\n#Set the value of Processing time for not qualified machines as the max processing time +4 hours\r\nfor i in PartType:\r\n for j in JobTypeData[i]:\r\n maxs =0\r\n for k2 in Pijk.select(i,j,'*','*'):\r\n if k2[3] > maxs:\r\n maxs = k2[3]*factor\r\n for k in NotQualified[i,j]:\r\n Pijk+= [(i,j,k,maxs)]\r\n\r\n################################ End of Data ###############################\r\n \r\n \r\n################################ Parameters ##############################\r\n \r\nTau=3\r\nTheta=0.5\r\ngamma=10\r\nT=10\r\nthreshold = .7\r\ne= ((1-Theta)/(T*(1.0-threshold)))\r\nA=480\r\n#############################################################################\r\n\r\n\r\n#%%\r\nimport time\r\n\r\n# your code\r\n\r\n\r\ndef subproblem_t(t,s_var,x_var_t):\r\n # Input: s:= array of s[i,j,k,t] values and t is the time period\r\n model = grb.Model(\"TRA_SubProblem\") \r\n x_t ={}\r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n for k in FeasibleMachines[i,j]:\r\n if Demand[i,j,t] !=0:\r\n x_t[i,j,k] = model.addVar(vtype= grb.GRB.CONTINUOUS,lb=0.0)\r\n n_t = model.addVar(vtype = grb.GRB.CONTINUOUS,lb=0.0)\r\n model.setObjective(((Theta)/(T*(1.0-threshold)))*n_t,grb.GRB.MINIMIZE)\r\n Assignments_t = {}\r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n if Demand[i,j,t]!=0:\r\n Assignments_t[i,j] = model.addConstr(grb.quicksum(x_t[i,j,k] for k in FeasibleMachines[i,j]) >= max(0,Demand[i,j,t]),name=\"Assignments[%s]\" % (str(i) + \",\" + str(j)))\r\n\r\n sijkvariable_t = {}\r\n \r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n for k in NotQualified[i,j]:\r\n if Demand[i,j,t]!=0:\r\n sijkvariable_t[i,j,k] = model.addConstr(-x_t[i,j,k] >= -Demand[i,j,t]*max(0,s_var[i,j,k,t]),name= \"sijkvariable_t[%s]\" % (str(i) + \",\" + str(j) + \",\" + str(k)))\r\n \r\n \r\n MinmaxCategory_t={}\r\n\r\n for k in Work_Center_ID: \r\n MinmaxCategory_t[k] = model.addConstr(Capacity[k,t]*n_t - grb.quicksum(Pijk.select(i,j,k,'*')[0][3]*x_t[i,j,k] for i in PartType for j in JobTypeData[i] if (i,j,k) in x_t) >= -threshold*Capacity[k,t], name= \"MinmaxCategory_t[%s]\" % str(k))\r\n \r\n thres = model.addConstr(-n_t >= -1 + threshold, name= \"thres\")\r\n \r\n \r\n model.Params.InfUnbdInfo = 1\r\n model.Params.Method=1\r\n model.Params.DualReductions = 0\r\n model.Params.PrePasses = 1\r\n \r\n \r\n model.optimize()\r\n \r\n pi_t_Dual={}\r\n y_t_Dual ={}\r\n mu_t_Dual={}\r\n d_t_Dual=0\r\n Stage2_Cost_t=0\r\n pi_t_Dual_ray ={}\r\n y_t_Dual_ray ={}\r\n mu_t_Dual_ray = {}\r\n d_t_Dual_ray = 0\r\n status= model.status\r\n rays =0\r\n \r\n if (status==grb.GRB.Status.INFEASIBLE): # https://www.gurobi.com/documentation/9.0/refman/optimization_status_codes.html\r\n rays=1\r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n if (i,j) in Assignments_t:\r\n pi_t_Dual_ray[i,j] = -Assignments_t[i,j].FarkasDual\r\n \r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n for k in FeasibleMachines[i,j]:\r\n if (i,j,k) in sijkvariable_t:\r\n y_t_Dual_ray[i,j,k]= -sijkvariable_t[i,j,k].FarkasDual\r\n \r\n for k in Work_Center_ID:\r\n if k in MinmaxCategory_t: \r\n mu_t_Dual_ray[k]= -MinmaxCategory_t[k].FarkasDual\r\n \r\n d_t_Dual_ray = -thres.FarkasDual\r\n# print('The model is infeasible; computing IIS')\r\n# model.computeIIS()\r\n# print('\\nThe following constraint(s) cannot be satisfied:')\r\n# \r\n# for c in model.getConstrs():\r\n# if c.IISConstr:\r\n# print('%s' % c.constrName)\r\n# exit(0) \r\n\r\n \r\n \r\n else:\r\n \r\n \r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n if (i,j) in Assignments_t:\r\n pi_t_Dual[i,j] = Assignments_t[i,j].Pi\r\n \r\n \r\n \r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n for k in FeasibleMachines[i,j]:\r\n if (i,j,k) in sijkvariable_t:\r\n y_t_Dual[i,j,k] = sijkvariable_t[i,j,k].Pi\r\n \r\n \r\n for k in Work_Center_ID:\r\n if k in MinmaxCategory_t:\r\n mu_t_Dual[k] = MinmaxCategory_t[k].Pi\r\n \r\n d_t_Dual = thres.Pi\r\n Stage2_Cost_t = model.objVal\r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n for k in FeasibleMachines[i,j]:\r\n if (i,j,k) in x_t:\r\n x_var_t[i,j,k] = x_t[i,j,k].X \r\n # find extreme rays of the dual\r\n # output scenarios\r\n # 1. Primal feasible => rays are empty since dual is bounded; update Stage2_Cost\r\n # 2. Primal infeasible => 1 - Dual is unbounded => find the extreme rays which leads to unboundedness (Farkas Dual)\r\n # 2 - Dual is infeasible => we assume primal sub-problem is always bounded and thus dual is feasible\r\n # rays ==1 means primal sub-problem is infeasible thus, we generate feasibility cut\r\n return rays,pi_t_Dual,mu_t_Dual,y_t_Dual,d_t_Dual,pi_t_Dual_ray,mu_t_Dual_ray,y_t_Dual_ray,d_t_Dual_ray,Stage2_Cost_t,x_var_t # \\pi^{t}_{ij}, \\mu^{t}_{k\\in \\mathcal{K}}, y^{t}_{ijk} (i,j);k\\in K_j, d^{t}_k\r\n##############-----------------Dual Sub-problem End---------------------------------------------------------\r\n# custom optimize() function that uses callback\r\n \r\ndef mycallback(model, where): # https://www.gurobi.com/documentation/9.0/examples/cb_py.html\r\n\r\n if where == grb.GRB.Callback.MIPSOL:\r\n # General MIP callback\r\n objbnd = model.cbGet(grb.GRB.Callback.MIPSOL_OBJBND) # Current best objective bound. MIPSOL_OBJBST\r\n objbst = model.cbGet(grb.GRB.Callback.MIPSOL_OBJBST)\r\n if (objbnd > -grb.GRB.INFINITY and model._lowerbounds >= objbst) :\r\n \r\n model.terminate()\r\n return\r\nBestLowerBounds={}\r\nBestUpperBounds = {}\r\nTimeLapse= {}\r\nstoreQual = {}\r\nfor iter in range(1,2): \r\n print('New Iteration-%d' %(iter))\r\n start_time = time.time()\r\n Theta=0.9\r\n nCUT=0\r\n gamma=10\r\n T=12\r\n A=gamma*T\r\n threshold=0.7\r\n \r\n # Start\r\n model = grb.Model('Master-Problem-TRA')\r\n s = {}\r\n z= {}\r\n o ={}\r\n \r\n \r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n for k in NotQualified[i,j]:\r\n for t in range(1,T+1):\r\n if Demand[i,j,t]!=0:\r\n s[i,j,k,t] = model.addVar(vtype=grb.GRB.BINARY,lb=0.0)\r\n \r\n z[i,j,k,t] = model.addVar(vtype=grb.GRB.BINARY)\r\n \r\n for t in range(1,T+1):\r\n o[t]= model.addVar(vtype=grb.GRB.CONTINUOUS,lb=0.0)\r\n \r\n #model.setObjective(((1-Theta)/A)*grb.quicksum(QualCost[i,j,k]*z[i,j,k,t] \r\n # for i in PartType for j in JobTypeData[i] for k in FeasibleMachines[i,j] for t in range(1,T+1)) + sum(o[t] for t in range(1,T+1))\r\n # - eps*sum(s[i,j,k,t] for i in PartType for j in JobTypeData[i] for k in FeasibleMachines[i,j] for t in range(1,T+1)),grb.GRB.MINIMIZE)\r\n \r\n \r\n model.setObjective(((1-Theta)/A)*grb.quicksum(QualCost[i,j,k]*z[i,j,k,t] \r\n for i in PartType for j in JobTypeData[i] for k in NotQualified[i,j] for t in range(1,T+1) ) + sum(o[t] for t in range(1,T+1)),grb.GRB.MINIMIZE)\r\n \r\n \r\n temp={}\r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n for k in NotQualified[i,j]:\r\n for t in range(1,T+1):\r\n if Demand[i,j,t]!=0:\r\n temp[i,j,k,t] = model.addConstr(sum(z[i,j,k,l] for l in range(1,t+1))>= s[i,j,k,t])\r\n Budget={} \r\n for t in range(1,T+1):\r\n Budget[t] = model.addConstr(sum(z[i,j,k,t] for i in PartType for j in JobTypeData[i] for k in FeasibleMachines[i,j] if k in NotQualified[i,j]) <= gamma)\r\n \r\n #for i in PartType:\r\n # for j in JobTypeData[i]:\r\n # for k in FeasibleMachines[i,j]:\r\n # for t in range(1,T+1):\r\n # s[i,j,k,t].start=newS[i,j,k,t] # heuristic solution\r\n # z[i,j,k,t].start = newZ[i,j,k,t]\r\n model.Params.PrePasses = 1\r\n model.Params.MIPFocus = 1\r\n model.Params.Heuristics = 0.05 # 10% time spent on Heuristics, default is 0.05\r\n model.Params.Method=2\r\n \r\n model.optimize()\r\n \r\n s_var={}\r\n z_var={}\r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n for k in NotQualified[i,j]:\r\n for t in range(1,T+1):\r\n if Demand[i,j,t]!=0:\r\n s_var[i,j,k,t] = s[i,j,k,t].X\r\n \r\n z_var[i,j,k,t] = z[i,j,k,t].X\r\n \r\n pi_Dual = {} \r\n mu_Dual ={} #\r\n y_Dual = {}\r\n d_Dual = {}\r\n pi_Dual_ray={}\r\n mu_Dual_ray = {}\r\n y_Dual_ray={}\r\n d_Dual_ray={}\r\n \r\n Stage2Total=12\r\n Stage2 = {}\r\n queue_not_alpha_Covered = grb.tuplelist()\r\n CCB_counter = 1\r\n lowerbound={}\r\n lowerbound[0]=0\r\n UpperBound = {}\r\n UpperBound[0]=100\r\n breaks = 0\r\n lazyConst={}\r\n for r in range(1,30):\r\n print(\"\\nIteration %d \\n\\n\" %(nCUT+1))\r\n s2 =0\r\n nCUT=nCUT+1\r\n infeas=0\r\n infeasi = {}\r\n x_var={}\r\n for t in range(1,T+1):\r\n print(\"\\nSubproblem- %d \\n\\n\" %(t))\r\n x_var_t = {}\r\n if r==1:\r\n \r\n rays,pi_t_Dual,mu_t_Dual,y_t_Dual,d_t_Dual,pi_t_Dual_ray,mu_t_Dual_ray,y_t_Dual_ray,d_t_Dual_ray,Stage2_Cost_t,x_var_t = subproblem_t(t,s_var,x_var_t)\r\n elif (r-1,t) in Stage2:\r\n rays,pi_t_Dual,mu_t_Dual,y_t_Dual,d_t_Dual,pi_t_Dual_ray,mu_t_Dual_ray,y_t_Dual_ray,d_t_Dual_ray,Stage2_Cost_t,x_var_t = subproblem_t(t,s_var,x_var_t)\r\n \r\n else:\r\n continue\r\n Defn_Cut={}\r\n \r\n \r\n if ((rays==0)):\r\n if (Stage2_Cost_t==0):\r\n continue\r\n \r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n if (i,j) in pi_t_Dual:\r\n pi_Dual[i,j,t,nCUT] = pi_t_Dual[i,j]\r\n for k in Work_Center_ID:\r\n if k in mu_t_Dual: \r\n mu_Dual[k,t,nCUT] = mu_t_Dual[k]\r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n for k in FeasibleMachines[i,j]:\r\n if (i,j,k) in y_t_Dual: \r\n y_Dual[i,j,k,t,nCUT] = y_t_Dual[i,j,k]\r\n d_Dual[t,nCUT] = d_t_Dual\r\n s2 = s2 + Stage2_Cost_t\r\n Stage2[r,t] = Stage2_Cost_t\r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n for k in FeasibleMachines[i,j]:\r\n if Demand[i,j,t] !=0:\r\n x_var[i,j,k,t] = x_var_t[i,j,k] # current value of x\r\n else:\r\n \r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n if (i,j) in pi_t_Dual_ray:\r\n pi_Dual_ray[i,j,t,nCUT] = pi_t_Dual_ray[i,j]\r\n for k in Work_Center_ID:\r\n mu_Dual_ray[k,t,nCUT] = mu_t_Dual_ray[k]\r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n for k in FeasibleMachines[i,j]:\r\n if (i,j) in y_t_Dual_ray:\r\n y_Dual_ray[i,j,k,t,nCUT] = y_t_Dual_ray[i,j,k]\r\n d_Dual_ray[t,nCUT] = d_t_Dual_ray\r\n infeas = 1\r\n infeasi[r,t] = 1\r\n \r\n #####\r\n \r\n if infeas ==1:\r\n Stage2Total= 12\r\n else:\r\n Stage2Total=s2\r\n \r\n \r\n f_y = ((1-Theta)/A)*grb.quicksum(QualCost[i,j,k]*z_var[i,j,k,t] for i in PartType for j in JobTypeData[i] for k in FeasibleMachines[i,j] for t in range(1,T+1) if (i,j,k,t) in z_var) \r\n \r\n if (min(UpperBound.values()) > max(lowerbound.values())) :\r\n # add cuts to RMP \r\n #print('continue')\r\n for t in range(1,T+1):\r\n \r\n \r\n if (nCUT,t) in Stage2:\r\n \r\n a1 = sum((-threshold*Capacity[k,t])*mu_Dual[k,t,nCUT] for k in Work_Center_ID if (k,t,nCUT) in mu_Dual)\r\n a2 = sum(Demand[i,j,t]*pi_Dual[i,j,t,nCUT] for i in PartType for j in JobTypeData[i] if (i,j,t,nCUT) in pi_Dual)\r\n a3= (-1+threshold)*d_Dual[t,nCUT]\r\n lazyConst[nCUT,t]=model.addConstr(o[t] >= a1 + a2 + grb.quicksum((-Demand[i,j,t]*y_Dual[i,j,k,t,nCUT]*s[i,j,k,t]) for i in PartType for j in JobTypeData[i] for k in FeasibleMachines[i,j] if (i,j,k,t,nCUT) in y_Dual)+ a3)\r\n lazyConst[nCUT,t].lazy=1\r\n \r\n print(\"Optimality cut-%d,%d\" %(t,nCUT))\r\n \r\n else:\r\n breaks = 1 \r\n break\r\n print(\"\\n\")\r\n print(\"\\nRE-Solving Master Problem\\n\\n\")\r\n \r\n# for i in PartType:\r\n# for j in JobTypeData[i]:\r\n# for k in FeasibleMachines[i,j]:\r\n# for t in range(1,T+1):\r\n# if (i,j,k,t) in s_var:\r\n# s[i,j,k,t].start= s_var[i,j,k,t] # heuristic solution\r\n# if(i,j,k,t) in z_var:\r\n# z[i,j,k,t].start = z_var[i,j,k,t] # heuristic solution\r\n# model.Params.PrePasses = 1\r\n# model.Params.MIPFocus = 1 # MIP Focus on the bounds\r\n# model.Params.Heuristics = 0.1 # 10% time spent on Heuristics, default is 0.05\r\n# #model.Params.Method=2\r\n# model.Params.MIPGap=.05\r\n# model.Params.TimeLimit = 150\r\n# model._lowerbounds = max(lowerbound.values())\r\n dd = ((1-Theta)/A)*sum(QualCost[i,j,k]*z_var[i,j,k,t] for i in PartType for j in JobTypeData[i] for k in FeasibleMachines[i,j] for t in range(1,T+1) if (i,j,k,t) in z_var)\r\n sf= sum(o[t].X for t in range(1,T+1))\r\n lowerbound[r]= model.objbound\r\n print(\"\\nLower Bound = %f\" %lowerbound[r])\r\n print(\"Upper Bound = %f\" % (dd+Stage2Total))\r\n UpperBound[r] = (dd+Stage2Total)\r\n \r\n if dd >0:\r\n storeQual[r] = sum(z_var.values())\r\n \r\n if breaks==0:\r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n for k in FeasibleMachines[i,j]:\r\n for t in range(1,T+1):\r\n if (i,j,k,t) in s_var:\r\n s[i,j,k,t].start= s_var[i,j,k,t] # heuristic solution\r\n if(i,j,k,t) in z_var:\r\n z[i,j,k,t].start = z_var[i,j,k,t] # heuristic solution\r\n model.Params.PrePasses = 1\r\n model.Params.MIPFocus = 2 # MIP Focus on the bounds\r\n model.Params.Heuristics = 0.05 # 10% time spent on Heuristics, default is 0.05\r\n #model.Params.Method=2\r\n model.Params.MIPGap=.005\r\n #model.Params.lazyConstraints = 1\r\n if r >=20:\r\n model.Params.TimeLimit = 200\r\n else:\r\n model.Params.TimeLimit = 200\r\n model._lowerbounds = max(lowerbound.values())\r\n model.optimize(mycallback)\r\n elapsed_time = time.time() - start_time\r\n TimeLapse[r] = elapsed_time\r\n print(\"\\n\")\r\n s_var={}\r\n z_var={}\r\n for i in PartType:\r\n for j in JobTypeData[i]:\r\n for k in FeasibleMachines[i,j]:\r\n for t in range(1,T+1):\r\n if (i,j,k,t) in s:\r\n s_var[i,j,k,t] = s[i,j,k,t].X\r\n if (i,j,k,t) in z:\r\n z_var[i,j,k,t]= z[i,j,k,t].X\r\n# dd = ((1-Theta)/A)*sum(QualCost[i,j,k]*z_var[i,j,k,t] for i in PartType for j in JobTypeData[i] for k in FeasibleMachines[i,j] for t in range(1,T+1) if (i,j,k,t) in z_var)\r\n# sf= sum(o[t].X for t in range(1,T+1))\r\n# lowerbound[r]= model.objbound\r\n# print(\"\\nLower Bound = %f\" %lowerbound[r])\r\n# print(\"Upper Bound = %f\" % (dd+Stage2Total))\r\n# UpperBound[r] = (dd+Stage2Total)\r\n# if dd >0:\r\n# storeQual[r] = sum(z_var.values())\r\n \r\n BestLowerBounds[iter] = max(lowerbound.values())\r\n BestUpperBounds[iter] = min(UpperBound.values())\r\n \r\n \r\n\r\n#\r\n# Copyright 2020, Gurobi Optimization, LLC\r\n#\r\n# Interactive shell customization example\r\n#\r\n# Define a set of customizations for the Gurobi shell.\r\n# Type 'from custom import *' to import them into your shell.\r\n#\r\n# Custom termination criterion: Quit optimization\r\n# - after 5s if a high quality (1% gap) solution has been found, or\r\n# - after 10s if a feasible solution has been found.\r\n\r\n#%%\r\n# Number of job types which are above \\tau\r\ncounters=dict((key,0) for key in range(1,T+1))\r\ntotaljobs= dict((key2,0) for key2 in range(1,T+1))\r\nfor i in PartType:\r\n for j in JobTypeData[i]:\r\n for t in range(1,T+1):\r\n if Demand[i,j,t] >0: \r\n totaljobs[t]=totaljobs[t]+1\r\n if sum(s[i,j,k,t].X for k in FeasibleMachines[i,j]) > Tau:\r\n counters[t]= counters[t]+1\r\n \r\n \r\nratios = {}\r\nfor t in range(1,T+1):\r\n ratios[t] = counters[t]/totaljobs[t] \r\n\r\nUtilization = dict(((key1,key3), 0) for key1 in Work_Center_ID for key3 in range(1,T+1)) \r\n \r\nabove = {}\r\nstore=[]\r\ncounts=0\r\nfor k in Work_Center_ID:\r\n for t in range(1,T+1):\r\n Utilization[k,t] = round(sum((1/Capacity[k,t])*Pijk.select(i,j,k,'*')[0][3]*x_var[i,j,k,t] for i in PartType for j in JobTypeData[i] if (i,j,k,t) in x_var),2)\r\n if Utilization[k,t] > 1.0:\r\n above[k,t] = 1\r\n store.append(k)\r\n counts+=1 \r\nmaxUtlization = dict(((key1), 0) for key1 in range(1,T+1))\r\n\r\nfor t in range(1,T+1):\r\n for k in Work_Center_ID:\r\n \r\n if Utilization[k,t] > maxUtlization[t]:\r\n maxUtlization[t]= Utilization[k,t]\r\n maxUtlization[t] = max(maxUtlization[t] -0.7,0)\r\n# chech demand satisfaction\r\n \r\nfor i in PartType:\r\n for j in JobTypeData[i]:\r\n if Demand[i,j,t]!=0:\r\n d =sum(x_var[i,j,k,t] for k in FeasibleMachines[i,j])\r\n if round(d) < round(Demand[i,j,t]):\r\n print(i,j,t)\r\n print(Demand[i,j,t])\r\n print(d)\r\n break\r\n\r\n#%%\r\nimport matplotlib.pyplot as plt\r\nlowerbounds_X=[]\r\nlowerbounds_Y=[]\r\nupperbounds_Y = []\r\nfor ss in range(1,r):\r\n lowerbounds_X.append(TimeLapse[ss])\r\n lowerbounds_Y.append(lowerbound[ss])\r\n upperbounds_Y.append(UpperBound[ss])\r\n \r\nplt.plot(lowerbounds_X, lowerbounds_Y, 'r--', lowerbounds_X, upperbounds_Y, 'bs--') \r\nplt.xlabel('time (seconds)')\r\nDraws_Y =[]\r\nminUpp=100\r\ncounts=0\r\nDraws_X = []\r\nfor iter in range(1,r):\r\n if UpperBound[iter] <= minUpp:\r\n counts=counts+1\r\n minUpp = UpperBound[iter]\r\n Draws_Y.append(minUpp)\r\n Draws_X.append(TimeLapse[counts])\r\n #plt.plot(Draws_X, Draws_Y, 'b',label=\"Bend-ub\")\r\n else:\r\n counts=counts+1\r\n Draws_Y.append(minUpp)\r\n Draws_X.append(TimeLapse[counts])\r\nplt.plot(Draws_X, Draws_Y, 'b',label=\"Bend-ub\")\r\n \r\nDraws_Y =[]\r\nmaxLow=0\r\ncounts=0\r\nDraws_X = []\r\nfor iter in range(1,r):\r\n if lowerbound[iter] >= maxLow:\r\n counts=counts+1\r\n maxLow = lowerbound[iter]\r\n Draws_Y.append(maxLow)\r\n Draws_X.append(TimeLapse[counts])\r\n# plt.plot(Draws_X, Draws_Y, 'r',label=\"Bend-lb\") \r\n else:\r\n counts=counts+1\r\n Draws_Y.append(maxLow)\r\n Draws_X.append(TimeLapse[counts])\r\nplt.plot(Draws_X, Draws_Y, 'r',label=\"Bend-lb\") \r\n\r\nDraws_Y =[0.0781326,0.0497663, 0.0491283, .04913, .04913, .04913]\r\nmaxLow=0\r\ncounts=0\r\nDraws_X = [60.4642,349.206,358.426, 1431, 1659, 2200] \r\nplt.plot(Draws_X, Draws_Y, 'x-',label=\"Gur-ub\") \r\nDraws_Y =[0,0.046357, 0.046357, .04762, .04782, .04795]\r\nmaxLow=0\r\ncounts=0\r\nDraws_X = [45,349.206,358.426, 1431, 1659, 2200] \r\nplt.plot(Draws_X, Draws_Y, marker='^', label=\"Gur-lb\") \r\nplt.legend(loc='upper right')\r\n\r\n#%%\r\nlowerbounds_X=[]\r\nlowerbounds_Y=[]\r\nupperbounds_Y = []\r\nfor ss in range(1,r):\r\n lowerbounds_X.append(TimeLapse[ss])\r\n lowerbounds_Y.append(lowerbound[ss])\r\n upperbounds_Y.append(UpperBound[ss])\r\n \r\nplt.plot(lowerbounds_X, lowerbounds_Y, 'r--', lowerbounds_X, upperbounds_Y, 'bs--') \r\nplt.xlabel('time (seconds)')\r\nDraws_Y =[]\r\nminUpp=100\r\ncounts=0\r\nDraws_X = []\r\nfor iter in range(1,r):\r\n if UpperBound[iter] <= minUpp:\r\n counts=counts+1\r\n minUpp = UpperBound[iter]\r\n Draws_Y.append(minUpp)\r\n Draws_X.append(TimeLapse[counts])\r\n plt.plot(Draws_X, Draws_Y, 'b')\r\n else:\r\n counts=counts+1\r\n Draws_Y.append(minUpp)\r\n Draws_X.append(TimeLapse[counts])\r\n plt.plot(Draws_X, Draws_Y, 'b')\r\n \r\nDraws_Y =[]\r\nmaxLow=0\r\ncounts=0\r\nDraws_X = []\r\nfor iter in range(1,r):\r\n if lowerbound[iter] >= maxLow:\r\n counts=counts+1\r\n maxLow = lowerbound[iter]\r\n Draws_Y.append(maxLow)\r\n Draws_X.append(TimeLapse[counts])\r\n plt.plot(Draws_X, Draws_Y, 'r') \r\n else:\r\n counts=counts+1\r\n Draws_Y.append(maxLow)\r\n Draws_X.append(TimeLapse[counts])\r\n plt.plot(Draws_X, Draws_Y, 'r') \r\n\r\n" } ]
1
Remy93130/Projet_Python
https://github.com/Remy93130/Projet_Python
27f64b69bfa2bd89a8e499eb2a35bd35258bcf2c
9387118fb710ea599fc6dcbf3bfebaa7675ce912
f4a26cd7b50a32491268b2234cf92a15ea2a8868
refs/heads/master
2021-05-15T18:41:29.550413
2018-01-10T18:57:18
2018-01-10T18:57:18
107,651,360
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4255269467830658, "alphanum_fraction": 0.42599278688430786, "avg_line_length": 58.914894104003906, "blob_id": "41948f7fd122808997697300131ef0478db29e01", "content_id": "516534b299821187f578268f2e63fd18f5cd4741", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 10656, "license_type": "no_license", "max_line_length": 79, "num_lines": 141, "path": "/README.txt", "repo_name": "Remy93130/Projet_Python", "src_encoding": "UTF-8", "text": "Casse brique créé par Remy Barberet et Léo Chardon\r\ndans le cadre du projet casse brique du DUT informatique 1 de Champs sur Marne.\r\n\r\n _____ _____ _ _____ _____ _____ _ _ _ \r\n| _ \\ | ____| | | / _ \\ | _ \\ | _ \\ | | | | / / \r\n| |_| | | |__ | | | | | | | |_| | | |_| | | | | |/ / \r\n| _ / | __| | | | | | | | _ { | _ / | | | |\\ \\ \r\n| | \\ \\ | |___ | |___ | |_| | | |_| | | | \\ \\ | | | | \\ \\ \r\n|_| \\_\\ |_____| |_____| \\_____/ |_____/ |_| \\_\\ |_| |_| \\_\\ \r\n\r\n ╔═════════════════════╗ \r\n╔═══════════════════╣ TABLE DES MATIERES ╠═══════════════════╗\r\n║ ╚═════════════════════╝ ║\r\n║ ║\r\n║ I. OPTIMISATION DU PROGRAMME ║\r\n║ II. ORGANISATION DU PROGRAMME ║\r\n║ III. CHOIX TECHNIQUES ║\r\n║ IV. PROBLEMES RENCONTRES ║\r\n║ ║\r\n╚═════════════════════════════════════════════════════════════╝\r\n\r\n\r\n ╔════════════════════════════╗ \r\n╔════════════════╣ OPTIMISATION DU PROGRAMME ╠═══════════════╗\r\n║ ╚════════════════════════════╝ ║\r\n║ ║\r\n║ Pour optimiser le programme nous avons choisis de faire en ║\r\n║ sorte que le programme supprime et affiche uniquement les ║\r\n║ objets concernés afin que celui-ci soit plus fluide. ║\r\n║ ║\r\n║ Au début, nous voulions aussi faire en sorte que les ║\r\n║ briques est une unique couleur, mais que celles-ci se ║\r\n║ fissurent si la balle les touchais. Mais l'affichage ║\r\n║ des images faisait trop ralentir les machines donc nous ║\r\n║ avons remis les niveaux de couleurs pour les briques. ║\r\n║ ║\r\n║ Pour augmenter la fluidité possible, nous avons retirés ║\r\n║ la fonction sleep du module time et fait avec un systeme ║\r\n║ de module (cf tp snake) afin de mieux pouvoir gerer le ║\r\n║ rafraichissement du programme. ║\r\n║ ║\r\n║ Lors du Premier rendus, notre casse brique ne possedait pas║\r\n║ de vecteur vitesse, la balle ne faisait que s'incrementer ║\r\n║ de 1 par rafraichissement, désormais il y a la possibilité ║\r\n║ de modifier ce vecteur vitesse, ainsi la balle peut ║\r\n║ s'incrementer de 1 comme de 3 sans pour autant avoir des ║\r\n║ problèmes avec la collision. Cette optimisation permet aux ║\r\n║ machines lentes de pouvoir jouer sans problèmes. ║\r\n║ ║\r\n╚═════════════════════════════════════════════════════════════╝\r\n\r\n\r\n ╔════════════════════════════╗ \r\n╔════════════════╣ ORGANISATION DU PROGRAMME ╠═══════════════╗\r\n║ ╚════════════════════════════╝ ║\r\n║ ║\r\n║ Le programme est organisé en fonctions qui sont regrouper ║\r\n║ par thèmes (collision, animation, etc..) pour le futur, ces║\r\n║ thèmes seront ranger dans des modules. ║\r\n║ ║\r\n║ Le corps du programme possède quelque variables ║\r\n║ initialisées pour le bon fonctionnement des fonctions ║\r\n║ ainsi que la boucle while qui fait tourner le programme, ║\r\n║ on sort de cette boucle si l'on gagne ou si l'on n'a plus ║\r\n║ aucune vie, cela va ramener aux lignes de fin du programme ║\r\n║ qui agit en fonction de la victoire ou de la défaite. ║\r\n║ ║\r\n║ Lorsque le joueur perd ou gagne, il a la possibilité de ║\r\n║ directement relancer une partie dans une nouvelle fenêtre ║\r\n║ en appuyant sur R, d'où l'interêt de couper le code en ║\r\n║ différents fichiers qui peuvent s'appeler les uns et ║\r\n║ les autres. ║\r\n║ ║\r\n║ ║\r\n╚═════════════════════════════════════════════════════════════╝\r\n\r\n\r\n ╔════════════════════════════╗ \r\n╔════════════════╣ CHOIX TECHNIQUES ╠═══════════════╗\r\n║ ╚════════════════════════════╝ ║\r\n║ ║\r\n║ Pour tout ce qui est stockage de variable souvent modifier ║\r\n║ tel que la position de la balle ou de la raquette, nous ║\r\n║ avons utilise des listes ce qui nous permet de ne pas ║\r\n║ toujours retourner la valeur modifier ║\r\n║ ║\r\n║ Quant aux selection de variable specifique comme le mode ║\r\n║ auto ou encore augmenter le nombre de vie nous ajouter ║\r\n║ un parametre pour les activer afin de verifier plus vite ║\r\n║ la presence ou non de bug dans le programme ║\r\n║ ║\r\n║ Pour certaine variable, nous avons choisi que celle-ci ║\r\n║ soient globale car elles sont tres souvent utiliser dans ║\r\n║ les fonctions que l'ont utilise ║\r\n║ ║\r\n║ Désormais, seul le main.py possède un corps, tout nos ║\r\n║ autres fichier possède des fonctions qui contribue aux jeu ║\r\n║ même les variables sont maintenant dans des fonctions ║\r\n║ ║\r\n╚═════════════════════════════════════════════════════════════╝\r\n\r\n ╔════════════════════════════╗ \r\n╔════════════════╣ PROBLEMES RENCONTRES ╠═══════════════╗\r\n║ ╚════════════════════════════╝ ║\r\n║ ║\r\n║ A travers le développement du casse brique, il y a eu une ║\r\n║ multitude de problèmes comme la collision des briques, ║\r\n║ leurs affichage ou la fluidité du jeu. La fluidité et ║\r\n║ l'affichage ont été expliqués dans l'optimisation du ║\r\n║ programme quant aux collisions des briques, le plus gros ║\r\n║ problèmes était de régler les coordonnées de collisions ║\r\n║ pour la gauche et la droite car le haut et le bas des ║\r\n║ briques étaient prioritaires. Les briques sont donc ║\r\n║ découpées en quatre parties pour la collision, haut, ║\r\n║ bas, droite et gauche. Mais le haut et le bas recouvrent ║\r\n║ toute la partie superieur et inferieur de l'écran ainsi ║\r\n║ si la balle tapait dans les coins haut et bas il pouvait ║\r\n║ y avoir des bugs car on inverse son axe des ordonnées, ║\r\n║ ainsi nous avons donc rajoutés des conditions, si la ║\r\n║ balle monte et qu'elle touche le haut c'est son axe des ║\r\n║ abscisses qui doit etre inversé et c'est pareil pour le ║\r\n║ bas de la brique. Voilà comment les collisions des ║\r\n║ briques ont été corrigées. ║\r\n║ ║\r\n║ Après avoir insérer un vecteur vitesse, il y a eu d'autres ║\r\n║ problèmes avec la collision, notamment lorsque la balle ║\r\n║ possedait un vecteur vitesse trop important, mais nous avons║\r\n║ su corriger ce problème en utilisant plus de précisions ║\r\n║ sur les coordonnées de la balle et des briques dans notre ║\r\n║ programme. ║\r\n║ ║\r\n║ La gestion du menu pause était aussi assez compliquée. ║\r\n║ En effet, il fallait utiliser les fonctions événements de ║\r\n║ la bibliothèque upemtk en même temps que les déplacements ║\r\n║ de la raquette car un seul événement peut donner plusieurs ║\r\n║ possibilité ( position de la souris, clic ou touche) ║\r\n║ c'est pour cette raison que la fonction pause a uniquement ║\r\n║ la possibilité d'être appelée dans la fonction qui ║\r\n║ contrôle la raquette. ║\r\n║ ║\r\n╚═════════════════════════════════════════════════════════════╝" }, { "alpha_fraction": 0.5421249270439148, "alphanum_fraction": 0.5831611752510071, "avg_line_length": 34.25984191894531, "blob_id": "a63f53b01e752c563a77eb2e3c5764a25599a83f", "content_id": "6ca0354923707d7cc17a76a77495fd30f7bac776", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17929, "license_type": "no_license", "max_line_length": 211, "num_lines": 508, "path": "/jeu.py", "repo_name": "Remy93130/Projet_Python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"Fonctions d'un jeu de Casse brique.\"\"\"\n# Imports --------------------------------------------------------------------------------------------------------\nfrom upemtk import *\nfrom time import time, sleep\nfrom random import randint\nfrom sys import argv\nfrom score import *\nimport main \n\n# Variables globales ---------------------------------------------------------------------------------------------\ndef variables_globales():\n\t\"\"\"Permet d'initialiser la position de la raquette et les deplacements de la balle.\"\"\"\n\tglobal deplacementBalle, v_vitesse, positionRaquette\n\tdeplacementBalle = [0,0]\n\tdeplacementBalle[0] = randint(0,8)\n\tif deplacementBalle[0] != 0:\n\t\tdeplacementBalle[0] = deplacementBalle[0] / 10\n\tdeplacementBalle[1] = 1-deplacementBalle[0]\n\tpositionRaquette = [110, 420, 190, 430]\n\tv_vitesse = 1\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#\n#---------------------------------------------------------------Fonctions d'interface-----------------------------------------------------------------------------------------------------#\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#\n\n\ndef creation_interface(score, vie):\n\t\"\"\"Cree l interface du jeu.\"\"\"\n\tefface('score')\n\tefface('vie')\n\ttexte(320,50, \"Score : \" + str(score), taille=14, tag='score')\n\ttexte(320,85, \"Vie : \" + str(vie), taille=14, tag='vie')\n\n\ndef timer(minute, tempsDebut):\n\t\"\"\"Permet de faire le chronometre du jeu renvoie le tuple\n\tavec les minutes et le temps du debut.\"\"\"\n\tefface('timer')\n\ttempsATM = int(time()-tempsDebut)\n\t#Si une minute est passe\n\tif tempsATM >= 60:\n\t\ttempsATM = 0\n\t\ttempsDebut = time()\n\t\tminute += 1\n\t#On affiche le chrono\n\ttexte(320,120, \"Temps : \" + str(minute) + ':' + str(tempsATM),\n\t\ttaille=14, tag='timer')\n\treturn (minute, tempsDebut)\n\t\n\t\ndef fin_jeu(vie, positionBalle):\n\t\"\"\"Permet de verifier si la balle n est pas renvoyer\n\tSinon la balle est repositionner renvoie le vie et la \n\tposition de la balle si la balle est perdue sinon rien\n\t>>> fin_jeu(3, [150, 455])\n\t(2, [150, 400])\n\t>>> fin_jeu(3, [150, 150])\n\t\"\"\"\n\tif positionBalle[1] > 453:\n\t\tvie -= 1\n\t\tpositionBalle = [150, 400]\n\t\treturn (vie, positionBalle)\n\treturn None\n\t\n\ndef pause():\n\t\"\"\"Permet de marquer une pause, appelée si l'utilisateur a appuyer sur P\n\t, permet aussi de redefinir le type de contrôle de la raquette\"\"\"\n\tglobal contrôle \n\tefface('balle')\n\trectangle(10, 200, 280, 350,couleur='black', epaisseur=1, tag='menu_pause')\n\ttexte(130,210, \"Pause\",\n\t\ttaille=12, tag='menu_pause')\n\ttexte(130,260, \"contrôle clavier\",\n\t\ttaille=9, tag='menu_pause')\n\trectangle(130, 260, 220, 280 ,couleur='black', epaisseur=1, tag='menu_pause')\n\ttexte(130,310, \"contrôle souris\",\n\t\ttaille=9, tag='menu_pause')\n\trectangle(130, 310, 220, 330,couleur='black', epaisseur=1, tag='menu_pause')\n\twhile True:\n\t\tev = donne_evenement()\n\t\ttype_ev = type_evenement(ev)\n\t\tif type_ev == \"Touche\":\n\t\t\tgo = touche(ev)\n\t\t\tif go == 'p':\n\t\t\t\tefface('menu_pause')\n\t\t\t\tbreak\n\t\tif type_ev == \"ClicDroit\" or type_ev == \"ClicGauche\":\n\t\t\tcoord = (clic_x(ev), clic_y(ev))\n\t\t\tif coord[0] > 130 and coord[0] < 220 and coord[1] > 260 and coord[1] < 280:\n\t\t\t\trectangle(130, 260, 220, 280 ,couleur='black',remplissage = 'red', epaisseur=1, tag='effect')\n\t\t\t\tmise_a_jour()\n\t\t\t\tcontrôle = 'clavier'\n\t\t\t\tsleep(0.2)\n\t\t\t\tefface('effect')\n\t\t\tif coord[0] > 130 and coord[0] < 220 and coord[1] > 310 and coord[1] < 330:\n\t\t\t\trectangle(130, 310, 220, 330 ,couleur='black',remplissage = 'red', epaisseur=1, tag='effect')\n\t\t\t\tmise_a_jour()\n\t\t\t\tcontrôle = 'souris'\n\t\t\t\tsleep(0.2)\n\t\t\t\tefface('effect')\n\t\t\n\t\tmise_a_jour()\n\t\t\t\t\n\t\n\t\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#\n#---------------------------------------------------------------Fonctions de collision----------------------------------------------------------------------------------------------------#\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#\n\n\ndef collision(positionBalle):\n\t\"\"\"Permet de verifier si la balle entre en contact avec un element.\"\"\"\n\tglobal deplacementBalle, positionRaquette\n\n\t#On verifie si elle touche le haut de la fenetre\n\tif (positionBalle[1]+4 < 0):\n\t\t#On inverse le deplacement verticale de la balle\n\t\tdeplacementBalle[1] *= -1\n\n\t#On verifie si elle touche un cote de la fenetre\n\tif (positionBalle[0]+4 < 0 or positionBalle[0]+4 > 300):\n\t\tdeplacementBalle[0] *= -1\n\n\t#On verifie si elle touche la raquette:\n\tcollision_raquette(positionBalle)\n\t\n\ndef collision_raquette(positionBalle):\n\t\"\"\"Complement de la fonction collision, permet de vérifier \n\tsi la balle touche la raquette et modifie l'orientation de\n\tla balle.\"\"\"\n\tglobal deplacementBalle, positionRaquette\n\n\tif (positionBalle[0] >= positionRaquette[0] and positionBalle[0] <= positionRaquette[2]) and (positionBalle[1] > 420 and positionBalle[1] < 430):\n\n\t\tdeplacementBalle[1] *= -1 #On renvoie la balle vers le haut\n\n\t\t#On choisi l inclinaison de la balle selon ou elle touche la raquette\n\t\tif ((positionRaquette[0] <= positionBalle[0] and positionBalle[0] <= positionRaquette[0]+10) or \n\t\t\t(positionRaquette[0]+70 <= positionBalle[0] and positionBalle[0] <= positionRaquette[0]+80)):\n\n\t\t\tdeplacementBalle = [0.8,0.2]\n\t\telif ((positionRaquette[0]+10 < positionBalle[0] and positionBalle[0] <= positionRaquette[0]+20) or \n\t\t\t(positionRaquette[0]+60 <= positionBalle[0] and positionBalle[0] < positionRaquette[0]+70)):\n\n\t\t\tdeplacementBalle = [0.6,0.4]\n\t\telif ((positionRaquette[0]+20 < positionBalle[0] and positionBalle[0] <= positionRaquette[0]+30) or \n\t\t\t(positionRaquette[0]+50 <= positionBalle[0] and positionBalle[0] < positionRaquette[0]+60)):\n\t\t\t\n\t\t\tdeplacementBalle = [0.4,0.6]\n\n\t\telse:\n\t\t\tdeplacementBalle = [0.2,0.8]\n\n\t\t#Verifie si la balle doit changer de direction selon le positionnement\n\t\t#De la raquette\n\t\tif (positionBalle[0] < ((positionRaquette[0]+positionRaquette[2])/2) and deplacementBalle[0] > 0):\n\t\t\tdeplacementBalle[0] *= -1\n\t\tif (positionBalle[0] > ((positionRaquette[0]+positionRaquette[2])/2) and deplacementBalle[0] < 0):\n\t\t\tdeplacementBalle[0] *= -1\n\t\t\t\n\t\t\t\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#\n#---------------------------------------------------------------Fonctions d'animation-----------------------------------------------------------------------------------------------------#\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#\n\ndef animation_balle(balle):\n\t\"\"\"Permet de deplacer la balle.\"\"\"\n\tglobal positionBalle\n\tpositionBalle = (positionBalle[0] + v_vitesse*deplacementBalle[0], positionBalle[1] - v_vitesse*deplacementBalle[1])\n\tballe = cercle(positionBalle[0], positionBalle[1], 4, remplissage=\"black\" ,tag='balle')\n\tmise_a_jour()\n\treturn(balle)\n\n\ndef animation_raquette_clavier(raquette):\n\t\"\"\"Permet de deplacer la raquette\"\"\"\n\tglobal positionRaquette\n\tpositionRaquette = list(positionRaquette)\n\tev = donne_evenement()\n\ttype_ev = type_evenement(ev)\n\tif type_ev == \"Touche\":\n\t\tdeplace = touche(ev)\n\t\tif deplace == 'Right' and positionRaquette[2] < 300:\n\n\t\t\tpositionRaquette[0] += 10\n\t\t\tpositionRaquette[2] += 10\n\t\t\t\n\t\tif deplace == 'Left' and positionRaquette[0] > 0:\n\t\t\t\n\t\t\tpositionRaquette[0] -= 10\n\t\t\tpositionRaquette[2] -= 10\n\t\t\t\n\t\tif deplace =='p':\n\t\t\tpause()\n\tefface(raquette)\n\traquette = rectangle(positionRaquette[0], positionRaquette[1], \n\t\tpositionRaquette[2], positionRaquette[3],\n\t\tcouleur='black', remplissage='blue', epaisseur=1,)\n\tmise_a_jour()\n\treturn raquette \n\t\n\t\ndef animation_raquette_souris(raquette):\n\t\"\"\"Permet de deplacer la raquette\"\"\"\n\tglobal positionRaquette\n\tev = donne_evenement()\n\ttype_ev = type_evenement(ev)\n\tif type_ev == \"Deplacement\":\n\t\tsouris = clic_x(ev)\n\t\tpositionRaquette = (souris-40, positionRaquette[1],\n\t\t\t souris+40, positionRaquette[3])\n\t\n\tif positionRaquette[0] < -3:\n\t\tpositionRaquette = (-3, positionRaquette[1],\n\t\t\t 77, positionRaquette[3])\n\t\n\tif positionRaquette[2] > 300:\n\t\tpositionRaquette = (220, positionRaquette[1],\n\t\t\t 300, positionRaquette[3])\n\tif type_ev == \"Touche\":\n\t\ttentative = touche(ev)\n\t\tif tentative =='p':\n\t\t\tpause()\n\tefface(raquette)\n\traquette = rectangle(positionRaquette[0], positionRaquette[1], \n\t\tpositionRaquette[2], positionRaquette[3],\n\t\tcouleur='black', remplissage='blue', epaisseur=1,)\n\tmise_a_jour()\n\treturn raquette \n\n\ndef mode_auto(raquette):\n\t\"\"\"Permet si l'option est selectionnee que \n\tl ordinateur joue a notre place.\"\"\"\n\tglobal positionBalle, positionRaquette\n\tefface(raquette)\n\t\t\n\tpositionRaquette = (positionBalle[0]-40, positionRaquette[1],\n\t\t\t positionBalle[0]+40, positionRaquette[3])\n\t\n\tif positionRaquette[0] < -3:\n\t\tpositionRaquette = (-3, positionRaquette[1],\n\t\t\t 77, positionRaquette[3])\n\t\n\tif positionRaquette[2] > 300:\n\t\tpositionRaquette = (220, positionRaquette[1],\n\t\t\t 300, positionRaquette[3])\n\traquette = rectangle(positionRaquette[0], positionRaquette[1], \n\t\tpositionRaquette[2], positionRaquette[3],\n\t\tcouleur='black', remplissage='blue', epaisseur=1,)\n\tmise_a_jour()\n\treturn raquette \n\n\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#\n#---------------------------------------------------------------Fonctions des briques-----------------------------------------------------------------------------------------------------#\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#\n\ndef creation_brique():\n\t\"\"\"Creer les briques qui devront etre detruites\"\"\"\n\tbrique = [\n\t1, 1, 1, 1, 1, 1, 1,\n\t2, 2, 0, 0, 0, 2, 2,\n\t1, 1, 3, 3, 3, 1, 1,\n\t0, 2, 1, 1, 1, 2, 0,\n\t3, 0, 0, 2, 0, 0, 3,\n\t3, 3, 0, 2, 0, 3, 3,\n\t2, 2, 2, 2, 2, 2, 2,\n\t0, 0, 2, 2, 2, 0, 0,\n\t1, 1, 1, 1, 1, 1, 1,\n\t1, 1, 1, 1, 1, 1, 1,\n\t]\n\treturn(brique)\n\n\ndef afficher_brique(brique):\n\t\"\"\"Permet d'afficher les briques dans la fenetre\"\"\"\n\tbriqueTester = 0 #Parametre de la premiere brique\n\tfor i in range(10,150,15):\n\t\tfor j in range(10,280,40):\n\t\t\tif brique[briqueTester] <= 0:\n\t\t\t\tbriqueTester += 1\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tif brique[briqueTester] == 1:\n\t\t\t\t\t#image(j,i,'brique1.gif',\n\t\t\t\t\t\t#ancrage='nw',\n\t\t\t\t\t\t\t#tag= 't')\n\t\t\t\t\trectangle(j, i, j+40, i+15,\n\t\t\t\t\t\tcouleur='black', remplissage='yellow', epaisseur=1, tag='tbrique')\n\t\t\t\telif brique[briqueTester] == 2:\n\t\t\t\t\t#image(j,i,'brique2.gif',\n\t\t\t\t\t\t#ancrage='nw',\n\t\t\t\t\t\t\t#tag= 't')\n\t\t\t\t\trectangle(j, i, j+40, i+15,\n\t\t\t\t\t\tcouleur='black', remplissage='orange', epaisseur=1, tag='tbrique')\n\t\t\t\telse:\n\t\t\t\t\t#image(j,i,'brique3.gif',\n\t\t\t\t\t\t#ancrage='nw',\n\t\t\t\t\t\t\t#tag= 't')\n\t\t\t\t\trectangle(j, i, j+40, i+15,\n\t\t\t\t\t\tcouleur='black', remplissage='red', epaisseur=1, tag='tbrique')\n\t\t\tbriqueTester += 1\n\n\ndef collision_brique(brique, positionBalle, score, vie):\n\t\"\"\"Permet de gérer la collision entre la balle et les briques et calcule le score\n\tsi une brique a ete detruite.\"\"\"\n\tbriqueTester = 0 #Parametre de la premiere brique\n\tfor i in range(10,150,15):\n\t\tfor j in range(10,280,40):\n\t\t\tif brique[briqueTester] <= 0:\n\t\t\t\tbriqueTester += 1\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tif (positionBalle[1] > i and positionBalle[1] < i+15) and (positionBalle[0] + v_vitesse*deplacementBalle[0] > j and positionBalle[0] + v_vitesse*deplacementBalle[0] < j+19.8): # gauche \n\t\t\t\t\t\tscore = effet_de_collision(briqueTester, 0, brique, score, vie)\n\t\t\t\t\t\t#print('gauche')\n\t\t\t\tif (positionBalle[1] > i and positionBalle[1] < i+15) and (positionBalle[0] + v_vitesse*deplacementBalle[0] < j+40 and positionBalle[0] + v_vitesse*deplacementBalle[0] > j+19.9): # droite\n\t\t\t\t\t\tscore = effet_de_collision(briqueTester, 0, brique, score, vie)\n\t\t\t\t\t\t#print('droite')\n\t\t\t\tif (positionBalle[0] > j and positionBalle[0] < j+40) and (positionBalle[1] - v_vitesse*deplacementBalle[1] > i and positionBalle[1] - v_vitesse*deplacementBalle[1] < i+15) and deplacementBalle[1] > 0: #bas\n\t\t\t\t\t\tscore = effet_de_collision(briqueTester, 1, brique, score, vie)\n\t\t\t\t\t\t#print('bas')\n\t\t\t\tif (positionBalle[0] > j and positionBalle[0] < j+40) and (positionBalle[1] - v_vitesse*deplacementBalle[1] > i and positionBalle[1] - v_vitesse*deplacementBalle[1] < i+15) and deplacementBalle[1] < 0:#haut \n\t\t\t\t\t\tscore = effet_de_collision(briqueTester, 1, brique, score, vie)\n\t\t\t\t\t\t#print('haut')\n\n\t\t\tbriqueTester += 1\n\treturn score\n\n\ndef effet_de_collision(numbrique, axe, brique, score, vie):\n\t\"\"\"Fonction complémentaire de collision_brique,permet l'actualisation d'une brique touchée\n\tainsi que l'inversement du deplacement de la balle.\"\"\"\n\tdeplacementBalle[axe] *= -1\n\tbrique[numbrique] -= 1\n\tif not brique[numbrique]: #Si on viens de detruire une brique\n\t\tscore += 10\n\tefface('tbrique')\n\tafficher_brique(brique)\n\tcreation_interface(score, vie)\n\tmise_a_jour()\n\treturn score\n\t\n\ndef verification_brique(brique):\n\t\"\"\"Verifie si toutes les briques ont ete detruite\n\trenvoie True si oui sinon False\n\t>>> verification_brique([0,0,0,0])\n\tTrue\n\t>>> verification_brique([0,1,0,0])\n\tFalse\n\t\"\"\"\n\tfor element in brique:\n\t\tif element > 0:\n\t\t\treturn False\n\treturn True\n\t\n\t\ndef lancement(modePerso):\n\t\"\"\"Fonction principale pour lancer le jeu\n\t\"\"\"\n\tglobal positionRaquette, positionBalle, contrôle, deplacementBalle, v_vitesse\n\tvariables_globales()\n\thauteur = 450\n\tlargeur = 450\n\tfin = False\n\ta = 0 #Rafraichissement du jeu\n\tb = 0 #Rafraichissement du timer\n\tcontrôle = 'clavier' # contrôle de la raquette\n\t#Definition de variable pour l interface\n\tscore = 0\n\tvie = 3\n\n\tif \"jeveuxdesvies\" in argv: #Petit easter egg\n\t\tvie = 99\n\tif 'aezakmi' in argv:\n\t\t\tfin = True\n\n\t#Vitesse du jeu a modifier selon la machine\n\tif \"auto\" in argv: #On augmente la vitesse du jeu si on est en mode auto (debogage)\n\t\trafraichissement = 100\n\t\tv_vitesse = 3\n\telse:\t\n\t\trafraichissement = 5000\n\t\t\n\tcree_fenetre(largeur, hauteur)\n\tligne(300,0,300,450, epaisseur=\"2\", tag='ligne')\n\ttexte(320,15, \"Relobrik\", taille=14, tag='nom')\n\tcreation_interface(score, vie)\n\n\tif not modePerso[0]:\n\t\thighscore = lecture_score()\n\t\taffichage_score(highscore)\n\t\t\n\n\t#----------Position initiale de la raquette----------#\n\traquette = rectangle(positionRaquette[0], positionRaquette[1], \n\t\tpositionRaquette[2], positionRaquette[3],\n\t\tcouleur='black', remplissage='', epaisseur=1,)\n\n\n\t#----------Position de départ de la balle-------------#\n\tpositionBalle = [150, 400]\n\tballe = cercle(positionBalle[0], positionBalle[1], 4, remplissage=\"black\")\n\t\n\t\n\t#----------Affichage initiale des briques-------------#\n\tif not modePerso[0]:\n\t\tbrique = creation_brique()\n\telse:\n\t\tbrique = modePerso[1]\n\tafficher_brique(brique)\n\n\t\n\t#-----------Jeu en attente du joueur------------------#\n\ttexte(30, 225, ' Appuyez sur une \\ntouche pour commencer', couleur='red',\n\t\t\t\tancrage='nw', police=\"Purisa\", taille=10, tag='commence')\n\tattente_touche()\n\tefface('commence')\n\t\n\t#----------affichage initiale du chronometre----------#\n\ttemps = timer(0, time())\n\n\twhile (vie > 0 and fin == False): #Corps du programmes\n\n\t\t\n\t\tif a%rafraichissement == 0:\n\t\t\tif \"auto\" in argv: #Si on a choisi le mode auto en parametre\n\t\t\t\traquette = mode_auto(raquette)\n\t\t\telse:\n\t\t\t\tif contrôle == 'clavier':\n\t\t\t\t\traquette = animation_raquette_clavier(raquette)\n\t\t\t\tif contrôle == 'souris':\n\t\t\t\t\traquette = animation_raquette_souris(raquette)\n\t\t\tefface(balle)\n\t\t\tballe = animation_balle(balle)\n\t\t\tcollision(positionBalle)\n\t\t\t\t\t\n\t\t\tscore = collision_brique(brique, positionBalle, score, vie)\n\t\t\treset = fin_jeu(vie, positionBalle)\n\t\t\t\n\n\t\t\t#On verifie si le joueur perd une vie et on remet la balle en place si c est le cas\n\t\t\tif reset:\n\t\t\t\tvie = reset[0]\n\t\t\t\tif vie == 0:\n\t\t\t\t\tbreak\n\t\t\t\tpositionBalle = reset[1]\n\t\t\t\tpositionRaquette = [110, 420, 190, 430]\n\t\t\t\tcreation_interface(score, vie)\n\t\t\t\tdeplacementBalle[1] *= -1\n\t\t\t\ttexte(30, 225, ' Appuyez sur une \\ntouche pour continuer', couleur='red',\n\t\t\t\t\tancrage='nw', police=\"Purisa\", taille=20, tag='texteC')\n\t\t\t\tattente_touche()\n\t\t\t\tefface('texteC')\n\n\n\t\t\tfin = verification_brique(brique)\n\t\t\ttemps = timer(temps[0], temps[1])\n\t\t\tif b%100== 0:\n\t\t\t\ttemps = timer(temps[0], temps[1])\n\t\t\t\tb = 0\n\t\t\tb += 1\n\t\t\ta = 0\n\t\ta += 1\n\t\t\n\n\tefface(balle)\n\tefface(raquette)\n\n\tif vie == 0:\n\t\ttexte(30, 225, 'Vous avez perdu,\\n appuyer sur R \\n pour recommencer \\n ou sur une \\n autre touche pour \\n quitter', couleur='red',\n\t\t\tancrage='nw', police=\"Purisa\", taille=20)\n\t\t\n\t\n\telse: #Le joueur a gagner\n\t\ttexte(30, 225, 'Vous avez gagné,\\n appuyer sur R \\n pour recommencer \\n ou sur une \\n autre touche pour \\n quitter', couleur='red',\n\t\t\tancrage='nw', police=\"Purisa\", taille=20)\n\t\t#On calcule son score final\n\t\ttempsATM = int(time()-temps[1])\n\t\ttempsSeconde = temps[0]*60 + tempsATM\n\t\tscore += int((1500/(0.25*tempsSeconde+1)) + 100*vie)\n\t\tcreation_interface(score, vie)\n\t\tsleep(1)\n\t\tif not modePerso[0] and score > highscore[-1][0]: #Verification meilleur score\n\t\t\tmeilleur_score(score, highscore)\n\n\twhile True:\n\t\tev = donne_evenement()\n\t\ttype_ev = type_evenement(ev)\n\t\tif type_ev == \"Touche\":\n\t\t\tt = touche(ev)\n\t\t\tif t == 'r':\n\t\t\t\tvariables_globales()\n\t\t\t\tferme_fenetre()\n\t\t\t\tif not modePerso[0]:\n\t\t\t\t\tlancement([False, None])\n\t\t\t\telse:\n\t\t\t\t\tlancement([True, main.lecture()])\n\t\t\telse:\n\t\t\t\tbreak\n\t\tmise_a_jour()\n\tferme_fenetre()" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5538881421089172, "avg_line_length": 28.34000015258789, "blob_id": "9816ea426c873b28246f5369904e9d79851afd03", "content_id": "628af16a9e2c1319e6323545bb955a89f36915a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1468, "license_type": "no_license", "max_line_length": 114, "num_lines": 50, "path": "/main.py", "repo_name": "Remy93130/Projet_Python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"Fonctions du menu principale du casse brique.\"\"\"\n# Imports --------------------------------------------------------------------------------------------------------\nfrom upemtk import *\nimport sys\nimport jeu\n\n# Fonctions ------------------------------------------------------------------------------------------------------\ndef interface_start():\n\t\"\"\"Creation de l interface de depart\"\"\"\n\tcree_fenetre(450, 450)\n\ttexte(225, 35, \"Bienvenue sur Relobrik\\n Choisissez un mode\", ancrage='center')\n\trectangle(10, 100, 440, 250, couleur='red', remplissage='red')\n\ttexte(225, 175, \"Mode challenge\", ancrage='center', taille=18)\n\trectangle(10, 270, 440, 420, couleur='blue', remplissage='blue')\n\ttexte(225, 345, \"Mode personnalisé\", ancrage='center', taille=18)\n\ndef lecture():\n\tbrique = list()\n\tfichier = open(\"brique_perso.txt\", 'r')\n\tfor ligne in fichier.readlines():\n\t\tif ligne[0] == '#':\n\t\t\tcontinue\n\t\telse:\n\t\t\tbriqueL = ligne.strip()[0:7]\n\t\t\tfor element in ligne.strip():\n\t\t\t\tbrique.append(int(element))\n\tfichier.close()\n\n\tif len(brique) != 7*10:\n\t\tprint(\"Il y a un probleme avec le niveau personnalisé\")\n\t\tsys.exit(0)\n\treturn brique\n\t\n\nif __name__ == '__main__':\n\t\n\tinterface_start()\n\twhile 1:\n\t\tx = attente_clic()\n\t\tif 10 < x[0] < 440:\n\t\t\tif 100 <= x[1] <= 250:\n\t\t\t\tferme_fenetre()\n\t\t\t\tjeu.lancement([False, None])\n\t\t\t\tbreak\n\t\t\tif 270 <= x[1] <= 420:\n\t\t\t\tferme_fenetre()\n\t\t\t\tjeu.lancement([True, lecture()])\n\t\t\t\tbreak" }, { "alpha_fraction": 0.563370943069458, "alphanum_fraction": 0.5846051573753357, "avg_line_length": 34.904762268066406, "blob_id": "14ec5bd7d34522aae5032e0b5daa4d2188902f43", "content_id": "ab05bc2817f75993e6a4e81b1d9f80f406776143", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1509, "license_type": "no_license", "max_line_length": 114, "num_lines": 42, "path": "/score.py", "repo_name": "Remy93130/Projet_Python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"Fonctions pour gerer les scores.\"\"\"\n# Imports --------------------------------------------------------------------------------------------------------\nfrom upemtk import *\n\nENTREE = \"meilleur_score\"\n\n# Fonctions ------------------------------------------------------------------------------------------------------\ndef lecture_score():\n\t\"\"\"Récupere les score dans le fichier score, les trie et les renvoie\"\"\"\n\tfichier = open(ENTREE, 'r')\n\tscore = list()\n\tfor ligne in fichier.readlines():\n\t\tligne = ligne.strip()\n\t\tscore.append(ligne.split(':'))\n\tfichier.close()\n\n\tfor element in score:\n\t\telement[0] = int(element[0])\n\tscore = sorted(score, key=lambda x: x[0], reverse=True)\n\treturn score\n\ndef affichage_score(score):\n\t\"\"\"Affiche les meilleur score sur le panneau de jeu\"\"\"\n\tdecal = 180\n\ttexte(320, 150, \"Meilleur Score\", taille=14)\n\tfor element in score:\n\t\ttexte(320, decal, element[1] + ' ' + str(element[0]), taille=10)\n\t\tdecal += 15\n\ndef meilleur_score(Nscore, highscore):\n\t\"\"\"Demande le nom du joueur et inscrit son score dans le fichier\"\"\"\n\tprint(\"Félicitation c'est un nouveau record\")\n\tnom = input(\"Entrez votre nom : \")\n\tnom = nom[0:3]\n\tprint(\"Bravo {} vous avez fait un score de {}. Il a bien ete enregistre !\".format(nom, Nscore))\n\thighscore.append([Nscore, nom])\n\thighscore = sorted(highscore, key=lambda x: x[0], reverse=True)\n\tfichier = open(ENTREE, 'w')\n\tfor i in range(10):\n\t\tfichier.write(\"{}:{}\\n\".format(highscore[i][0], highscore[i][1]))" } ]
4
luoyuan3316/mhc2flurry
https://github.com/luoyuan3316/mhc2flurry
7e9ef790fbceebc34e8f432dc594fc3a12bddab7
914dddfd708801a83615d0cc3d41dd3b19e45919
f8d7bf751f5596f46111f52f127a412c50b7c6a4
refs/heads/master
2023-04-16T14:27:36.602561
2021-04-26T14:09:56
2021-04-26T14:09:56
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6440930962562561, "alphanum_fraction": 0.6461814045906067, "avg_line_length": 29.198198318481445, "blob_id": "79388d95be367c33a0431e832effa6a3fa3aeb92", "content_id": "054d7549c43c600f505e848d326ed32231fde1b7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3352, "license_type": "permissive", "max_line_length": 79, "num_lines": 111, "path": "/downloads-generation/data_curated/annotate_proteins.py", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "\"\"\"\nGiven a CSV where some column indicates peptides, add a column indicating which\nprotein(s) from some specified proteome contain that peptide.\n\"\"\"\n\nimport argparse\nimport time\nimport sys\n\nimport tqdm\nimport pandas\nimport numpy\nimport shellinford\n\nfrom mhc2flurry.fasta import read_fasta_to_dataframe\n\nparser = argparse.ArgumentParser(usage=__doc__)\n\nparser.add_argument(\n \"reference\",\n metavar=\"FASTA\",\n help=\"Fasta proteome to search.\")\nparser.add_argument(\n \"--annotate\",\n action=\"append\",\n default=[],\n nargs=2,\n metavar=\"CSV\",\n help=\"Input and output file pairs. Specify this argument multiple times \"\n \"to process multiple input files, each of which will be written to its \"\n \"respective output file. The output file can be specified as '-' to \"\n \"overwrite the input file.\")\nparser.add_argument(\n \"--peptide-column\",\n default=\"peptide\",\n help=\"Name of column that gives peptides. Default: %(default)s\")\nparser.add_argument(\n \"--protein-column\",\n default=\"proteins\",\n help=\"Name of column to write proteins. Default: %(default)s\")\nparser.add_argument(\n \"--full-descriptions\",\n default=False,\n action=\"store_true\",\n help=\"Write the full protein descriptions, not just the IDs.\")\nparser.add_argument(\n \"--join-character\",\n default=\" \",\n help=\"Separator to use between protein names. Default: '%(default)s'\")\nparser.add_argument(\n \"--fm-index-suffix\",\n metavar=\"SUFFIX\",\n help=\"Use a pre-existing fm index found by concatenating SUFFIX onto each \"\n \"input fasta filename.\")\n\n\ndef run():\n args = parser.parse_args(sys.argv[1:])\n\n peptides = set()\n input_filename_df_and_output_filename = []\n\n for (input, output) in args.annotate:\n if output.strip() == \"-\":\n output = input\n df = pandas.read_csv(input)\n print(\"Read peptides\", input)\n print(df)\n input_filename_df_and_output_filename.append((input, df, output))\n peptides.update(df[args.peptide_column].unique())\n\n print(\"Read %d peptides to annotate\" % len(peptides))\n\n proteome_df = read_fasta_to_dataframe(\n args.reference, full_descriptions=args.full_descriptions)\n\n print(\"Read proteome:\")\n print(proteome_df)\n\n fm = shellinford.FMIndex()\n start = time.time()\n if args.fm_index_suffix:\n name = args.reference + args.fm_index_suffix\n print(\"Using pre-existing fm index\", name)\n fm.read(name)\n print(\"Read in %0.3f sec.\" % (time.time() - start))\n else:\n print(\"Building FM index\")\n fm.build(proteome_df.sequence.tolist())\n print(\"Built index of %d sequences in %0.3f sec.\" % (\n len(proteome_df), time.time() - start))\n\n print(\"Annotating peptides\")\n peptide_to_matches = {}\n for peptide in tqdm.tqdm(peptides):\n matches = [item.doc_id for item in fm.search(peptide)]\n names = args.join_character.join(\n proteome_df.loc[matches, \"sequence_id\"].values)\n peptide_to_matches[peptide] = names\n\n print(\"Writing files\")\n for (input, df, output) in input_filename_df_and_output_filename:\n print(input)\n df[args.protein_column] = df[args.peptide_column].map(\n peptide_to_matches)\n df.to_csv(output, index=False)\n print(\"Wrote\", output)\n\n\nif __name__ == '__main__':\n run()\n" }, { "alpha_fraction": 0.7184115648269653, "alphanum_fraction": 0.7220216393470764, "avg_line_length": 14.333333015441895, "blob_id": "cf85cc2c6d0cc6ab9c12c5beed396053d6e495bd", "content_id": "523482025945c2d0f6e6e24c9b686661400fdc37", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 277, "license_type": "permissive", "max_line_length": 71, "num_lines": 18, "path": "/README.md", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "# mhc2flurry\nMHC class II binding predictor, under development\n\nThis is mostly just scaffolding for experiments. No trained models yet.\n\n## Installation\nInstall using pip from a checkout:\n\n```\n$ pip install .\n```\n\nTo run the unit tests:\n\n```\n$ pip install pytest\n$ pytest\n```\n\n" }, { "alpha_fraction": 0.4914149343967438, "alphanum_fraction": 0.5824167132377625, "avg_line_length": 38.030364990234375, "blob_id": "dece8851b30c8c74af1815b6bd3b4008386fe7bc", "content_id": "db9b0a4884325f93c847584133c222b551c79f40", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 37274, "license_type": "permissive", "max_line_length": 165, "num_lines": 955, "path": "/downloads-generation/data_curated/curate_ms_by_pmid.py", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "\"\"\"\nFilter and combine various peptide/MHC datasets to derive a composite training set,\noptionally including eluted peptides identified by mass-spec.\n\nThe handle_pmid_XXXX functions should return a DataFrame with columns:\n - peptide\n - sample_id\n - hla [space separated list of alleles]\n - pulldown_antibody\n - format [monoallelic, multiallelic, DR-specific]\n - mhc_class [should be II]\n - sample type [an expression group, e.g. \"spleen\" or \"expi293\"]\n - cell_line [for samples deriving from a single known cell line]\n\"\"\"\nimport sys\nimport argparse\nimport os\nimport json\nimport collections\nfrom six.moves import StringIO\n\nfrom mhc2flurry.common import normalize_allele_name\n\n\nimport pandas\n\nparser = argparse.ArgumentParser(usage=__doc__)\n\nparser.add_argument(\n \"--ms-item\",\n nargs=\"+\",\n action=\"append\",\n metavar=\"PMID FILE, ... FILE\",\n default=[],\n help=\"Mass spec item to curate: PMID and list of files\")\nparser.add_argument(\n \"--expression-item\",\n nargs=\"+\",\n action=\"append\",\n metavar=\"LABEL FILE, ... FILE\",\n default=[],\n help=\"Expression data to curate: dataset label and list of files\")\nparser.add_argument(\n \"--ms-out\",\n metavar=\"OUT.csv\",\n help=\"Out file path (MS data)\")\nparser.add_argument(\n \"--expression-out\",\n metavar=\"OUT.csv\",\n help=\"Out file path (RNA-seq expression)\")\nparser.add_argument(\n \"--expression-metadata-out\",\n metavar=\"OUT.csv\",\n help=\"Out file path for expression metadata, i.e. which samples used\")\nparser.add_argument(\n \"--debug\",\n action=\"store_true\",\n default=False,\n help=\"Leave user in pdb if PMID is unsupported\")\n\nPMID_HANDLERS = {}\nEXPRESSION_HANDLERS = {}\n\n\ndef load(filenames, **kwargs):\n result = {}\n for filename in filenames:\n if filename.endswith(\".csv\"):\n result[filename] = pandas.read_csv(filename, **kwargs)\n elif filename.endswith(\".xlsx\") or filename.endswith(\".xls\"):\n result[filename] = pandas.read_excel(filename, **kwargs)\n else:\n result[filename] = filename\n\n return result\n\n\ndef debug(*filenames):\n loaded = load(filenames)\n import ipdb\n ipdb.set_trace()\n\n\n\nPMID_31495665_SAMPLE_TYPES = {\n \"HLA-DR_A375\": \"a375\",\n \"HLA-DR_Lung\": \"lung\",\n \"HLA-DR_PBMC_HDSC\": \"pbmc\",\n \"HLA-DR_PBMC_RG1095\": \"pbmc\",\n \"HLA-DR_PBMC_RG1104\": \"pbmc\",\n \"HLA-DR_PBMC_RG1248\": \"pbmc\",\n \"HLA-DR_SILAC_Donor1_10minLysate\": \"pbmc\",\n \"HLA-DR_SILAC_Donor1_5hrLysate\": \"pbmc\",\n \"HLA-DR_SILAC_Donor1_DConly\": \"pbmc\",\n \"HLA-DR_SILAC_Donor1_UVovernight\": \"pbmc\",\n \"HLA-DR_SILAC_Donor2_DC_UV_16hr\": \"pbmc\",\n \"HLA-DR_SILAC_Donor2_DC_UV_24hr\": \"pbmc\",\n \"HLA-DR_Spleen\": \"spleen\",\n \"MAPTAC_A*02:01\": \"mix:a375,expi293,hek293,hela\",\n \"MAPTAC_A*11:01\": \"mix:expi293,hela\",\n \"MAPTAC_A*32:01\": \"mix:a375,expi293,hela\",\n \"MAPTAC_B*07:02\": \"mix:a375,expi293,hela\",\n \"MAPTAC_B*45:01\": \"expi293\",\n \"MAPTAC_B*52:01\": \"mix:a375,expi293\",\n \"MAPTAC_C*03:03\": \"expi293\",\n \"MAPTAC_C*06:02\": \"mix:a375,expi293\",\n \"MAPTAC_DPB1*06:01/DPA1*01:03_dm+\": \"expi293\",\n \"MAPTAC_DPB1*06:01/DPA1*01:03_dm-\": \"expi293\",\n \"MAPTAC_DQB1*06:04/DQA1*01:02_dm+\": \"expi293\",\n \"MAPTAC_DQB1*06:04/DQA1*01:02_dm-\": \"expi293\",\n \"MAPTAC_DRB1*01:01\": \"mix:a375,b721,expi293,kg1,k562\",\n \"MAPTAC_DRB1*03:01\": \"expi293\",\n \"MAPTAC_DRB1*04:01\": \"expi293\",\n \"MAPTAC_DRB1*07:01\": \"mix:expi293,hek293\",\n \"MAPTAC_DRB1*11:01\": \"mix:expi293,k562,kg1\",\n \"MAPTAC_DRB1*12:01_dm+\": \"expi293\",\n \"MAPTAC_DRB1*12:01_dm-\": \"expi293\",\n \"MAPTAC_DRB1*15:01\": \"expi293\",\n \"MAPTAC_DRB3*01:01_dm+\": \"expi293\",\n \"MAPTAC_DRB3*01:01_dm-\": \"expi293\",\n}\nCELL_LINE_MIXTURES = sorted(\n set(\n x for x in PMID_31495665_SAMPLE_TYPES.values()\n if x.startswith(\"mix:\")))\n\n\ndef handle_pmid_25502872(filename):\n \"\"\"Bergseng, ..., Sollid. Immunogenetics 2015 [PMID 25502872]\"\"\"\n return None\n\n\ndef handle_pmid_26495903(*filenames):\n \"\"\"Sofron, ..., Fugmann. Eur. J. Immunol. 2015 [PMID 26495903]\"\"\"\n return None\n\n\ndef handle_pmid_26740625(*filenames):\n \"\"\"Clement, ..., Santambrogio. J. Biol. Chem. 2016 [PMID 26740625]\"\"\"\n # Mouse with transgenic DRB*01:01, collected about 3,000 peptides.\n # Peptides are mouse-derived, MHC II is human.\n return None\n\n\ndef handle_pmid_27452731(*filenames):\n \"\"\"Heyder, ..., Ytterberg. Mol. Cell. Proteomics 2016 [PMID 27452731]\"\"\"\n return None\n\n\ndef handle_pmid_27726376(*filenames):\n \"\"\"Wang, ..., Costello. J. Proteom. Res. 2017\"\"\"\n return None\n\n\ndef handle_pmid_28329770(*filenames):\n \"\"\"Khodadoust, ..., Alizadeh. Nature 2017 [PMID 28329770]\"\"\"\n return None\n\n\ndef handle_pmid_28467828(filename):\n \"\"\"Ooi, ..., Kitching. Nature 2017 [PMID 28467828]\"\"\"\n return None\n\n\ndef handle_pmid_29314611(filename):\n \"\"\"Ritz, ..., Fugmann. Proteomics 2018 [PMID 29314611]\"\"\"\n\n hla_types = {\n \"MAVER-1\": \"DRB1*01:01 DRB1*13:01 DRB3*02:02 DQA1*01:01 DQB1*05:01 DQA1*01:03 DQB1*06:03\",\n \"DOHH2\": \"DRB1*01:01 DRB1*15:01 DRB5*01:01 DQA1*01:01 DQB1*05:01 DQB1*06:02 DQA1*01:02\",\n }\n pulldown_antibody = {\n \"DR\": \"L243 (HLA-DR)\",\n \"DQ\": \"SPVL3 (HLA-DQ)\",\n }\n format = {\n \"DR\": \"DR-specific\",\n \"DQ\": \"DQ-specific\",\n }\n result_dfs = []\n dfs = pandas.read_excel(\n filename, sheet_name=None, skiprows=1, index_col=\"Sequence\")\n\n for (label, df) in dfs.items():\n label = label.upper()\n (cell_line, restriction) = label.split(\"_\")\n result_df = pandas.DataFrame({\"peptide\": df.index.values})\n result_df[\"sample_id\"] = label\n result_df[\"cell_line\"] = cell_line\n result_df[\"sample_type\"] = \"B-CELL\"\n result_df[\"mhc_class\"] = \"II\"\n result_df[\"hla\"] = hla_types[cell_line]\n result_df[\"pulldown_antibody\"] = pulldown_antibody[restriction]\n result_df[\"format\"] = format[restriction]\n result_dfs.append(result_df)\n\n result_df = pandas.concat(result_dfs, ignore_index=True)\n return result_df\n\n\ndef handle_pmid_29317506(*filenames):\n \"\"\"Ting, ..., Rossjohn. J. Biol. Chem. 2018 [PMID 29317506]\"\"\"\n return None\n\n\ndef handle_pmid_29632711(*filenames):\n \"\"\"Nelde, ..., Walz. Oncoimmunology 2018 [PMID 29632711]\"\"\"\n return None\n\n\ndef handle_pmid_31495665(filename):\n \"\"\"Abelin, ..., Rooney Immunity 2019 [PMID 31495665]\"\"\"\n hla_type = {\n \"HLA-DR_A375\": \"DRB1*07:01 DRB4*01:01 DRB1*04:05\",\n \"HLA-DR_Lung\": \"DRB1*01:01 DRB1*03:01 DRB3*01:01\",\n \"HLA-DR_PBMC_HDSC\": \"DRB1*03:01 DRB1*11:01 DRB3*01:01 DRB3*02:02\",\n \"HLA-DR_PBMC_RG1095\": \"DRB1*03:01 DRB1*11:01 DRB3*01:01 DRB3*02:02\",\n \"HLA-DR_PBMC_RG1104\": \"DRB1*01:01 DRB1*11:01 DRB3*02:02\",\n \"HLA-DR_PBMC_RG1248\": \"DRB1*03:01 DRB1*03:01 DRB3*01:01 DRB3*01:01\",\n\n # Note: the paper and Data S1 are pretty confusing regarding the donor1\n # and donor2 SILAC experiments. These HLA types are a best guess but\n # I am not 100% confident.\n \"HLA-DR_SILAC_Donor1_10minLysate\": \"DRB1*07:01 DRB4*01:01\",\n \"HLA-DR_SILAC_Donor1_5hrLysate\": \"DRB1*07:01 DRB4*01:01\",\n \"HLA-DR_SILAC_Donor1_DConly\": \"DRB1*07:01 DRB4*01:01\",\n \"HLA-DR_SILAC_Donor1_UVovernight\": \"DRB1*07:01 DRB4*01:01\",\n \"HLA-DR_SILAC_Donor2_DC_UV_16hr\": \"DRB1*04:01 DRB4*01:03 DRB1*15:03 DRB5*01:01 DQB1*03:02 DQA1*01:02 DQB1*06:02 DQA1*03:01 DPB1*02:01 DPA1*01:03 DPB1*04:01\",\n \"HLA-DR_SILAC_Donor2_DC_UV_24hr\": \"DRB1*04:01 DRB4*01:03 DRB1*15:03 DRB5*01:01 DQB1*03:02 DQA1*01:02 DQB1*06:02 DQA1*03:01 DPB1*02:01 DPA1*01:03 DPB1*04:01\",\n \"HLA-DR_Spleen\": \"DRB1*04:01 DRB4*01:03 DRB1*15:03 DRB5*01:01\",\n \"MAPTAC_A*02:01\": \"HLA-A*02:01\",\n \"MAPTAC_A*11:01\": \"HLA-A*11:01\",\n \"MAPTAC_A*32:01\": \"HLA-A*32:01\",\n \"MAPTAC_B*07:02\": \"HLA-B*07:02\",\n \"MAPTAC_B*45:01\": \"HLA-B*45:01\",\n \"MAPTAC_B*52:01\": \"HLA-B*52:01\",\n \"MAPTAC_C*03:03\": \"HLA-C*03:03\",\n \"MAPTAC_C*06:02\": \"HLA-C*06:02\",\n \"MAPTAC_DPB1*06:01/DPA1*01:03_dm+\": \"DPA1*01:03 DPB1*06:01\",\n \"MAPTAC_DPB1*06:01/DPA1*01:03_dm-\": \"DPA1*01:03 DPB1*06:01\",\n \"MAPTAC_DQB1*06:04/DQA1*01:02_dm+\": \"DQA1*01:02 DQB1*06:04\",\n \"MAPTAC_DQB1*06:04/DQA1*01:02_dm-\": \"DQA1*01:02 DQB1*06:04\",\n \"MAPTAC_DRB1*01:01\": \"DRB1*01:01\",\n \"MAPTAC_DRB1*03:01\": \"DRB1*03:01\",\n \"MAPTAC_DRB1*04:01\": \"DRB1*04:01\",\n \"MAPTAC_DRB1*07:01\": \"DRB1*07:01\",\n \"MAPTAC_DRB1*11:01\": \"DRB1*11:01\",\n \"MAPTAC_DRB1*12:01_dm+\": \"DRB1*12:01\",\n \"MAPTAC_DRB1*12:01_dm-\": \"DRB1*12:01\",\n \"MAPTAC_DRB1*15:01\": \"DRB1*15:01\",\n \"MAPTAC_DRB3*01:01_dm+\": \"DRB3*01:01\",\n \"MAPTAC_DRB3*01:01_dm-\": \"DRB3*01:01\",\n }\n pulldown_antibody = {\n \"HLA-DR_A375\": \"L243+tal1b5 (HLA-DR)\",\n \"HLA-DR_Lung\": \"L243 (HLA-DR)\",\n \"HLA-DR_PBMC_HDSC\": \"tal1b5 (HLA-DR)\",\n \"HLA-DR_PBMC_RG1095\": \"tal1b5 (HLA-DR)\",\n \"HLA-DR_PBMC_RG1104\": \"tal1b5 (HLA-DR)\",\n \"HLA-DR_PBMC_RG1248\": \"tal1b5 (HLA-DR)\",\n \"HLA-DR_SILAC_Donor1_10minLysate\": \"L243 (HLA-DR)\",\n \"HLA-DR_SILAC_Donor1_5hrLysate\": \"L243 (HLA-DR)\",\n \"HLA-DR_SILAC_Donor1_DConly\": \"L243 (HLA-DR)\",\n \"HLA-DR_SILAC_Donor1_UVovernight\": \"L243 (HLA-DR)\",\n \"HLA-DR_SILAC_Donor2_DC_UV_16hr\": \"L243 (HLA-DR)\",\n \"HLA-DR_SILAC_Donor2_DC_UV_24hr\": \"L243 (HLA-DR)\",\n \"HLA-DR_Spleen\": \"L243 (HLA-DR)\",\n \"MAPTAC_A*02:01\": \"MAPTAC\",\n \"MAPTAC_A*11:01\": \"MAPTAC\",\n \"MAPTAC_A*32:01\": \"MAPTAC\",\n \"MAPTAC_B*07:02\": \"MAPTAC\",\n \"MAPTAC_B*45:01\": \"MAPTAC\",\n \"MAPTAC_B*52:01\": \"MAPTAC\",\n \"MAPTAC_C*03:03\": \"MAPTAC\",\n \"MAPTAC_C*06:02\": \"MAPTAC\",\n \"MAPTAC_DPB1*06:01/DPA1*01:03_dm+\": \"MAPTAC\",\n \"MAPTAC_DPB1*06:01/DPA1*01:03_dm-\": \"MAPTAC\",\n \"MAPTAC_DQB1*06:04/DQA1*01:02_dm+\": \"MAPTAC\",\n \"MAPTAC_DQB1*06:04/DQA1*01:02_dm-\": \"MAPTAC\",\n \"MAPTAC_DRB1*01:01\": \"MAPTAC\",\n \"MAPTAC_DRB1*03:01\": \"MAPTAC\",\n \"MAPTAC_DRB1*04:01\": \"MAPTAC\",\n \"MAPTAC_DRB1*07:01\": \"MAPTAC\",\n \"MAPTAC_DRB1*11:01\": \"MAPTAC\",\n \"MAPTAC_DRB1*12:01_dm+\": \"MAPTAC\",\n \"MAPTAC_DRB1*12:01_dm-\": \"MAPTAC\",\n \"MAPTAC_DRB1*15:01\": \"MAPTAC\",\n \"MAPTAC_DRB3*01:01_dm+\": \"MAPTAC\",\n \"MAPTAC_DRB3*01:01_dm-\": \"MAPTAC\",\n }\n format = {\n \"HLA-DR_A375\": \"DR-specific\",\n \"HLA-DR_Lung\": \"DR-specific\",\n \"HLA-DR_PBMC_HDSC\": \"DR-specific\",\n \"HLA-DR_PBMC_RG1095\": \"DR-specific\",\n \"HLA-DR_PBMC_RG1104\": \"DR-specific\",\n \"HLA-DR_PBMC_RG1248\": \"DR-specific\",\n \"HLA-DR_SILAC_Donor1_10minLysate\": \"DR-specific\",\n \"HLA-DR_SILAC_Donor1_5hrLysate\": \"DR-specific\",\n \"HLA-DR_SILAC_Donor1_DConly\": \"DR-specific\",\n \"HLA-DR_SILAC_Donor1_UVovernight\": \"DR-specific\",\n \"HLA-DR_SILAC_Donor2_DC_UV_16hr\": \"DR-specific\",\n \"HLA-DR_SILAC_Donor2_DC_UV_24hr\": \"DR-specific\",\n \"HLA-DR_Spleen\": \"DR-specific\",\n \"MAPTAC_A*02:01\": \"monoallelic\",\n \"MAPTAC_A*11:01\": \"monoallelic\",\n \"MAPTAC_A*32:01\": \"monoallelic\",\n \"MAPTAC_B*07:02\": \"monoallelic\",\n \"MAPTAC_B*45:01\": \"monoallelic\",\n \"MAPTAC_B*52:01\": \"monoallelic\",\n \"MAPTAC_C*03:03\": \"monoallelic\",\n \"MAPTAC_C*06:02\": \"monoallelic\",\n \"MAPTAC_DPB1*06:01/DPA1*01:03_dm+\": \"monoallelic\",\n \"MAPTAC_DPB1*06:01/DPA1*01:03_dm-\": \"monoallelic\",\n \"MAPTAC_DQB1*06:04/DQA1*01:02_dm+\": \"monoallelic\",\n \"MAPTAC_DQB1*06:04/DQA1*01:02_dm-\": \"monoallelic\",\n \"MAPTAC_DRB1*01:01\": \"monoallelic\",\n \"MAPTAC_DRB1*03:01\": \"monoallelic\",\n \"MAPTAC_DRB1*04:01\": \"monoallelic\",\n \"MAPTAC_DRB1*07:01\": \"monoallelic\",\n \"MAPTAC_DRB1*11:01\": \"monoallelic\",\n \"MAPTAC_DRB1*12:01_dm+\": \"monoallelic\",\n \"MAPTAC_DRB1*12:01_dm-\": \"monoallelic\",\n \"MAPTAC_DRB1*15:01\": \"monoallelic\",\n \"MAPTAC_DRB3*01:01_dm+\": \"monoallelic\",\n \"MAPTAC_DRB3*01:01_dm-\": \"monoallelic\",\n }\n mhc_class = {\n \"HLA-DR_A375\": \"II\",\n \"HLA-DR_Lung\": \"II\",\n \"HLA-DR_PBMC_HDSC\": \"II\",\n \"HLA-DR_PBMC_RG1095\": \"II\",\n \"HLA-DR_PBMC_RG1104\": \"II\",\n \"HLA-DR_PBMC_RG1248\": \"II\",\n \"HLA-DR_SILAC_Donor1_10minLysate\": \"II\",\n \"HLA-DR_SILAC_Donor1_5hrLysate\": \"II\",\n \"HLA-DR_SILAC_Donor1_DConly\": \"II\",\n \"HLA-DR_SILAC_Donor1_UVovernight\": \"II\",\n \"HLA-DR_SILAC_Donor2_DC_UV_16hr\": \"II\",\n \"HLA-DR_SILAC_Donor2_DC_UV_24hr\": \"II\",\n \"HLA-DR_Spleen\": \"II\",\n \"MAPTAC_A*02:01\": \"I\",\n \"MAPTAC_A*11:01\": \"I\",\n \"MAPTAC_A*32:01\": \"I\",\n \"MAPTAC_B*07:02\": \"I\",\n \"MAPTAC_B*45:01\": \"I\",\n \"MAPTAC_B*52:01\": \"I\",\n \"MAPTAC_C*03:03\": \"I\",\n \"MAPTAC_C*06:02\": \"I\",\n \"MAPTAC_DPB1*06:01/DPA1*01:03_dm+\": \"II\",\n \"MAPTAC_DPB1*06:01/DPA1*01:03_dm-\": \"II\",\n \"MAPTAC_DQB1*06:04/DQA1*01:02_dm+\": \"II\",\n \"MAPTAC_DQB1*06:04/DQA1*01:02_dm-\": \"II\",\n \"MAPTAC_DRB1*01:01\": \"II\",\n \"MAPTAC_DRB1*03:01\": \"II\",\n \"MAPTAC_DRB1*04:01\": \"II\",\n \"MAPTAC_DRB1*07:01\": \"II\",\n \"MAPTAC_DRB1*11:01\": \"II\",\n \"MAPTAC_DRB1*12:01_dm+\": \"II\",\n \"MAPTAC_DRB1*12:01_dm-\": \"II\",\n \"MAPTAC_DRB1*15:01\": \"II\",\n \"MAPTAC_DRB3*01:01_dm+\": \"II\",\n \"MAPTAC_DRB3*01:01_dm-\": \"II\",\n }\n cell_line = {\n \"HLA-DR_A375\": \"A375\",\n \"HLA-DR_Lung\": \"\",\n \"HLA-DR_PBMC_HDSC\": \"\",\n \"HLA-DR_PBMC_RG1095\": \"\",\n \"HLA-DR_PBMC_RG1104\": \"\",\n \"HLA-DR_PBMC_RG1248\": \"\",\n \"HLA-DR_SILAC_Donor1_10minLysate\": \"\",\n \"HLA-DR_SILAC_Donor1_5hrLysate\": \"\",\n \"HLA-DR_SILAC_Donor1_DConly\": \"\",\n \"HLA-DR_SILAC_Donor1_UVovernight\": \"\",\n \"HLA-DR_SILAC_Donor2_DC_UV_16hr\": \"\",\n \"HLA-DR_SILAC_Donor2_DC_UV_24hr\": \"\",\n \"HLA-DR_Spleen\": \"L243 (HLA-DR)\",\n \"HLA-DR_Spleen\": \"\",\n \"MAPTAC_A*02:01\": \"\",\n \"MAPTAC_A*11:01\": \"\",\n \"MAPTAC_A*32:01\": \"\",\n \"MAPTAC_B*07:02\": \"\",\n \"MAPTAC_B*45:01\": \"expi293\",\n \"MAPTAC_B*52:01\": \"\",\n \"MAPTAC_C*03:03\": \"expi293\",\n \"MAPTAC_C*06:02\": \"\",\n \"MAPTAC_DPB1*06:01/DPA1*01:03_dm+\": \"expi293\",\n \"MAPTAC_DPB1*06:01/DPA1*01:03_dm-\": \"expi293\",\n \"MAPTAC_DQB1*06:04/DQA1*01:02_dm+\": \"expi293\", # don't actually see this in DataS1A!\n \"MAPTAC_DQB1*06:04/DQA1*01:02_dm-\": \"expi293\",\n \"MAPTAC_DRB1*01:01\": \"\",\n \"MAPTAC_DRB1*03:01\": \"expi293\",\n \"MAPTAC_DRB1*04:01\": \"expi293\",\n \"MAPTAC_DRB1*07:01\": \"\",\n \"MAPTAC_DRB1*11:01\": \"\",\n \"MAPTAC_DRB1*12:01_dm+\": \"expi293\",\n \"MAPTAC_DRB1*12:01_dm-\": \"expi293\",\n \"MAPTAC_DRB1*15:01\": \"expi293\",\n \"MAPTAC_DRB3*01:01_dm+\": \"expi293\",\n \"MAPTAC_DRB3*01:01_dm-\": \"expi293\",\n }\n\n df = pandas.read_excel(filename, sheet_name=\"DataS1B\")\n results = []\n for sample_id in df.columns:\n if hla_type[sample_id] is None:\n print(\"Intentionally skipping\", sample_id)\n continue\n\n result_df = pandas.DataFrame({\n \"peptide\": df[sample_id].dropna().values,\n })\n result_df[\"sample_id\"] = sample_id\n result_df[\"hla\"] = hla_type[sample_id]\n result_df[\"pulldown_antibody\"] = pulldown_antibody[sample_id]\n result_df[\"format\"] = format[sample_id]\n result_df[\"mhc_class\"] = mhc_class[sample_id]\n result_df[\"sample_type\"] = PMID_31495665_SAMPLE_TYPES[sample_id]\n result_df[\"cell_line\"] = cell_line[sample_id]\n results.append(result_df)\n result_df = pandas.concat(results, ignore_index=True)\n result_df = result_df.loc[\n result_df.mhc_class == \"II\"\n ]\n return result_df\n\n\ndef handle_pmid_31611696(data_s1_filename, data_s2_filename):\n \"\"\"Racle, ..., Gfeller. Nature Biotechnology 2019 [PMID 31611696]\"\"\"\n data_s1 = pandas.read_csv(\n data_s1_filename, sep=None, engine=\"python\").set_index(\"Sequence\")\n data_s2 = pandas.read_csv(\n data_s2_filename, sep=None, engine=\"python\").set_index(\"Sequence\")\n\n # HLA typing is given as a PDF in Supplementary Table 1.\n # In cases of ambiguous assignment we use the primary assignment.\n text = \"\"\"\n 3808_HMC MENINGIOMA DRB1*03:01 DRB1*07:01 DRB3*01:01 DRB4*01:01 DPA1*01:03 DPA1*02:01 DPB1*03:01 DPB1*11:01 DQA1*02:01 DQA1*05:01 DQB1*02:01 DQB1*02:02\n 3830_NJF MENINGIOMA DRB1*04:04 DRB1*11:01 DRB3*02:02 DRB4*01:03 DPA1*01:03 DPB1*02:01 DPB1*06:01 DQA1*03:01 DQA1*05:05 DQB1*03:01 DQB1*03:02\n 3849BR MENINGIOMA DRB1*11:04 DRB3*02:02 DPA1*01:03 DPB1*02:01 DPB1*04:01 DQA1*05:05 DQB1*03:01\n 3865_DM MENINGIOMA DRB1*01:01 DRB1*07:01 DRB4*01:03 DPA1*01:03 DPB1*04:01 DPB1*20:01 DQA1*01:01 DQA1*02:01 DQB1*03:03 DQB1*05:01\n 3869_GA MENINGIOMA DRB1*01:03 DRB1*04:04 DRB4*01:03 DPA1*01:03 DPB1*04:01 DPB1*126:01 DQA1*03:01 DQA1*05:05 DQB1*03:01 DQB1*03:02\n 3911_ME MENINGIOMA DRB1*11:01 DRB3*02:02 DPA1*01:03 DPB1*04:01 DQA1*05:05 DQB1*03:01\n 3912_BAM MENINGIOMA DRB1*03:01 DRB1*04:01 DRB3*01:01 DRB4*01:03 DPA1*01:03 DPB1*04:01 DQA1*03:01 DQA1*05:01 DQB1*02:01 DQB1*03:02\n 3947_GA MENINGIOMA DRB1*01:01 DRB1*13:01 DRB3*01:01 DPA1*01:03 DPB1*02:01 DPB1*04:02 DQA1*01:01 DQA1*01:03 DQB1*05:01 DQB1*06:03\n 3971_ORA MENINGIOMA DRB1*13:03 DRB1*07:01 DRB3*01:01 DRB4*01:01 DPA1*01:03 DPA1*02:02 DPB1*04:01 DQA1*02:01 DQA1*05:05 DQB1*02:02 DQB1*03:01\n 3993 MENINGIOMA DRB1*07:01 DRB1*15:01 DRB4*01:03 DRB5*01:01 DPA1*01:03 DPA1*02:01 DPB1*04:01 DPB1*17:01 DQA1*01:02 DQA1*02:01 DQB1*02:02 DQB1*06:02\n 4001 MENINGIOMA DRB1*13:01 DRB1*14:01 DRB3*01:01 DRB3*02:02 DPA1*01:03 DPB1*04:01 DPB1*04:02 DQA1*01:03 DQA1*01:04 DQB1*05:03 DQB1*06:03\n 4021 MENINGIOMA DRB1*11:01 DRB1*04:05 DRB3*02:02 DRB4*01:03 DPA1*01:03 DPB1*03:01 DPB1*104:01 DQA1*03:03 DQA1*05:05 DQB1*02:02 DQB1*03:01\n 4037_DC MENINGIOMA DRB1*01:01 DPA1*01:03 DPB1*04:01 DPB1*06:01 DQA1*01:01 DQB1*05:01\n 4052_BA MENINGIOMA DRB1*03:01 DRB1*11:04 DRB3*01:01 DRB3*02:02 DPA1*01:03 DPB1*04:01 DQA1*05:01 DQA1*05:05 DQB1*02:01 DQB1*03:01\n BP455 B-CELL DRB1*10:01 DRB1*13:01 DRB3*01:01 DPA1*01:03 DPB1*02:01 DQA1*01:05 DQA1*01:10 DQB1*05:01 DQB1*06:03\n CD165 B-CELL DRB1*11:01 DRB3*02:02 DPA1*01:03 DPB1*04:01 DPB1*04:02 DQA1*05:05 DQB1*03:01\n CM647 B-CELL DRB1*07:01 DRB1*16:01 DRB4*01:03 DRB5*02:02 DPA1*01:03 DPB1*02:01 DPB1*23:01 DQA1*01:02 DQA1*02:01 DQB1*02:02 DQB1*05:02\n GD149 B-CELL DRB1*07:01 DRB1*13:01 DRB3*01:01 DRB4*01:01 DPA1*01:03 DPA1*02:01 DPB1*03:01 DPB1*04:01 DQA1*01:10 DQA1*02:01 DQB1*02:02 DQB1*06:03\n JY B-CELL DRB1*04:04 DRB1*13:01 DRB3*01:01 DRB4*01:03 DPA1*01:03 DPB1*02:01 DPB1*04:01 DQA1*01:03 DQA1*03:01 DQB1*03:02 DQB1*06:03\n PD42 B-CELL DRB1*01:02 DRB1*15:01 DRB5*01:01 DPA1*01:03 DPA1*02:02 DPB1*04:01 DPB1*05:01 DQA1*01:01 DQA1*01:02 DQB1*05:01 DQB1*06:02\n RA957 B-CELL DRB1*04:01 DRB1*08:01 DRB4*01:03 DPA1*01:03 DPB1*04:01 DPB1*04:02 DQA1*03:03 DQA1*04:01 DQB1*03:01 DQB1*04:02\n TIL1 TIL DRB1*01:01 DRB1*04:08 DRB4*01:03 DPA1*01:03 DPB1*02:01 DPB1*04:01 DQA1*01:01 DQA1*03:03 DQB1*03:01 DQB1*05:01\n TIL3 TIL DRB1*12:01 DRB1*15:01 DRB3*02:02 DRB5*01:01 DPA1*01:03 DPB1*03:01 DPB1*04:01 DQA1*01:02 DQA1*05:05 DQB1*03:01 DQB1*05:02\n \"\"\"\n rows = [\n row.split() for row in text.strip().split(\"\\n\")\n ]\n rows = [\n (row[0].replace(\"_\", \"-\"), row[1], \" \".join(row[2:])) for row in rows\n ]\n info_df = pandas.DataFrame(rows, columns=[\"kind\", \"sample_type\", \"hla\"])\n info_df = info_df.set_index(\"kind\")\n\n # Data S1\n renames = {\n c : c.replace(\"Intensity\", \"\").replace(\"_II\", \"\").strip()\n for c in data_s1.columns if c.startswith(\"Intensity\")\n }\n\n data_s1 = data_s1[sorted(renames)].rename(columns=renames).rename(columns={\n \"3830NJF\": \"3830-NJF\",\n \"3865DM\": \"3865-DM\",\n \"3912BAM\": \"3912-BAM\",\n \"3865DM\": \"3865-DM\",\n \"CD165_ IFNg\": \"CD165_IFNg\",\n })\n\n result1_df = data_s1.stack().reset_index()\n result1_df.columns = [\"peptide\", \"sample_id\", \"intensity\"]\n result1_df = result1_df.loc[result1_df.intensity > 0]\n result1_df[\"kind\"] = result1_df.sample_id.map(lambda s: {\n \"JY_DR\": \"JY\",\n \"CD165_IFNg\": \"CD165\",\n }.get(s, s))\n result1_df[\"hla\"] = result1_df.kind.map(info_df.hla)\n result1_df[\"pulldown_antibody\"] = \"HB145\"\n result1_df[\"format\"] = \"MULTIALLELIC\"\n result1_df.loc[\n result1_df.sample_id == \"JY_DR\",\n \"format\"\n ] = \"DR-specific\"\n result1_df[\"mhc_class\"] = \"II\"\n result1_df[\"sample_type\"] = result1_df.kind.map(info_df.sample_type)\n result1_df[\"cell_line\"] = [\n row.kind if row.sample_type == \"B-CELL\" else \"\"\n for _, row in result1_df.iterrows()\n ]\n del result1_df[\"kind\"]\n\n # Data S2\n renames = {\n c : c.replace(\"Intensity\", \"\").replace(\"_II\", \"\").strip()\n for c in data_s2.columns if c.startswith(\"Intensity\")\n }\n\n data_s2 = data_s2[sorted(renames)].rename(columns=renames).rename(columns={\n \"3830NJF\": \"3830-NJF\",\n \"3865DM\": \"3865-DM\",\n \"3912BAM\": \"3912-BAM\",\n \"3865DM\": \"3865-DM\",\n \"CD165_ IFNg\": \"CD165_IFNg\",\n })\n result2_df = data_s2.stack().reset_index()\n result2_df.columns = [\"peptide\", \"sample_id\", \"intensity\"]\n result2_df[\"kind\"] = result2_df.sample_id.str.replace(\n \"-HLA-DR\", \"\").str.replace(\"-depleted\", \"\").str.replace(\"_\", \"-\")\n result2_df[\"hla\"] = result2_df.kind.map(info_df.hla)\n result2_df[\"pulldown_antibody\"] = \"\"\n assert all(result2_df.sample_id.map(\n lambda s: s.endswith(\"DR-depleted\") or s.endswith(\"-DR\")))\n result2_df[\"format\"] = result2_df.sample_id.map(\n lambda s: \"DR-depleted\" if \"DR-depleted\" in s else \"DR-specific\")\n\n result2_df[\"mhc_class\"] = \"II\"\n result2_df[\"sample_type\"] = result2_df.kind.map(info_df.sample_type)\n result2_df[\"cell_line\"] = [\n row.kind if row.sample_type == \"B-CELL\" else \"\" for _, row in\n result2_df.iterrows()\n ]\n del result2_df[\"kind\"]\n result_df = pandas.concat([result1_df, result2_df], ignore_index=True)\n\n # DR-specific samples used HB298 antibody\n result_df.loc[\n result_df.format == \"DR-specific\",\n \"pulldown_antibody\"\n ] = \"HB298\"\n\n # Subsample alleles to just DR alleles for DR-specific samples.\n result_df.loc[\n result_df.format == \"DR-specific\",\n \"hla\"\n ] = result_df.loc[result_df.format == \"DR-specific\", \"hla\"].map(\n lambda s: \" \".join([allele for allele in s.split() if \"DR\" in allele])\n )\n del result_df[\"intensity\"]\n return result_df\n\n\ndef handle_pmid_27869121(filename):\n \"\"\"Bassani-Sternberg, ..., Krackhardt Nature Comm. 2016 [PMID 27869121]\"\"\"\n # While this data set includes class II ligands, unfortunately the HLA\n # typing (Supp Table 2) seems to be class I only. So we skip this dataset.\n return None\n\n\nEXPRESSION_GROUPS_ROWS = []\n\n\ndef make_expression_groups(dataset_identifier, df, groups):\n result_df = pandas.DataFrame(index=df.index)\n for (label, columns) in groups.items():\n for col in columns:\n if col not in df.columns:\n raise ValueError(\n \"Missing: %s. Available: %s\" % (col, df.columns.tolist()))\n result_df[label] = df[columns].mean(1)\n EXPRESSION_GROUPS_ROWS.append((dataset_identifier, label, columns))\n return result_df\n\n\ndef handle_expression_GSE113126(*filenames):\n \"\"\"\n Barry, ..., Krummel Nature Medicine 2018 [PMID 29942093]\n\n This is the melanoma met RNA-seq dataset.\n\n \"\"\"\n\n df = pandas.read_csv(filenames[0], sep=\"\\t\", index_col=0)\n df = df[[]] # no columns\n\n for filename in filenames:\n df[os.path.basename(filename)] = pandas.read_csv(\n filename, sep=\"\\t\", index_col=0)[\"TPM\"]\n\n assert len(df.columns) == len(filenames)\n\n groups = {\n \"sample_type:MELANOMA_MET\": df.columns.tolist(),\n }\n return [make_expression_groups(\"GSE113126\", df, groups)]\n\n\ndef handle_expression_expression_atlas_22460905(filename):\n df = pandas.read_csv(filename, sep=\"\\t\", skiprows=4, index_col=0)\n del df[\"Gene Name\"]\n df.columns = df.columns.str.lower()\n df = df.fillna(0.0)\n\n def matches(*strings):\n return [c for c in df.columns if all(s in c for s in strings)]\n\n groups = {\n \"sample_type:B-LCL\": (\n matches(\"b-cell\", \"lymphoblast\") + matches(\"b acute lymphoblastic\")),\n \"sample_type:B-CELL\": matches(\"b-cell\"),\n \"sample_type:B721-LIKE\": matches(\"b-cell\"),\n \"sample_type:MELANOMA_CELL_LINE\": matches(\"melanoma\"),\n \"sample_type:MELANOMA\": matches(\"melanoma\"),\n \"sample_type:KG1-LIKE\": matches(\"myeloid leukemia\"),\n\n # Using a fibrosarcoma cell line for our fibroblast sample.\n \"sample_type:FIBROBLAST\": ['fibrosarcoma, ht-1080'],\n\n # For GBM tissue we are just using a mixture of cell lines.\n \"sample_type:GLIOBLASTOMA_TISSUE\": matches(\"glioblastoma\"),\n\n \"cell_line:A375\": ['amelanotic melanoma, a-375'],\n \"cell_line:THP-1\": [\"childhood acute monocytic leukemia, thp-1\"],\n \"cell_line:HL-60\": [\"adult acute myeloid leukemia, hl-60\"],\n \"cell_line:U-87\": ['glioblastoma, u-87 mg'],\n \"cell_line:LNT-229\": ['glioblastoma, ln-229'],\n \"cell_line:T98G\": ['glioblastoma, t98g'],\n \"cell_line:SK-MEL-5\": ['cutaneous melanoma, sk-mel-5'],\n 'cell_line:MEWO': ['melanoma, mewo'],\n \"cell_line:HCC1937\": ['breast ductal adenocarcinoma, hcc1937'],\n \"cell_line:HCT116\": ['colon carcinoma, hct 116'],\n \"cell_line:HCC1143\": ['breast ductal adenocarcinoma, hcc1143'],\n }\n return [make_expression_groups(\"expression_atlas_22460905\", df, groups)]\n\n\ndef handle_expression_human_protein_atlas(*filenames):\n (cell_line_filename,) = [f for f in filenames if \"celline\" in f]\n (blood_filename,) = [f for f in filenames if \"blood\" in f]\n (gtex_filename,) = [f for f in filenames if \"gtex\" in f]\n\n cell_line_df = pandas.read_csv(cell_line_filename, sep=\"\\t\")\n blood_df = pandas.read_csv(blood_filename, sep=\"\\t\", index_col=0)\n gtex_df = pandas.read_csv(gtex_filename, sep=\"\\t\")\n\n cell_line_df = cell_line_df.pivot(\n index=\"Gene\", columns=\"Cell line\", values=\"TPM\")\n\n gtex_df = gtex_df.pivot(\n index=\"Gene\", columns=\"Tissue\", values=\"TPM\")\n\n return [\n make_expression_groups(\n \"human_protein_atlas:%s\" % os.path.basename(blood_filename),\n blood_df,\n groups={\n \"sample_type:PBMC\": [\n c for c in blood_df.columns if \"total PBMC\" in c\n ],\n\n # for samples labeled leukapheresis we also use PBMC\n \"sample_type:LEUKAPHERESIS\": [\n c for c in blood_df.columns if \"total PBMC\" in c\n ],\n\n # for samples labeled TIL we are also using PBMC\n \"sample_type:TIL\": [\n c for c in blood_df.columns if \"total PBMC\" in c\n ],\n }),\n make_expression_groups(\n \"human_protein_atlas:%s\" % os.path.basename(cell_line_filename),\n cell_line_df,\n groups={\n \"cell_line:HELA\": ['HeLa'],\n \"cell_line:K562\": [\"K-562\"],\n \"cell_line:HEK293\": ['HEK 293'],\n \"cell_line:RPMI8226\": ['RPMI-8226'],\n \"cell_line:EXPI293\": ['HEK 293'], # EXPI293 derived from HEK293\n }),\n make_expression_groups(\n \"human_protein_atlas:%s\" % os.path.basename(gtex_filename),\n gtex_df,\n groups={\n \"sample_type:LUNG\": [\"lung\"],\n \"sample_type:SPLEEN\": [\"spleen\"],\n \"sample_type:OVARY\": [\"ovary\"],\n \"sample_type:KIDNEY\": [\"kidney\"],\n\n # This is bad! I just can't find anything better currently.\n # We should find some meningioma RNA-seq and switch to that.\n \"sample_type:MENINGIOMA\": [\n \"amygdala\", \"basal ganglia\", \"cerebellum\", \"cerebral cortex\",\n \"midbrain\", \"spinal cord\",\n ],\n }),\n ]\n\n\ndef make_expression_mixtures(expression_df):\n global CELL_LINE_MIXTURES\n groups = {}\n for mix in CELL_LINE_MIXTURES:\n components = []\n for item in mix.replace(\"mix:\", \"\").upper().split(\",\"):\n if \"cell_line:%s\" % item in expression_df.columns:\n components.append(\"cell_line:%s\" % item)\n else:\n print(\"No cell line, falling back on similar: \", item)\n components.append(\"sample_type:%s-LIKE\" % item)\n groups[\"sample_type:\" + mix.upper()] = components\n missing = set()\n for some in groups.values():\n for item in some:\n if item not in expression_df.columns:\n missing.add(item)\n if missing:\n raise ValueError(\n \"Missing [%d]: %s. Available: %s\" % (\n len(missing), missing, expression_df.columns.tolist()))\n return make_expression_groups(\"mixtures\", expression_df, groups)\n\n\n# Add all functions with names like handle_pmid_XXXX to PMID_HANDLERS dict.\nfor (key, value) in list(locals().items()):\n if key.startswith(\"handle_pmid_\"):\n PMID_HANDLERS[key.replace(\"handle_pmid_\", \"\")] = value\n elif key.startswith(\"handle_expression_\"):\n EXPRESSION_HANDLERS[key.replace(\"handle_expression_\", \"\")] = value\n\n\ndef run():\n args = parser.parse_args(sys.argv[1:])\n\n expression_dfs = []\n for (i, item_tpl) in enumerate(args.expression_item):\n (label, filenames) = (item_tpl[0], item_tpl[1:])\n label = label.replace(\"-\", \"_\")\n print(\n \"Processing expression item %d of %d\" % (i + 1, len(args.expression_item)),\n label,\n *[os.path.abspath(f) for f in filenames])\n\n expression_dfs_for_item = []\n handler = None\n if label in EXPRESSION_HANDLERS:\n handler = EXPRESSION_HANDLERS[label]\n expression_dfs_for_item = handler(*filenames)\n elif args.debug:\n debug(*filenames)\n else:\n raise NotImplementedError(label)\n\n if expression_dfs_for_item:\n print(\n \"Processed expression data\",\n label,\n \"result dataframes\",\n len(expression_dfs_for_item))\n print(*[e.columns for e in expression_dfs_for_item])\n expression_dfs.extend(expression_dfs_for_item)\n\n expression_df = expression_dfs[0]\n for other in expression_dfs[1:]:\n expression_df = pandas.merge(\n expression_df, other, how='outer', left_index=True, right_index=True)\n\n print(\"Genes in each expression dataframe: \",\n *[len(e) for e in expression_dfs])\n print(\"Genes in merged expression dataframe\", len(expression_df))\n\n if CELL_LINE_MIXTURES:\n print(\"Generating cell line mixtures.\")\n expression_mixture_df = make_expression_mixtures(expression_df)\n expression_df = pandas.merge(\n expression_df,\n expression_mixture_df,\n how='outer',\n left_index=True,\n right_index=True)\n\n ms_dfs = []\n for (i, item_tpl) in enumerate(args.ms_item):\n (pmid, filenames) = (item_tpl[0], item_tpl[1:])\n print(\n \"Processing MS item %d of %d\" % (i + 1, len(args.ms_item)),\n pmid,\n *[os.path.abspath(f) for f in filenames])\n\n ms_df = None\n handler = None\n if pmid in PMID_HANDLERS:\n handler = PMID_HANDLERS[pmid]\n ms_df = handler(*filenames)\n elif args.debug:\n debug(*filenames)\n else:\n raise NotImplementedError(pmid)\n\n if ms_df is not None:\n ms_df[\"pmid\"] = pmid\n if \"original_pmid\" not in ms_df.columns:\n ms_df[\"original_pmid\"] = pmid\n if \"expression_dataset\" not in ms_df.columns:\n ms_df[\"expression_dataset\"] = \"\"\n ms_df = ms_df.applymap(str).applymap(str.upper)\n ms_df[\"sample_id\"] = ms_df.sample_id.str.replace(\" \", \"\")\n print(\"*** PMID %s: %d peptides ***\" % (pmid, len(ms_df)))\n if handler is not None:\n print(handler.__doc__)\n print(\"Counts by sample id:\")\n print(ms_df.groupby(\"sample_id\").peptide.nunique())\n print(\"\")\n print(\"Counts by sample type:\")\n print(ms_df.groupby(\"sample_type\").peptide.nunique())\n print(\"****************************\")\n\n for value in ms_df.expression_dataset.unique():\n if value and value not in expression_df.columns:\n raise ValueError(\"No such expression dataset\", value)\n\n ms_dfs.append(ms_df)\n else:\n print(\"Skipping MS item\", pmid)\n\n ms_df = pandas.concat(ms_dfs, ignore_index=True, sort=False)\n ms_df[\"cell_line\"] = ms_df[\"cell_line\"].fillna(\"\")\n ms_df[\"hla\"] = ms_df[\"hla\"].str.strip().str.replace(r'\\s+', ' ').map(\n lambda hla: \" \".join(\n [\n normalize_allele_name(a, raise_on_error=True)\n for a in hla.split()\n ]))\n\n for _, row in ms_df.drop_duplicates(\"hla\").iterrows():\n alleles = row.hla.split()\n for allele in alleles:\n # Catch pairs like HLA-DQA*01:01-DQB1*01:01.\n # We want only single alleles. They get paired up in analysis code.\n if \"-\" in allele.replace(\"HLA-\", \"\"):\n raise ValueError(\n \"Allele pair present: %s. In: %s\\n%s\" % (\n allele, row.hla, row))\n\n\n sample_table = ms_df[\n [\n \"sample_id\",\n \"pmid\",\n \"format\",\n \"expression_dataset\",\n \"cell_line\",\n \"sample_type\",\n ]\n ].drop_duplicates().set_index(\"sample_id\")\n\n sample_id_to_expression_dataset = sample_table.expression_dataset.to_dict()\n for (sample_id, value) in sorted(sample_id_to_expression_dataset.items()):\n if value:\n print(\"Expression dataset for sample\", sample_id, \"already assigned\")\n continue\n cell_line_col = \"cell_line:\" + sample_table.loc[sample_id, \"cell_line\"]\n sample_type_col = \"sample_type:\" + (\n sample_table.loc[sample_id, \"sample_type\"])\n\n expression_dataset = None\n for col in [cell_line_col, sample_type_col]:\n if col in expression_df.columns:\n expression_dataset = col\n break\n\n if not expression_dataset:\n print(\"*\" * 20)\n print(\"No expression dataset for sample \", sample_id)\n print(\"Sample info:\")\n print(sample_table.loc[sample_id])\n print(\"*\" * 20)\n\n sample_id_to_expression_dataset[sample_id] = expression_dataset\n print(\n \"Sample\", sample_id, \"assigned exp. dataset\", expression_dataset)\n\n print(\"Expression dataset usage:\")\n print(pandas.Series(sample_id_to_expression_dataset).value_counts())\n\n print(\"PMIDs by format:\")\n print(sample_table.groupby(\"format\").pmid.unique())\n\n missing = [\n key for (key, value) in\n sample_id_to_expression_dataset.items()\n if value is None\n ]\n if missing:\n print(\"Missing expression data for samples\", *missing)\n print(\n \"Missing cell lines: \",\n *sample_table.loc[missing, \"cell_line\"].dropna().drop_duplicates().tolist())\n print(\"Missing sample types: \", *sample_table.loc[\n missing, \"sample_type\"].dropna().drop_duplicates().tolist())\n if args.debug:\n import ipdb; ipdb.set_trace()\n else:\n raise ValueError(\"Missing expression data for samples: \", missing)\n\n ms_df[\"expression_dataset\"] = ms_df.sample_id.map(\n sample_id_to_expression_dataset)\n\n cols = [\n \"pmid\",\n \"sample_id\",\n \"peptide\",\n \"format\",\n \"mhc_class\",\n \"hla\",\n \"expression_dataset\",\n ]\n cols += [c for c in sorted(ms_df.columns) if c not in cols]\n ms_df = ms_df[cols]\n\n null_df = ms_df.loc[ms_df.isnull().any(1)]\n if len(null_df) > 0:\n print(\"Nulls:\")\n print(null_df)\n else:\n print(\"No nulls.\")\n\n # Each sample should be coming from only one experiment.\n assert ms_df.groupby(\"sample_id\").pmid.nunique().max() == 1, (\n ms_df.groupby(\"sample_id\").pmid.nunique().sort_values())\n\n expression_df.to_csv(args.expression_out, index=True)\n print(\"Wrote: %s\" % os.path.abspath(args.expression_out))\n\n ms_df.to_csv(args.ms_out, index=False)\n print(\"Wrote: %s\" % os.path.abspath(args.ms_out))\n\n if args.expression_metadata_out is not None:\n expression_metadata_df = pandas.DataFrame(\n EXPRESSION_GROUPS_ROWS,\n columns=[\"expression_dataset\", \"label\", \"samples\"])\n expression_metadata_df[\"samples\"] = expression_metadata_df[\n \"samples\"\n ].map(json.dumps)\n expression_metadata_df.to_csv(args.expression_metadata_out, index=False)\n print(\"Wrote: %s\" % os.path.abspath(args.expression_metadata_out))\n\n\nif __name__ == '__main__':\n run()\n" }, { "alpha_fraction": 0.713936448097229, "alphanum_fraction": 0.7212713956832886, "avg_line_length": 26.886363983154297, "blob_id": "1be389779e4e9af1a4b8a0fa84ac1dde5045b5f6", "content_id": "74c8ae9eb1007d457a127e8acbb018c88aebeafc", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1227, "license_type": "permissive", "max_line_length": 106, "num_lines": 44, "path": "/downloads-generation/data_pdb/GENERATE.sh", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n# Class II structures from PDB\n#\n# Requires: curl\n#\nset -e\nset -x\n\nDOWNLOAD_NAME=data_pdb\nSCRATCH_DIR=${TMPDIR-/tmp}/mhc2flurry-downloads-generation\nSCRIPT_ABSOLUTE_PATH=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/$(basename \"${BASH_SOURCE[0]}\")\"\nSCRIPT_DIR=$(dirname \"$SCRIPT_ABSOLUTE_PATH\")\nexport PYTHONUNBUFFERED=1\n\nmkdir -p \"$SCRATCH_DIR\"\nrm -rf \"$SCRATCH_DIR/$DOWNLOAD_NAME\"\nmkdir \"$SCRATCH_DIR/$DOWNLOAD_NAME\"\n\n# Send stdout and stderr to a logfile included with the archive.\nexec > >(tee -ia \"$SCRATCH_DIR/$DOWNLOAD_NAME/LOG.txt\")\nexec 2> >(tee -ia \"$SCRATCH_DIR/$DOWNLOAD_NAME/LOG.txt\" >&2)\n\n# Log some environment info\ndate\npip freeze\ngit status\n\ncd $SCRATCH_DIR/$DOWNLOAD_NAME\ncp $SCRIPT_DIR/batch_download.sh .\ncp $SCRIPT_DIR/*.py .\ncp $SCRIPT_ABSOLUTE_PATH .\n\nmkdir structures\npython make_pdb_query.py > pdb_query.json\ncurl https://search.rcsb.org/rcsbsearch/v1/query --data-urlencode \"json@pdb_query.json\" -G -o results.json\npython parse_results.py results.json identifiers.txt\nbash batch_download.sh -f identifiers.txt -o structures -c\n\ncp $SCRIPT_ABSOLUTE_PATH .\nbzip2 LOG.txt\nRESULT=\"$SCRATCH_DIR/${DOWNLOAD_NAME}.$(date +%Y%m%d).tar.bz2\"\ntar -cjf \"$RESULT\" *\necho \"Created archive: $RESULT\"\n" }, { "alpha_fraction": 0.6904198527336121, "alphanum_fraction": 0.7684801816940308, "avg_line_length": 52.68254089355469, "blob_id": "c762788e12cea0596a56971b514bb0b0992b4b46", "content_id": "d942318ff6a693e6e080a4a8e0f17d7564f7137b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3382, "license_type": "permissive", "max_line_length": 206, "num_lines": 63, "path": "/downloads-generation/data_proteomes/GENERATE.sh", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n# Download viral, human, and mouse proteomes from Uniprot\n#\nset -e\nset -x\n\nDOWNLOAD_NAME=data_proteomes\nSCRATCH_DIR=${TMPDIR-/tmp}/mhc2flurry-downloads-generation\nSCRIPT_ABSOLUTE_PATH=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/$(basename \"${BASH_SOURCE[0]}\")\"\nSCRIPT_DIR=$(dirname \"$SCRIPT_ABSOLUTE_PATH\")\n\nmkdir -p \"$SCRATCH_DIR\"\nrm -rf \"$SCRATCH_DIR/$DOWNLOAD_NAME\"\nmkdir \"$SCRATCH_DIR/$DOWNLOAD_NAME\"\n\n# Send stdout and stderr to a logfile included with the archive.\nexec > >(tee -ia \"$SCRATCH_DIR/$DOWNLOAD_NAME/LOG.txt\")\nexec 2> >(tee -ia \"$SCRATCH_DIR/$DOWNLOAD_NAME/LOG.txt\" >&2)\n\n# Log some environment info\ndate\n\ncd $SCRATCH_DIR/$DOWNLOAD_NAME\n\ncp $SCRIPT_DIR/index_fasta.py .\n\n\n###### Human protein sequences\n# We are downloading both the canonical (one protein per gene) sequences as well\n# as the alternate isoforms.\n# We also download ID mapping to Ensembl and other databases.\nwget -q 'ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/reference_proteomes/Eukaryota/UP000005640/UP000005640_9606.fasta.gz' -O human.uniprot.one_per_gene.fasta.gz\nwget -q 'ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/reference_proteomes/Eukaryota/UP000005640/UP000005640_9606_additional.fasta.gz' -O human.uniprot.isoforms.fasta.gz\nwget -q 'ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/reference_proteomes/Eukaryota/UP000005640/UP000005640_9606.idmapping.gz' -O human.uniprot_id_mapping.dat.gz\nwget -q 'ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/reference_proteomes/Eukaryota/UP000005640/UP000005640_9606.gene2acc.gz' -O human.uniprot_gene2acc.gz\n\n###### Mouse protein sequences\n# Also using the \"one proein sequence per gene\" version.\nwget -q 'ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/reference_proteomes/Eukaryota/UP000000589/UP000000589_10090.fasta.gz' -O mouse.uniprot.one_per_gene.fasta.gz\nwget -q 'ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/reference_proteomes/Eukaryota/UP000000589/UP000000589_10090_additional.fasta.gz' -O mouse.uniprot.isoforms.fasta.gz\nwget -q 'ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/reference_proteomes/Eukaryota/UP000000589/UP000000589_10090.idmapping.gz' -O mouse.uniprot_id_mapping.dat.gz\nwget -q 'ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/reference_proteomes/Eukaryota/UP000000589/UP000000589_10090.gene2acc.gz' -O mouse.uniprot_gene2acc.gz\n\n###### Viral protein sequences\n# UniprotKB search:\n# proteome:(excluded:no taxonomy:\"Viruses [10239]\") host:\"Homo sapiens (Human) [9606]\"\n# link to human readable:\n# https://www.uniprot.org/uniprot/?query=proteome%3A%28excluded%3Ano+taxonomy%3A%22Viruses+%5B10239%5D%22%29+AND+host%3A%22Homo+sapiens+%28Human%29+%5B9606%5D%22&sort=score\nwget -q 'https://www.uniprot.org/uniprot/?query=proteome:(excluded:no%20taxonomy:%22Viruses%20[10239]%22)%20AND%20host:%22Homo%20sapiens%20(Human)%20[9606]%22&format=fasta&sort=score' -O viral.uniprot.fasta\ngzip viral.uniprot.fasta\n\n###### Index all sequences\nfor i in $(ls *.fasta.gz)\ndo\n time python index_fasta.py \"$(pwd)/$i\" \"$(pwd)/$i.fm\"\ndone\n\ncp $SCRIPT_ABSOLUTE_PATH .\nbzip2 LOG.txt\nRESULT=\"$SCRATCH_DIR/${DOWNLOAD_NAME}.$(date +%Y%m%d).tar.bz2\"\ntar -cjf \"$RESULT\" *\necho \"Created archive: $RESULT\"\n" }, { "alpha_fraction": 0.763052225112915, "alphanum_fraction": 0.7710843086242676, "avg_line_length": 23.899999618530273, "blob_id": "7c04a64c75405517e3c3e58afee86241b886e7f8", "content_id": "303381ae27fbb511d39a1ae67011e754049c41ad", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 249, "license_type": "permissive", "max_line_length": 86, "num_lines": 10, "path": "/downloads-generation/data_curated/README.md", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "# Combined training data\n\nThis download contains the data used to train the production class2 MHC2flurry models.\n\nTo generate this download run:\n\n```\npip install -r requirements.txt # for the first time you generate this download\n./GENERATE.sh\n```\n" }, { "alpha_fraction": 0.6502209305763245, "alphanum_fraction": 0.6546391844749451, "avg_line_length": 22.824562072753906, "blob_id": "16c80dfd0e3f146bed262057d4e0975a64764f5c", "content_id": "e9f4f94671b2b75f9e8548ee5b23f260258c4177", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1358, "license_type": "permissive", "max_line_length": 77, "num_lines": 57, "path": "/downloads-generation/data_curated/curate_t_cell_epitopes.py", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "\"\"\"\nCurate IEDB T cell epitopes. Currently this doesn't do much except rename the\npeptide column from \"Description\" to \"peptide\".\n\"\"\"\nimport sys\nimport argparse\n\nimport pandas\n\nfrom mhc2flurry.amino_acid import COMMON_AMINO_ACIDS\n\nparser = argparse.ArgumentParser(usage=__doc__)\n\nparser.add_argument(\n \"--data-iedb\",\n metavar=\"tcell_full_v3.csv\",\n help=\"Path to IEDB-style T cell epitope data\")\n\nparser.add_argument(\n \"--max-epitopes\",\n metavar=\"N\",\n type=int,\n help=\"Process first N epitopes (for debugging)\")\n\nparser.add_argument(\n \"--out-csv\",\n required=True,\n help=\"Result file\")\n\n\ndef run():\n args = parser.parse_args(sys.argv[1:])\n\n epitopes_df = pandas.read_csv(\n args.data_iedb, skiprows=1, nrows=args.max_epitopes)\n print(\"Read epitopes\", *epitopes_df.shape)\n print(epitopes_df)\n\n epitopes_df.insert(0, \"peptide\", epitopes_df.Description)\n aa_regex = \"^[%s]+$\" % \"\".join(sorted(COMMON_AMINO_ACIDS))\n\n epitopes_df = epitopes_df.loc[\n epitopes_df.peptide.str.match(aa_regex) &\n (epitopes_df.peptide.str.len() >= 5)\n ]\n\n print(\"Epitopes with valid peptides\", len(epitopes_df))\n\n print(\"Generated result\", *epitopes_df.shape)\n print(epitopes_df)\n\n epitopes_df.to_csv(args.out_csv, index=False)\n print(\"Wrote\", args.out_csv)\n\n\nif __name__ == '__main__':\n run()\n" }, { "alpha_fraction": 0.8163822293281555, "alphanum_fraction": 0.8296928405761719, "avg_line_length": 31.932584762573242, "blob_id": "bc0c1e9c4fb25341dbc758a2a64d844ca15874db", "content_id": "30f58c391509423a4bee8d65a9cde3b8ff49837e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2930, "license_type": "permissive", "max_line_length": 80, "num_lines": 89, "path": "/downloads-generation/data_pdb/make_pdb_query.py", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "# Just print a JSON PDB query to stdout\n# Doing this in a python script so we have comments.\n\nimport json\n\nsequences = []\n\n# DRA1*01:01\nsequences.append(\n \"MAISGVPVLGFFIIAVLMSAQESWAIKEEHVIIQAEFYLNPDQSGEFMFDFDGDEIFHVDMAKKETVWRLEEFGRF\"\n \"ASFEAQGALANIAVDKANLEIMTKRSNYTPITNVPPEVTVLTNSPVELREPNVLICFIDKFTPPVVNVTWLRNGKP\"\n \"VTTGVSETVFLPREDHLFRKFHYLPFLPSTEDVYDCRVEHWGLDEPLLKHWEFDAPSPLPETTENVVCALGLTVGL\"\n \"VGIIIGTIFIIKGVRKSNAAERRGPL\")\n\n# DRB1*01:01\nsequences.append(\n \"MVCLKLPGGSCMTALTVTLMVLSSPLALAGDTRPRFLWQLKFECHFFNGTERVRLLERCIYNQEESVRFDSDVGEY\"\n \"RAVTELGRPDAEYWNSQKDLLEQRRAAVDTYCRHNYGVGESFTVQRRVEPKVTVYPSKTQPLQHHNLLVCSVSGFY\"\n \"PGSIEVRWFRNGQEEKAGVVSTGLIQNGDWTFQTLVMLETVPRSGEVYTCQVEHPSVTSPLTVEWRARSESAQSKM\"\n \"LSGVGGFVLGLLFLGAGLFIYFRNQKGHSGLQPTGFLS\")\n\n# DRB3*01:01\nsequences.append(\n \"MVCLKLPGGSSLAALTVTLMVLSSRLAFAGDTRPRFLELRKSECHFFNGTERVRYLDRYFHNQEEFLRFDSDVGEY\"\n \"RAVTELGRPVAESWNSQKDLLEQKRGRVDNYCRHNYGVGESFTVQRRVHPQVTVYPAKTQPLQHHNLLVCSVSGFY\"\n \"PGSIEVRWFRNGQEEKAGVVSTGLIQNGDWTFQTLVMLETVPRSGEVYTCQVEHPSVTSALTVEWRARSESAQSKM\"\n \"LSGVGGFVLGLLFLGAGLFIYFRNQKGHSGLQPTGFLS\")\n\n# DRB4*01:01\nsequences.append(\n \"MVCLKLPGGSCMAALTVTLTVLSSPLALAGDTQPRFLEQAKCECHFLNGTERVWNLIRYI\"\n \"YNQEEYARYNSDLGEYQAVTELGRPDAEYWNSQKDLLERRRAEVDTYCRYNYGVVESFTV\"\n \"QRRVQPKVTVYPSKTQPLQHHNLLVCSVNGFYPGSIEVRWFRNSQEEKAGVVSTGLIQNG\"\n \"DWTFQTLVMLETVPRSGEVYTCQVEHPSMMSPLTVQWSARSESAQSKMLSGVGGFVLGLL\"\n \"FLGTGLFIYFRNQKGHSGLQPTGLLS\")\n\n# DRB5*01:01\nsequences.append(\n \"MVCLKLPGGSYMAKLTVTLMVLSSPLALAGDTRPRFLQQDKYECHFFNGTERVRFLHRDIYNQEEDLRFDSDVGEY\"\n \"RAVTELGRPDAEYWNSQKDFLEDRRAAVDTYCRHNYGVGESFTVQRRVEPKVTVYPARTQTLQHHNLLVCSVNGFY\"\n \"PGSIEVRWFRNSQEEKAGVVSTGLIQNGDWTFQTLVMLETVPRSGEVYTCQVEHPSVTSPLTVEWRAQSESAQSKM\"\n \"LSGVGGFVLGLLFLGAGLFIYFKNQKGHSGLHPTGLVS\")\n\n# HLA-DQB1*02:01\nsequences.append(\n \"MSWKKALRIPGGLRAATVTLMLSMLSTPVAEGRDSPEDFVYQFKGMCYFTNGTERVRLVS\"\n \"RSIYNREEIVRFDSDVGEFRAVTLLGLPAAEYWNSQKDILERKRAAVDRVCRHNYQLELR\"\n \"TTLQRRVEPTVTISPSRTEALNHHNLLVCSVTDFYPAQIKVRWFRNDQEETAGVVSTPLI\"\n \"RNGDWTFQILVMLEMTPQRGDVYTCHVEHPSLQSPITVEWRAQSESAQSKMLSGIGGFVL\"\n \"GLIFLGLGLIIHHRSQKGLLH\")\n\n# HLA-DPB1*01:01\nsequences.append(\n \"MMVLQVSAAPRTVALTALLMVLLTSVVQGRATPENYVYQGRQECYAFNGTQRFLERYIYN\"\n \"REEYARFDSDVGEFRAVTELGRPAAEYWNSQKDILEEKRAVPDRVCRHNYELDEAVTLQR\"\n \"RVQPKVNVSPSKKGPLQHHNLLVCHVTDFYPGSIQVRWFLNGQEETAGVVSTNLIRNGDW\"\n \"TFQILVMLEMTPQQGDVYICQVEHTSLDSPVTVEWKAQSDSAQSKTLTGAGGFVLGLIIC\"\n \"GVGIFMHRRSKKVQRGSA\")\n\n# Should be distinct\nassert len(sequences) == len(set(sequences))\n\n\ndef node_from_sequence(sequence):\n return {\n \"type\": \"terminal\",\n \"service\": \"sequence\",\n \"parameters\": {\n \"evalue_cutoff\": 10,\n \"identity_cutoff\": 0.5,\n \"target\": \"pdb_protein_sequence\",\n \"value\": sequence,\n }\n }\n\n\nquery = {\n \"query\": {\n \"type\": \"group\",\n \"logical_operator\": \"or\",\n \"nodes\": [node_from_sequence(sequence) for sequence in sequences],\n },\n \"request_options\": {\n \"return_all_hits\": True\n },\n \"return_type\": \"entry\"\n}\n\nprint(json.dumps(query))" }, { "alpha_fraction": 0.6236686110496521, "alphanum_fraction": 0.6284023523330688, "avg_line_length": 17.369565963745117, "blob_id": "7bfd76cf79fa22b9b20536937ed36f28a61b3670", "content_id": "4542914cee66517d0516038ca04e2e7f9c5f6cc2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 845, "license_type": "permissive", "max_line_length": 57, "num_lines": 46, "path": "/downloads-generation/data_proteomes/index_fasta.py", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "\"\"\"\nWrite a shellinford index for a fasta.\n\"\"\"\n\nimport argparse\nimport time\nimport sys\n\nimport shellinford\n\nfrom mhc2flurry.fasta import read_fasta_to_dataframe\n\nparser = argparse.ArgumentParser(usage=__doc__)\n\nparser.add_argument(\n \"input\",\n metavar=\"FASTA\",\n help=\"Input file\")\nparser.add_argument(\n \"output\",\n metavar=\"FM\",\n help=\"Output file\")\n\n\ndef run():\n args = parser.parse_args(sys.argv[1:])\n\n df = read_fasta_to_dataframe(args.input)\n print(\"Read\")\n print(df)\n\n print(\"Building FM index\")\n start = time.time()\n fm = shellinford.FMIndex()\n fm.build(df.sequence.tolist())\n print(\"Built index of %d sequences in %0.3f sec.\" % (\n len(df), time.time() - start))\n\n print(\"Writing index\")\n fm.write(args.output)\n print(\"Wrote\", args.output)\n\n\n\nif __name__ == '__main__':\n run()\n" }, { "alpha_fraction": 0.6916167736053467, "alphanum_fraction": 0.696107804775238, "avg_line_length": 25.719999313354492, "blob_id": "3aa73352e7bcd3e4d1f592af2f09375d73529ab3", "content_id": "d2b924166b4175b73d788715009f3e81fe02f32a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 668, "license_type": "permissive", "max_line_length": 73, "num_lines": 25, "path": "/downloads-generation/data_pdb/parse_results.py", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "# From a PDB results json, print out a comma separated list of PDB IDs\n\nimport argparse\nimport sys\nimport json\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"results\", metavar=\"JSON\")\nparser.add_argument(\"out\", metavar=\"FILE\")\nargs = parser.parse_args(sys.argv[1:])\n\nparsed = json.load(open(args.results))\nprint(\"Loaded %d results\" % len(parsed['result_set']))\n\nprint(\"First result\")\nprint(parsed['result_set'][0])\n\nprint(\"Last result\")\nprint(parsed['result_set'][-1])\n\nwith open(args.out, \"w\") as fd:\n identifiers = [entry['identifier'] for entry in parsed['result_set']]\n fd.write(\",\".join(identifiers))\n fd.write(\"\\n\")\nprint(\"Wrote: \", args.out)\n" }, { "alpha_fraction": 0.6001904010772705, "alphanum_fraction": 0.6073298454284668, "avg_line_length": 20.22222137451172, "blob_id": "d4882be8b323593f0d8abad6c58362fb5ac7b93e", "content_id": "fdbe729c8266dc3740eeff8bf3d38eaa575dac82", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2101, "license_type": "permissive", "max_line_length": 103, "num_lines": 99, "path": "/downloads-generation/data_pdb/batch_download.sh", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Script to download files from RCSB http file download services.\n# Use the -h switch to get help on usage.\n\nif ! command -v curl &> /dev/null\nthen\n echo \"'curl' could not be found. You need to install 'curl' for this script to work.\"\n exit 1\nfi\n\nPROGNAME=$0\nBASE_URL=\"https://files.rcsb.org/download\"\n\nusage() {\n cat << EOF >&2\nUsage: $PROGNAME -f <file> [-o <dir>] [-c] [-p]\n\n -f <file>: the input file containing a comma-separated list of PDB ids\n -o <dir>: the output dir, default: current dir\n -c : download a cif.gz file for each PDB id\n -p : download a pdb.gz file for each PDB id\n -x : download a xml.gz file for each PDB id\n -s : download a sf.cif.gz file for each PDB id (diffraction only)\n -m : download a mr.gz file for each PDB id (NMR only)\n -r : download a mr.str.gz for each PDB id (NMR only)\nEOF\n exit 1\n}\n\ndownload() {\n url=\"$BASE_URL/$1\"\n out=$2/$1\n echo \"Downloading $url to $out\"\n curl -s -f $url -o $out || echo \"Failed to download $url\"\n}\n\nlistfile=\"\"\noutdir=\".\"\ncif=false\npdb=false\nxml=false\nsf=false\nmr=false\nmrstr=false\nwhile getopts f:o:cpxsmr o\ndo\n case $o in\n (f) listfile=$OPTARG;;\n (o) outdir=$OPTARG;;\n (c) cif=true;;\n (p) pdb=true;;\n (x) xml=true;;\n (s) sf=true;;\n (m) mr=true;;\n (r) mrstr=true;;\n (*) usage\n esac\ndone\nshift \"$((OPTIND - 1))\"\n\nif [ \"$listfile\" == \"\" ]\nthen\n echo \"Parameter -f must be provided\"\n exit 1\nfi\ncontents=$(cat $listfile)\n\n# see https://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash#tab-top\nIFS=',' read -ra tokens <<< \"$contents\"\n\nfor token in \"${tokens[@]}\"\ndo\n if [ \"$cif\" == true ]\n then\n download ${token}.cif.gz $outdir\n fi\n if [ \"$pdb\" == true ]\n then\n download ${token}.pdb.gz $outdir\n fi\n if [ \"$xml\" == true ]\n then\n download ${token}.xml.gz $outdir\n fi\n if [ \"$sf\" == true ]\n then\n download ${token}-sf.cif.gz $outdir\n fi\n if [ \"$mr\" == true ]\n then\n download ${token}.mr.gz $outdir\n fi\n if [ \"$mrstr\" == true ]\n then\n download ${token}_mr.str.gz $outdir\n fi\n\ndone\n" }, { "alpha_fraction": 0.6521739363670349, "alphanum_fraction": 0.782608687877655, "avg_line_length": 11, "blob_id": "f3305ce7361e06c91af59e769b8a283d7b77feef", "content_id": "71e59398aac66f1ba200bde4bcc488b15462779e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 23, "license_type": "permissive", "max_line_length": 11, "num_lines": 2, "path": "/downloads-generation/data_curated/requirements.txt", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "xlrd>=1.1.0\nshellinford" }, { "alpha_fraction": 0.6683968901634216, "alphanum_fraction": 0.7037332653999329, "avg_line_length": 34.77857208251953, "blob_id": "88deff690660b4933a09277eb0091c7c8a6f206a", "content_id": "8b344ab7446acca1618429c950c203a4a0cbf200", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 5009, "license_type": "permissive", "max_line_length": 106, "num_lines": 140, "path": "/downloads-generation/allele_sequences/GENERATE.sh", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n# Class II allele sequences\n#\n# Requires: clustalo, wget\n#\nset -e\nset -x\n\nDOWNLOAD_NAME=allele_sequences\nSCRATCH_DIR=${TMPDIR-/tmp}/mhc2flurry-downloads-generation\nSCRIPT_ABSOLUTE_PATH=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/$(basename \"${BASH_SOURCE[0]}\")\"\nSCRIPT_DIR=$(dirname \"$SCRIPT_ABSOLUTE_PATH\")\nexport PYTHONUNBUFFERED=1\n\nmkdir -p \"$SCRATCH_DIR\"\nrm -rf \"$SCRATCH_DIR/$DOWNLOAD_NAME\"\nmkdir \"$SCRATCH_DIR/$DOWNLOAD_NAME\"\n\n# Send stdout and stderr to a logfile included with the archive.\nexec > >(tee -ia \"$SCRATCH_DIR/$DOWNLOAD_NAME/LOG.txt\")\nexec 2> >(tee -ia \"$SCRATCH_DIR/$DOWNLOAD_NAME/LOG.txt\" >&2)\n\n# Log some environment info\ndate\npip freeze\ngit status\nwhich clustalo\nclustalo --version\n\ncd $SCRATCH_DIR/$DOWNLOAD_NAME\ncp $SCRIPT_DIR/*.py .\ncp $SCRIPT_ABSOLUTE_PATH .\n\n######## Human\n# Human Alpha chain\nmkdir -p alpha\ncd alpha\nwget -q ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/fasta/DPA1_prot.fasta\nwget -q ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/fasta/DPA2_prot.fasta\nwget -q ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/fasta/DQA1_prot.fasta\nwget -q ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/fasta/DQA2_prot.fasta\nwget -q ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/fasta/DRA_prot.fasta\ncd ..\n\n# Human Beta chain\nmkdir -p beta\ncd beta\nwget -q ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/fasta/DPB1_prot.fasta\nwget -q ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/fasta/DPB2_prot.fasta\nwget -q ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/fasta/DQB1_prot.fasta\nwget -q ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/fasta/DRB_prot.fasta\ncd ..\n\n######## MOUSE\n#\n# See http://www.imgt.org/IMGTrepertoireMH/Proteins/tables/index.php?species=mouse&gene=MH2-AB\n#\n#\n# Mouse Alpha chain: TODO\n#\n# Mouse Beta chain: H-2-AB alleles\n# Commented out for now until we have A-2-AA sequences\n#mkdir -p beta\n#cd beta\n#wget -q https://www.uniprot.org/uniprot/P14483.fasta # MH2-AB*01\n#wget -q https://www.uniprot.org/uniprot/P01921.fasta # MH2-AB*03\n#wget -q https://www.uniprot.org/uniprot/Q31135.fasta # MH2-AB*06\n#wget -q https://www.uniprot.org/uniprot/O78197.fasta # MH2-AB*10\n#wget -q https://www.uniprot.org/uniprot/O62867.fasta # MH2-AB*12\n#wget -q https://www.uniprot.org/uniprot/P06342.fasta # MH2-AB*13\n#wget -q https://www.uniprot.org/uniprot/O78197.fasta # MH2-AB*10\n#wget -q https://www.uniprot.org/uniprot/O62867.fasta # MH2-AB*12\n#wget -q https://www.uniprot.org/uniprot/P06342.fasta # MH2-AB*13\n#wget -q https://www.uniprot.org/uniprot/P06343.fasta # MH2-AB*14\n#wget -q https://www.uniprot.org/uniprot/Q31184.fasta # MH2-AB*15\n#wget -q https://www.uniprot.org/uniprot/Q31131.fasta # MH2-AB*16\n#wget -q https://www.uniprot.org/uniprot/P06345.fasta # MH2-AB*17\n#wget -q https://www.uniprot.org/uniprot/P06346.fasta # MH2-AB*20\n#wget -q https://www.uniprot.org/uniprot/O19470.fasta # MH2-AB*22\n\npython filter_sequences.py alpha/*.fasta --kind alpha --out alpha.database.fasta\npython filter_sequences.py beta/*.fasta --kind beta --out beta.database.fasta\n\n# Generate PDB sequences\ntime python extract_pdb_sequences.py \\\n \"$(mhc2flurry-downloads path data_pdb)/structures\" \\\n \"$(pwd)/pdb_sequences.fasta\"\n\n# Search PDB sequences against downloaded IMDB\ncat alpha.database.fasta beta.database.fasta > alpha_and_beta.database.fasta\nMMSEQS_OUTPUT_FORMAT=\"query,target,qaln,taln,qseq,tseq,qcov,tcov,qstart,qend,qlen,tstart,tend,tlen,evalue\"\nmmseqs easy-search \\\n \"$(pwd)/pdb_sequences.fasta\" \\\n \"$(pwd)/alpha_and_beta.database.fasta\" \\\n \"$(pwd)/pdb_search.m8\" \\\n \"${TMPDIR-/tmp}\" \\\n --format-output \"$MMSEQS_OUTPUT_FORMAT\" \\\n -s 1.0\ntime python assign_pdb_sequences_to_alpha_or_beta.py \\\n \"$(pwd)/pdb_sequences.fasta\" \\\n \"$(pwd)/pdb_search.m8\" \\\n --mmseqs-output-format \"$MMSEQS_OUTPUT_FORMAT\" \\\n --out-alpha \"$(pwd)/alpha.pdb.fasta\" \\\n --out-beta \"$(pwd)/beta.pdb.fasta\"\n\ncat alpha.pdb.fasta alpha.database.fasta > alpha.combined.fasta\ncat beta.pdb.fasta beta.database.fasta > beta.combined.fasta\n\n# Run clustalo to generate multiple sequence alignments\ntime clustalo -i \"$(pwd)/alpha.combined.fasta\" -o \"$(pwd)/alpha.aligned.fasta\" \\\n --clustering-out cluster.alpha.aux\ntime clustalo -i \"$(pwd)/beta.combined.fasta\" -o \"$(pwd)/beta.aligned.fasta\" \\\n --clustering-out cluster.beta.aux\n\ntime python make_pseudosequences.py \\\n \"$(pwd)/alpha.aligned.fasta\" \\\n \"$(pwd)/beta.aligned.fasta\" \\\n \"$(mhc2flurry-downloads path data_pdb)/structures\" \\\n --criteria 0.2 6.0 0.3 \\\n --criteria 0.1 8.0 0.1 \\\n --criteria 0.05 10.0 0.05 \\\n --reference-allele HLA-DRA*01:01 HLA-DRB1*01:01 \\\n --reference-structure 3QXD \\\n --reference-structure 5KSU \\\n --out-csv \"$(pwd)/allele_sequences.csv\" \\\n --out-aux-dir \"$(pwd)/aux-info\" # Extra info\n\n# Cleanup\nrm pdb_search.m8\nfor i in $(ls *.fasta)\ndo\n gzip -f \"$i\"\ndone\n\ncp $SCRIPT_ABSOLUTE_PATH .\nbzip2 LOG.txt\nRESULT=\"$SCRATCH_DIR/${DOWNLOAD_NAME}.$(date +%Y%m%d).tar.bz2\"\ntar -cjf \"$RESULT\" *\necho \"Created archive: $RESULT\"\n" }, { "alpha_fraction": 0.551116943359375, "alphanum_fraction": 0.5537450909614563, "avg_line_length": 33.27927780151367, "blob_id": "92da2a79bb2ed82d54a2b42fbba6a08e98958c7c", "content_id": "dd416f470be2fa3e0c50d5405ef44bf84f440bbc", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15220, "license_type": "permissive", "max_line_length": 86, "num_lines": 444, "path": "/downloads-generation/allele_sequences/make_pseudosequences.py", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "\"\"\"\nSelect allele sequences for pan-class II models by analyzing distances between\neach MHC residue and the peptide across a set of structures from PDB.\n\"\"\"\nfrom __future__ import print_function\n\nimport sys\nimport argparse\nimport collections\nimport os\nimport operator\n\nimport numpy\nimport pandas\n\nimport tqdm\n\nimport atomium\n\n\nfrom mhc2flurry.fasta import read_fasta_to_dataframe\n\n\nparser = argparse.ArgumentParser(usage=__doc__)\n\nparser.add_argument(\n \"alpha_aligned_fasta\",\n metavar=\"FASTA\",\n help=\"Aligned sequences\")\n\nparser.add_argument(\n \"beta_aligned_fasta\",\n metavar=\"FASTA\",\n help=\"Aligned sequences\")\n\nparser.add_argument(\n \"pdb_dir\",\n metavar=\"DIR\",\n help=\"Directory containing PDB structures\")\n\nparser.add_argument(\n \"--reference-allele\",\n nargs=2,\n help=\"Alpha and beta alleles to use for position numbering.\")\n\nparser.add_argument(\n \"--reference-structure\",\n action=\"append\",\n default=[],\n help=\"Structures to write out with b-factors rewritten according to \"\n \"inclusion in pseudosequences(for visualization).\")\n\nparser.add_argument(\n \"--out-csv\",\n help=\"Result file for sequences\")\n\nparser.add_argument(\n \"--out-aux-dir\",\n help=\"Result DIR for extra information\")\n\nparser.add_argument(\n \"--cutoffs\",\n default=[2.0, 4.0, 6.0, 8.0, 10.0],\n nargs=\"+\",\n type=float,\n metavar=\"X\",\n help=\"Cutoff distances to evaluate. Default: %(default)s.\")\n\nparser.add_argument(\n \"--criteria\",\n nargs=3,\n type=float,\n action=\"append\",\n default=[],\n required=True,\n metavar=\"X\",\n help=\"Criteria for selecting a position. Triple of: min minor allele \"\n \"fraction, cutoff distance, fraction of structures with a contact at \"\n \"the given cutoff. May be specified any number of times.\")\n\nparser.add_argument(\n \"--peptide-chain-min-length\",\n default=5,\n metavar=\"N\",\n type=int,\n help=\"Default: %(default)s.\")\n\nparser.add_argument(\n \"--peptide-chain-max-length\",\n default=50,\n metavar=\"N\",\n type=int,\n help=\"Default: %(default)s.\")\n\nparser.add_argument(\n \"--subsample-pdb\",\n metavar=\"N\",\n type=int,\n help=\"Subsample to at most N PDB structures. For debugging.\")\n\n\ndef make_position_to_aligned_position_dict(aligned_sequence):\n result = {}\n position = 0\n for (i, char) in enumerate(aligned_sequence):\n if char != \"-\":\n result[position] = i\n position += 1\n return result\n\n\ndef make_aligned_position_to_position_dict(aligned_sequence):\n result = {}\n position = 0\n for (i, char) in enumerate(aligned_sequence):\n if char != \"-\":\n result[i] = position\n position += 1\n return result\n\n\ndef run():\n args = parser.parse_args(sys.argv[1:])\n print(args)\n\n alpha_aligned_df = read_fasta_to_dataframe(\n args.alpha_aligned_fasta,\n full_descriptions=True)\n alpha_aligned_df[\"kind\"] = \"alpha\"\n\n beta_aligned_df = read_fasta_to_dataframe(\n args.beta_aligned_fasta,\n full_descriptions=True)\n beta_aligned_df[\"kind\"] = \"beta\"\n\n aligned_df = pandas.concat(\n [alpha_aligned_df, beta_aligned_df], ignore_index=True)\n aligned_df[\"unaligned\"] = aligned_df.sequence.str.replace(\"-\", \"\")\n aligned_df = aligned_df.rename(columns={\n \"sequence\": \"aligned_sequence\",\n }).set_index(\"sequence_id\")\n\n non_pdb_aligned_df = aligned_df.loc[\n ~aligned_df.index.str.startswith(\"pdb\")\n ].copy()\n minor_allele_fraction_df = []\n for kind, sub_df in non_pdb_aligned_df.groupby(\"kind\"):\n print(\"Calculating minor allelic fractions: \", kind)\n (length,) = sub_df.aligned_sequence.str.len().unique()\n for pos in tqdm.tqdm(range(length)):\n s = sub_df.aligned_sequence.str.get(pos)\n mode = s.mode()[0]\n maf = (s != mode).mean()\n minor_allele_fraction_df.append((kind, pos, mode, maf))\n minor_allele_fraction_df = pandas.DataFrame(\n minor_allele_fraction_df,\n columns=[\n \"mhc_chain_kind\",\n \"mhc_residue_aligned\",\n \"major_allele\",\n \"minor_allele_fraction\",\n ])\n minor_allele_fraction_df = minor_allele_fraction_df.set_index(\n [\"mhc_chain_kind\", \"mhc_residue_aligned\"])\n print(minor_allele_fraction_df)\n\n pdb_aligned_df = aligned_df.loc[\n aligned_df.index.str.startswith(\"pdb\")\n ].copy()\n pdb_aligned_df[\"accession\"] = pdb_aligned_df.index.str.split(\".\").str.get(\n 1).str.split(\"_\").str.get(0)\n pdb_aligned_df[\"chain\"] = pdb_aligned_df.index.str.split(\"_\").str.get(-1)\n\n if args.subsample_pdb:\n keep_accessions = list(\n pandas.Series(\n pdb_aligned_df.accession.unique()).sample(\n n=args.subsample_pdb)) + args.reference_structure\n pdb_aligned_df = pdb_aligned_df.loc[\n pdb_aligned_df.accession.isin(keep_accessions)\n ].copy()\n\n info_by_accession = {}\n contacts_df = []\n for accession, sub_df in tqdm.tqdm(\n pdb_aligned_df.groupby(\"accession\"),\n total=pdb_aligned_df.accession.nunique()):\n\n sub_df = sub_df.set_index(\"chain\")\n alpha_chains = sub_df.loc[sub_df.kind == \"alpha\"].index.values\n beta_chains = sub_df.loc[sub_df.kind == \"beta\"].index.values\n\n mhc_chain_to_kind = {}\n for chain in alpha_chains:\n mhc_chain_to_kind[chain] = \"alpha\"\n for chain in beta_chains:\n mhc_chain_to_kind[chain] = \"beta\"\n\n if len(alpha_chains) != len(beta_chains):\n print(\n \"Skipping\", accession,\n \"because num chains for alpha != beta\",\n len(alpha_chains), len(beta_chains))\n continue\n\n structure = atomium.open(\n os.path.join(\n args.pdb_dir, \"%s.cif.gz\" % accession)).model\n\n peptides = [\n c for c in structure.chains()\n if len(c) >= args.peptide_chain_min_length and\n len(c) <= args.peptide_chain_max_length\n ]\n\n if len(peptides) == 0:\n print(\"Skipping\", accession, \"because no peptides\")\n continue\n\n structure.optimise_distances()\n\n if accession in args.reference_structure:\n # Save for later\n info_by_accession[accession] = {\n \"structure\": structure,\n \"peptides\": peptides,\n \"mhc_chain_to_kind\": mhc_chain_to_kind,\n \"aligned_df\": sub_df.copy(),\n }\n\n mhc_chain_to_position_map = {}\n for chain in mhc_chain_to_kind:\n mhc_chain_to_position_map[chain] = make_position_to_aligned_position_dict(\n sub_df.loc[chain, \"aligned_sequence\"])\n\n for peptide in peptides:\n seen = set()\n for cutoff in sorted(args.cutoffs):\n nearby = [\n r for r in peptide.nearby_hets(\n cutoff=cutoff, residues=True, ligands=False)\n if r not in seen\n ]\n seen.update(nearby)\n for residue in nearby:\n kind = mhc_chain_to_kind.get(residue.chain.id)\n if kind is not None:\n index = residue.chain.residues().index(residue)\n row = sub_df.loc[residue.chain.id]\n numpy.testing.assert_equal(\n residue.code,\n row.unaligned[index])\n aligned_position = (\n mhc_chain_to_position_map[residue.chain.id][index])\n numpy.testing.assert_equal(\n residue.code,\n row.aligned_sequence[aligned_position])\n contacts_df.append((\n accession,\n cutoff,\n peptide.id,\n residue.chain.id,\n kind,\n index,\n aligned_position,\n residue.code))\n\n contacts_df = pandas.DataFrame(\n contacts_df, columns=[\n \"accession\",\n \"cutoff\",\n \"peptide_chain\",\n \"mhc_chain\",\n \"mhc_chain_kind\",\n \"mhc_residue_unaligned\",\n \"mhc_residue_aligned\",\n \"mhc_residue\",\n ])\n\n num_accessions = contacts_df.accession.nunique()\n positional_contact_rates_df = contacts_df.groupby(\n [\"mhc_chain_kind\", \"mhc_residue_aligned\", \"cutoff\"]\n ).accession.nunique().unstack().reindex(\n sorted(args.cutoffs), axis=1).fillna(0.0).cumsum(1) / num_accessions\n\n positional_df = minor_allele_fraction_df.merge(\n positional_contact_rates_df,\n how=\"left\",\n left_index=True,\n right_index=True).fillna(0)\n\n # Criteria name -> alpha or beta -> list of positions\n criteria_to_positions = collections.OrderedDict()\n for (maf, cutoff, fraction) in args.criteria:\n name = \"maf_%s_and_%s_within_%s_angstrom\" % (maf, fraction, cutoff)\n positional_df[name] = (\n (positional_df.minor_allele_fraction >= maf) &\n (positional_df[cutoff] >= fraction)\n )\n positions = positional_df.loc[\n positional_df[name]\n ].index.to_frame().reset_index(drop=True).groupby(\n \"mhc_chain_kind\"\n ).mhc_residue_aligned.unique().map(sorted).to_dict()\n\n criteria_to_positions[name] = positions\n print(\"Criteria\", name, \"selected:\")\n for (k, v) in criteria_to_positions[name].items():\n print(k, len(v))\n\n pseudosequences_df = non_pdb_aligned_df.copy()\n for (criteria, d) in criteria_to_positions.items():\n for kind in [\"alpha\", \"beta\"]:\n positions = d.get(kind, [])\n sub = pseudosequences_df.loc[\n pseudosequences_df.kind == kind,\n ]\n pseudosequences_df.loc[\n sub.index,\n criteria\n ] = sub.aligned_sequence.map(\n operator.itemgetter(*positions)\n ).map(\"\".join).str.replace(\"-\", \"X\")\n pseudosequences_df.index = pseudosequences_df.index.str.split().str.get(1)\n assert pseudosequences_df.index.value_counts().max() == 1\n\n main_result_df = pseudosequences_df[\n list(criteria_to_positions) + [\"kind\"]\n ].copy()\n\n main_result_df.to_csv(args.out_csv, index=True)\n print(\"Wrote %s: \" % str(main_result_df.shape), args.out_csv)\n\n if args.out_aux_dir:\n if not os.path.exists(args.out_aux_dir):\n os.mkdir(args.out_aux_dir)\n\n filename = os.path.join(args.out_aux_dir, \"aligned_sequences.csv\")\n pseudosequences_df.to_csv(filename, index=True)\n print(\"Wrote: \", filename)\n\n filename = os.path.join(args.out_aux_dir, \"contacts.csv\")\n contacts_df.to_csv(filename, index=True)\n print(\"Wrote: \", filename)\n\n # Positional. We add reference allele position numbering and amino acids.\n if args.reference_allele:\n write_df = positional_df.copy()\n (alpha_reference, beta_reference) = args.reference_allele\n reference_name = \"%s/%s\" % (alpha_reference, beta_reference)\n reference_alleles = {\n \"alpha\": alpha_reference,\n \"beta\": beta_reference,\n }\n for kind in [\"alpha\", \"beta\"]:\n reference_allele = reference_alleles[kind]\n reference_sequence = pseudosequences_df.loc[\n reference_allele, \"aligned_sequence\"\n ]\n position_map = make_aligned_position_to_position_dict(\n reference_sequence)\n write_df.loc[\n kind,\n reference_name + \" position\"\n ] = write_df.loc[\n kind\n ].index.map(position_map)\n write_df.loc[\n kind,\n reference_name + \" aa\"\n ] = write_df.loc[\n kind\n ].index.map(lambda pos: reference_sequence[pos])\n filename = os.path.join(args.out_aux_dir, \"positional.csv\")\n write_df.to_csv(filename, index=True)\n print(\"Wrote: \", filename)\n\n # Reference structures\n # Write out reference structures with the \"bvalue\" atom property used\n # to indicate minor allele fractions / fraction of residues within a\n # given distance of the peptide / inclusion in pseudosequences.\n # This can be used to generate colored renderings showing these\n # properties, e.g. in pymol.\n # This \"b-factor\" hack is commonly used to store arbitrary user data\n # in a PDB file. There may be a better way for CIF files but I don't\n # know of one.\n for accession in args.reference_structure:\n positional_with_residues_df = positional_df.copy()\n positional_with_residues_df[\n \"residues\"\n ] = positional_with_residues_df.index.map(lambda i: [])\n\n info = info_by_accession.get(accession)\n if not info:\n print(\"No info for reference structure\", accession)\n continue\n\n structure = info['structure']\n\n for chain, row in info['aligned_df'].iterrows():\n position_map = make_position_to_aligned_position_dict(\n row.aligned_sequence)\n residues_df = pandas.DataFrame({\n \"residue\": structure.chain(chain).residues(),\n })\n residues_df[\"aligned_position\"] = residues_df.index.map(\n position_map)\n\n for _, residue_row in residues_df.iterrows():\n positional_with_residues_df.loc[\n (row.kind, residue_row.aligned_position),\n \"residues\"\n ].append(residue_row.residue)\n\n positional_with_residues_df = positional_with_residues_df.loc[\n positional_with_residues_df.residues.str.len() > 0\n ]\n\n quantitative_columns = positional_with_residues_df.dtypes.loc[\n (positional_with_residues_df.dtypes == float) |\n (positional_with_residues_df.dtypes == bool)\n ].index\n\n for atom in structure.atoms():\n atom.bvalue = 0\n\n for col in quantitative_columns:\n # Assign bfactors based on the particular column.\n for _, row in positional_with_residues_df.iterrows():\n for residue in row.residues:\n for atom in residue.atoms():\n atom.bvalue = float(row[col]) * 100.0\n\n # Write out the file with modified bvalues.\n filename = os.path.join(\n args.out_aux_dir,\n \"%s.%s.cif\" % (accession, col))\n structure.save(filename)\n print(\"Wrote:\", filename)\n\n\n\nif __name__ == '__main__':\n run()\n" }, { "alpha_fraction": 0.5695514678955078, "alphanum_fraction": 0.7115603089332581, "avg_line_length": 39.17258834838867, "blob_id": "df4253ecc1fcbab3b1f38c631a5a313d94035b57", "content_id": "989c41ad2f437d41b99f1658d391ea7f4f4f05dd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 7915, "license_type": "permissive", "max_line_length": 166, "num_lines": 197, "path": "/downloads-generation/data_published/GENERATE.sh", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n# Download published MHC II ligand data.\n#\nset -e\nset -x\n\nDOWNLOAD_NAME=data_published\nSCRATCH_DIR=${TMPDIR-/tmp}/mhc2flurry-downloads-generation\nSCRIPT_ABSOLUTE_PATH=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/$(basename \"${BASH_SOURCE[0]}\")\"\nSCRIPT_DIR=$(dirname \"$SCRIPT_ABSOLUTE_PATH\")\n\nmkdir -p \"$SCRATCH_DIR\"\nrm -rf \"$SCRATCH_DIR/$DOWNLOAD_NAME\"\nmkdir \"$SCRATCH_DIR/$DOWNLOAD_NAME\"\n\n# Send stdout and stderr to a logfile included with the archive.\nexec > >(tee -ia \"$SCRATCH_DIR/$DOWNLOAD_NAME/LOG.txt\")\nexec 2> >(tee -ia \"$SCRATCH_DIR/$DOWNLOAD_NAME/LOG.txt\" >&2)\n\ndate\n\ncd $SCRATCH_DIR/$DOWNLOAD_NAME\n\n############################################\n# MS: Class II\n############################################\n\n## Scally, ..., Rossjohn. J. Exp. Med. [PMID 24190431]\n# PMID=24190431\n# mkdir -p ms/$PMID\n# TODO: couldn't find peptides, need to look again.\n\n# Bergseng, ..., Sollid. Immunogenetics 2015 [PMID 25502872]\nPMID=25502872\nmkdir -p ms/$PMID\nwget -q 'https://static-content.springer.com/esm/art%3A10.1007%2Fs00251-014-0819-9/MediaObjects/251_2014_819_MOESM3_ESM.xlsx' -P ms/$PMID\n\n# Sofron, ..., Fugmann. Eur. J. Immunol. 2015 [PMID 26495903]\nPMID=26495903\nmkdir -p ms/$PMID\nwget -q 'https://onlinelibrary.wiley.com/action/downloadSupplement?doi=10.1002%2Feji.201545930&file=eji3483-sup-0003-supinfo.xlsx' -P ms/$PMID\nwget -q 'https://onlinelibrary.wiley.com/action/downloadSupplement?doi=10.1002%2Feji.201545930&file=eji3483-sup-0004-supinfo.xlsx' -P ms/$PMID\nwget -q 'https://onlinelibrary.wiley.com/action/downloadSupplement?doi=10.1002%2Feji.201545930&file=eji3483-sup-0005-supinfo.xlsx' -P ms/$PMID\n\n# Bassani-Sternberg, ..., Krackhardt Nature Comm. 2016 [PMID 27869121]\nPMID=27869121\nmkdir -p ms/$PMID\nwget -q \"https://static-content.springer.com/esm/art%3A10.1038%2Fncomms13404/MediaObjects/41467_2016_BFncomms13404_MOESM1318_ESM.xlsx\" -P ms/$PMID\n\n# Clement, ..., Santambrogio. J. Biol. Chem. 2016 [PMID 26740625]\nPMID=26740625\nmkdir -p ms/$PMID\nwget -q 'https://www.jbc.org/cms/10.1074/jbc.M115.655738/attachment/687abf48-576f-41e1-8f9f-dc40fbfa27ae/mmc1.zip' -P ms/$PMID\npushd ms/$PMID\nunzip *.zip\nrm *.zip\npopd\n\n# Heyder, ..., Ytterberg. Mol. Cell. Proteomics 2016 [PMID 27452731]\nPMID=27452731\nmkdir -p ms/$PMID\nwget -q 'https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5013314/bin/10.1074_M116.060764_mcp.M116.060764-5.xlsx' -P ms/$PMID\nwget -q 'https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5013314/bin/10.1074_M116.060764_mcp.M116.060764-6.xlsx' -P ms/$PMID\nwget -q 'https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5013314/bin/10.1074_M116.060764_mcp.M116.060764-7.xlsx' -P ms/$PMID\nwget -q 'https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5013314/bin/10.1074_M116.060764_mcp.M116.060764-8.xlsx' -P ms/$PMID\nwget -q 'https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5013314/bin/10.1074_M116.060764_mcp.M116.060764-9.xlsx' -P ms/$PMID\nwget -q 'https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5013314/bin/10.1074_M116.060764_mcp.M116.060764-5.xlsx' -P ms/$PMID\n\n## Wang, ..., Costello. J. Proteom. Res. 2017 [PMID 27726376]\nPMID=27726376\nmkdir -p ms/$PMID\nwget -q 'https://pubs.acs.org/doi/suppl/10.1021/acs.jproteome.6b00386/suppl_file/pr6b00386_si_001.docx' -P ms/$PMID\nwget -q 'https://pubs.acs.org/doi/suppl/10.1021/acs.jproteome.6b00386/suppl_file/pr6b00386_si_002.xlsx' -P ms/$PMID\nwget -q 'https://pubs.acs.org/doi/suppl/10.1021/acs.jproteome.6b00386/suppl_file/pr6b00386_si_003.xlsx' -P ms/$PMID\nwget -q 'https://pubs.acs.org/doi/suppl/10.1021/acs.jproteome.6b00386/suppl_file/pr6b00386_si_004.xlsx' -P ms/$PMID\n\n## Khodadoust, ..., Alizadeh. Nature 2017 [PMID 28329770]\n# PMID=28329770\n# mkdir -p ms/$PMID\n# TODO. PRIDE Archive at www.ebi.ac.uk/pride/archive under accession numbers PXD004746 and PXD005704\n\n# Ooi, ..., Kitching. Nature 2017 [PMID 28467828]\nPMID=28467828\nmkdir -p ms/$PMID\nwget -q 'https://static-content.springer.com/esm/art%3A10.1038%2Fnature22329/MediaObjects/41586_2017_BFnature22329_MOESM1_ESM.xlsx' -P ms/$PMID\n\n# Ritz, ..., Fugmann. Proteomics 2018 [PMID 29314611]\nPMID=29314611\nmkdir -p ms/$PMID\nwget -q 'https://onlinelibrary.wiley.com/action/downloadSupplement?doi=10.1002%2Fpmic.201700246&file=pmic12799-sup-0006-TableS4.xlsx' -P ms/$PMID\n\n# Ting, ..., Rossjohn. J. Biol. Chem. 2018 [PMID 29317506]\nPMID=29317506\nmkdir -p ms/$PMID\nwget -q 'https://www.jbc.org/cms/10.1074/jbc.RA117.001013/attachment/3a33375f-7acd-420c-ac79-e3adbb6cf394/mmc1.zip' -P ms/$PMID\npushd ms/$PMID\nunzip *.zip\nrm *.zip\npopd\n\n# Nelde, ..., Walz. Oncoimmunology 2018 [PMID 29632711]\nPMID=29632711\nmkdir -p ms/$PMID\nwget -q 'https://www.tandfonline.com/doi/suppl/10.1080/2162402X.2017.1316438/suppl_file/koni_a_1316438_sm6974.zip' -P ms/$PMID\npushd ms/$PMID\nunzip *.zip\nrm *.zip\npopd\n\n## Alvaro-Benito, ..., Freund. Front. Immunol 2018 [PMID 29774024]\n# PMID=29774024\n# mkdir -p ms/$PMID\n# TODO\n\n## Nanaware, ..., Stern. Mol. Cell. Proteomics 2019 [PMID 30573663]\n# PMID=30573663\n# mkdir -p ms/$PMID\n# TODO: Accession MSV000082570 at http://massive.ucsd.edu\n\n# Abelin, ..., Rooney. Immunity 2019 [PMID 31495665]\nPMID=31495665\nmkdir -p ms/$PMID\nwget -q 'https://ars.els-cdn.com/content/image/1-s2.0-S1074761319303632-mmc2.xlsx' -P ms/$PMID\n\n# Racle, ..., Gfeller. Nature Biotechnology 2019 [PMID 31611696]\nPMID=31611696\nmkdir -p ms/$PMID\nwget -q 'https://static-content.springer.com/esm/art%3A10.1038%2Fs41587-019-0289-6/MediaObjects/41587_2019_289_MOESM4_ESM.txt' -P ms/$PMID\nwget -q 'https://static-content.springer.com/esm/art%3A10.1038%2Fs41587-019-0289-6/MediaObjects/41587_2019_289_MOESM5_ESM.txt' -P ms/$PMID\n\n############################################\n# Non MS: T cell epitopes, yeast display, etc.\n############################################\n#\n# \"NetMHCpan-4.1 and NetMHCIIpan-4.0: improved predictions of MHC antigen presentation by concurrent motif deconvolution and integration of MS MHC eluted ligand data\"\n# Reynissonm ..., Nielsen. Nucleic Acids Res. 2020 [PMID 32406916]\n#\nPMID=32406916\nmkdir -p other/$PMID\nwget -q 'https://services.healthtech.dtu.dk/services/NetMHCIIpan-4.0/suppl/CD4_epitopes/CD4_epitopes.fsa' -P other/$PMID\nwget -q 'http://www.cbs.dtu.dk/suppl/immunology/NAR_NetMHCpan_NetMHCIIpan/NetMHCIIpan_train.tar.gz' -P other/$PMID\npushd other/$PMID\ntar xvzf *.tar.gz\nrm *.tar.gz\nfor i in $(find . -mindepth 1 -type f)\ndo\n bzip2 $i\ndone\npopd\n\n#\n# \"Repertoire-scale determination of class II MHC peptide binding via yeast display improves antigen prediction\"\n# Rapazzo, ..., Birnbaum. Nat. Commun. 2020 [PMID 32887877]\n#\nPMID=32887877\nmkdir -p other/$PMID\nwget -q 'https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7473865/bin/41467_2020_18204_MOESM4_ESM.xlsx' -P other/$PMID\n\n############################################\n# RNA-seq expression data (TPMs)\n############################################\n# CCLE as processed by expression atlas\nDATASET=expression-atlas-22460905\nmkdir -p expression/$DATASET\nwget -q https://www.ebi.ac.uk/gxa/experiments-content/E-MTAB-2770/resources/ExperimentDownloadSupplier.RnaSeqBaseline/tpms.tsv -P expression/$DATASET\n\n# Human protein atlas\nDATASET=human-protein-atlas\nmkdir -p expression/$DATASET\npushd expression/$DATASET\nwget -q https://www.proteinatlas.org/download/rna_celline.tsv.zip\nwget -q https://www.proteinatlas.org/download/rna_blood_cell_sample_tpm_m.tsv.zip\nwget -q https://www.proteinatlas.org/download/rna_tissue_gtex.tsv.zip\nfor i in $(ls *.zip)\ndo\n unzip $i\n rm $i\ndone\npopd\n\n# Melanoma. Original publication\n# Barry, ..., Krummel Nature Medicine 2018 [PMID 29942093].\nDATASET=GSE113126\nmkdir -p expression/$DATASET \npushd expression/$DATASET\nwget -q \"https://www.ncbi.nlm.nih.gov/geo/download/?acc=GSE113126&format=file\" -O GSE113126_RAW.tar\ntar -xvf GSE113126_RAW.tar\nrm GSE113126_RAW.tar\npopd\n\n############################################\ncp $SCRIPT_ABSOLUTE_PATH .\nbzip2 LOG.txt\nRESULT=\"$SCRATCH_DIR/${DOWNLOAD_NAME}.$(date +%Y%m%d).tar.bz2\"\ntar -cjf \"$RESULT\" *\necho \"Created archive: $RESULT\"\n\n" }, { "alpha_fraction": 0.6377836465835571, "alphanum_fraction": 0.6420585513114929, "avg_line_length": 29.562814712524414, "blob_id": "0ef03d2a9b2e05f8f748e2db82f5301beb75f9c4", "content_id": "984679e970434406e84e515b01bc682828cbfcf3", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6082, "license_type": "permissive", "max_line_length": 83, "num_lines": 199, "path": "/mhc2flurry/downloads.py", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "\"\"\"\nManage local downloaded data.\n\"\"\"\n\nfrom __future__ import (\n print_function,\n division,\n absolute_import,\n)\nimport logging\nimport yaml\nfrom os.path import join, exists\nfrom os import environ\nfrom pipes import quote\nfrom collections import OrderedDict\nfrom appdirs import user_data_dir\nfrom pkg_resources import resource_string\n\nimport pandas\n\nENVIRONMENT_VARIABLES = [\n \"MHC2FLURRY_DATA_DIR\",\n \"MHC2FLURRY_DOWNLOADS_CURRENT_RELEASE\",\n \"MHC2FLURRY_DOWNLOADS_DIR\",\n \"MHC2FLURRY_DEFAULT_MODELS_DIR\",\n \"MHC2FLURRY_DOWNLOADS_GITHUB_AUTH_TOKEN\"\n]\n\n_DOWNLOADS_DIR = None\n_CURRENT_RELEASE = None\n_METADATA = None\n_MHC2FLURRY_DEFAULT_MODELS_DIR = environ.get(\n \"MHC2FLURRY_DEFAULT_MODELS_DIR\")\n\ndef get_downloads_dir():\n \"\"\"\n Return the path to local downloaded data\n \"\"\"\n return _DOWNLOADS_DIR\n\n\ndef get_current_release():\n \"\"\"\n Return the current downloaded data release\n \"\"\"\n return _CURRENT_RELEASE\n\n\ndef get_downloads_metadata():\n \"\"\"\n Return the contents of downloads.yml as a dict\n \"\"\"\n global _METADATA\n if _METADATA is None:\n _METADATA = yaml.safe_load(resource_string(__name__, \"downloads.yml\"))\n return _METADATA\n\n\ndef get_default_class2_models_dir(test_exists=True):\n \"\"\"\n Return the absolute path to the default class2 models dir.\n\n If environment variable MHC2FLURRY_DEFAULT_MODELS_DIR is set to an\n absolute path, return that path. If it's set to a relative path (i.e. does\n not start with /) then return that path taken to be relative to the mhc2flurry\n downloads dir.\n\n If environment variable _MHC2FLURRY_DEFAULT_MODELS_DIR is NOT set,\n then return the path to downloaded models in the \"models_class2\" download.\n\n Parameters\n ----------\n\n test_exists : boolean, optional\n Whether to raise an exception of the path does not exist\n\n Returns\n -------\n string : absolute path\n \"\"\"\n if _MHC2FLURRY_DEFAULT_MODELS_DIR:\n result = join(get_downloads_dir(), _MHC2FLURRY_DEFAULT_MODELS_DIR)\n if test_exists and not exists(result):\n raise IOError(\"No such directory: %s\" % result)\n return result\n return get_path(\n \"models_class2\", \"models\", test_exists=test_exists)\n\n\ndef get_current_release_downloads():\n \"\"\"\n Return a dict of all available downloads in the current release.\n\n The dict keys are the names of the downloads. The values are a dict\n with two entries:\n\n downloaded : bool\n Whether the download is currently available locally\n\n metadata : dict\n Info about the download from downloads.yml such as URL\n\n up_to_date : bool or None\n Whether the download URL(s) match what was used to download the current\n data. This is None if it cannot be determined.\n \"\"\"\n downloads = (\n get_downloads_metadata()\n ['releases']\n [get_current_release()]\n ['downloads'])\n\n def up_to_date(dir, urls):\n try:\n df = pandas.read_csv(join(dir, \"DOWNLOAD_INFO.csv\"))\n return list(df.url) == list(urls)\n except IOError:\n return None\n\n return OrderedDict(\n (download[\"name\"], {\n 'downloaded': exists(join(get_downloads_dir(), download[\"name\"])),\n 'up_to_date': up_to_date(\n join(get_downloads_dir(), download[\"name\"]),\n [download['url']] if 'url' in download else download['part_urls']),\n 'metadata': download,\n }) for download in downloads\n )\n\n\ndef get_path(download_name, filename='', test_exists=True):\n \"\"\"\n Get the local path to a file in a MHC2flurry download\n\n Parameters\n -----------\n download_name : string\n\n filename : string\n Relative path within the download to the file of interest\n\n test_exists : boolean\n If True (default) throw an error telling the user how to download the\n data if the file does not exist\n\n Returns\n -----------\n string giving local absolute path\n \"\"\"\n assert '/' not in download_name, \"Invalid download: %s\" % download_name\n path = join(get_downloads_dir(), download_name, filename)\n if test_exists and not exists(path):\n raise RuntimeError(\n \"Missing MHC2flurry downloadable file: %s. \"\n \"To download this data, run:\\n\\tmhc2flurry-downloads fetch %s\\n\"\n \"in a shell.\"\n % (quote(path), download_name))\n return path\n\n\ndef configure():\n \"\"\"\n Setup various global variables based on environment variables.\n \"\"\"\n global _DOWNLOADS_DIR\n global _CURRENT_RELEASE\n\n _CURRENT_RELEASE = None\n _DOWNLOADS_DIR = environ.get(\"MHC2FLURRY_DOWNLOADS_DIR\")\n if not _DOWNLOADS_DIR:\n metadata = get_downloads_metadata()\n _CURRENT_RELEASE = environ.get(\"MHC2FLURRY_DOWNLOADS_CURRENT_RELEASE\")\n if not _CURRENT_RELEASE:\n _CURRENT_RELEASE = metadata['current-release']\n\n current_release_compatability = (\n metadata[\"releases\"][_CURRENT_RELEASE][\"compatibility-version\"])\n current_compatability = metadata[\"current-compatibility-version\"]\n if current_release_compatability != current_compatability:\n logging.warning(\n \"The specified downloads are not compatible with this version \"\n \"of the MHC2flurry codebase. Downloads: release %s, \"\n \"compatability version: %d. Code compatability version: %d\",\n _CURRENT_RELEASE,\n current_release_compatability,\n current_compatability)\n\n data_dir = environ.get(\"MHC2FLURRY_DATA_DIR\")\n if not data_dir:\n # increase the version every time we make a breaking change in\n # how the data is organized. For changes to e.g. just model\n # serialization, the downloads release numbers should be used.\n data_dir = user_data_dir(\"mhc2flurry\", version=\"1\")\n _DOWNLOADS_DIR = join(data_dir, _CURRENT_RELEASE)\n\n logging.debug(\"Configured MHC2FLURRY_DOWNLOADS_DIR: %s\", _DOWNLOADS_DIR)\n\n\nconfigure()\n" }, { "alpha_fraction": 0.7078651785850525, "alphanum_fraction": 0.7865168452262878, "avg_line_length": 8.88888931274414, "blob_id": "e9b8df58995b06e71cec4962b81b70e7ad489a1d", "content_id": "0c8e065a3f6cbda6646d7ad8755a9d2731cd9fc1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 89, "license_type": "permissive", "max_line_length": 17, "num_lines": 9, "path": "/requirements.txt", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "six\npandas>=0.20.3\ntensorflow>=2.3.0\nappdirs\nscikit-learn\nmhcgnomes\npyyaml\ntqdm\nnp_utils\n" }, { "alpha_fraction": 0.6095238327980042, "alphanum_fraction": 0.6140350699424744, "avg_line_length": 23.9375, "blob_id": "38af90bacea260acd08b9399b7b1f9bec7c0a778", "content_id": "c630c532524756c550b5b5d5ceb9e859ce5a656c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1995, "license_type": "permissive", "max_line_length": 80, "num_lines": 80, "path": "/downloads-generation/allele_sequences/filter_sequences.py", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "\"\"\"\nFilter and combine class II sequence fastas.\n\"\"\"\nfrom __future__ import print_function\n\nimport sys\nimport argparse\n\nfrom mhc2flurry.common import normalize_allele_name\n\nimport Bio.SeqIO # pylint: disable=import-error\n\n\nparser = argparse.ArgumentParser(usage=__doc__)\n\nparser.add_argument(\n \"fastas\",\n nargs=\"+\",\n help=\"Unaligned fastas\")\n\nparser.add_argument(\n \"--kind\",\n required=True,\n choices=(\"alpha\", \"beta\"),\n help=\"Chain\")\n\nparser.add_argument(\n \"--out\",\n required=True,\n help=\"Fasta output\")\n\nmin_lengths = {\n \"alpha\": 200,\n \"beta\": 200,\n}\n\n\ndef run():\n args = parser.parse_args(sys.argv[1:])\n print(args)\n\n min_length = min_lengths[args.kind]\n\n output_records = []\n seen = set()\n sequences = set()\n\n input_records = []\n for fasta in args.fastas:\n reader = Bio.SeqIO.parse(fasta, \"fasta\")\n input_records.extend(reader)\n\n # Iterate longest records first so that when multiple records have the\n # same two digit normalized allele, we use the longest one.\n for record in sorted(input_records, key=lambda r: len(r.seq), reverse=True):\n original_name = record.description.split()[1]\n name = normalize_allele_name(original_name)\n if not name:\n print(\"Skipping due to parsing\", original_name)\n continue\n if name in seen:\n continue\n if len(record.seq) < min_length:\n print(\"Skipping due to short length\", name, record.description)\n continue\n seen.add(name)\n sequences.add(record.seq)\n record.id = \"%s.%s\" % (args.kind, record.id)\n record.description = \"%s %s\" % (name, record.description)\n output_records.append(record)\n\n with open(args.out, \"w\") as fd:\n Bio.SeqIO.write(output_records, fd, \"fasta\")\n\n print(\"Wrote %d / %d [%d unique] sequences: %s\" % (\n len(output_records), len(input_records), len(sequences), args.out))\n\n\nif __name__ == '__main__':\n run()\n" }, { "alpha_fraction": 0.5327585935592651, "alphanum_fraction": 0.5327585935592651, "avg_line_length": 26.619047164916992, "blob_id": "ea40547000e26311a09283833d6a2ad4278be8f3", "content_id": "0e8687a048e418b62f4f0e582c0e917b3bf9f2b3", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1160, "license_type": "permissive", "max_line_length": 58, "num_lines": 42, "path": "/mhc2flurry/allele_encoding_pair.py", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "from .allele_encoding import AlleleEncoding\n\n\nclass AlleleEncodingPair(object):\n def __init__(\n self,\n alpha_allele_encoding,\n beta_allele_encoding):\n \"\"\"\n \"\"\"\n\n self.alpha_allele_encoding = alpha_allele_encoding\n self.beta_allele_encoding = beta_allele_encoding\n\n def from_pairs(self, allele_pairs):\n alpha_alleles = [a for (a, b) in allele_pairs]\n beta_alleles = [b for (a, b) in allele_pairs]\n return AlleleEncodingPair(\n AlleleEncoding(\n alpha_alleles,\n borrow_from=self.alpha_allele_encoding),\n AlleleEncoding(\n beta_alleles,\n borrow_from=self.beta_allele_encoding),\n )\n\n @property\n def allele_encodings(self):\n return [\n (\"alpha\", self.alpha_allele_encoding),\n (\"beta\", self.beta_allele_encoding)\n ]\n\n @property\n def allele_pairs(self):\n return [\n (a, b)\n for (a, b)\n in zip(\n self.alpha_allele_encoding.alleles,\n self.beta_allele_encoding.alleles)\n ]\n" }, { "alpha_fraction": 0.3186813294887543, "alphanum_fraction": 0.504273533821106, "avg_line_length": 25.419355392456055, "blob_id": "7d15fb28483f369cc2a923d5cfe5e217a33cedfb", "content_id": "8c9c7cdfabc07d4c1d2e3ea5cd4bfefd59c8fc2f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 819, "license_type": "permissive", "max_line_length": 47, "num_lines": 31, "path": "/test/test_common.py", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "from mhc2flurry.common import make_allele_pairs\n\n\ndef test_allele_pairs():\n alleles = [\n \"HLA-DRB1*07:01\",\n \"HLA-DRB1*16:01\",\n \"HLA-DRB4*01:03\",\n \"HLA-DRB5*02:02\",\n \"HLA-DPA1*01:03\",\n \"HLA-DPB1*02:01\",\n \"HLA-DPB1*23:01\",\n \"HLA-DQA1*01:02\",\n \"HLA-DQA1*02:01\",\n \"HLA-DQB1*02:02\",\n \"HLA-DQB1*05:02\",\n ]\n result = make_allele_pairs(alleles)\n\n assert result == [\n 'HLA-DRA*01:01-DRB1*07:01',\n 'HLA-DRA*01:01-DRB1*16:01',\n 'HLA-DRA*01:01-DRB4*01:03',\n 'HLA-DRA*01:01-DRB5*02:02',\n 'HLA-DPA1*01:03-DPB1*02:01',\n 'HLA-DPA1*01:03-DPB1*23:01',\n 'HLA-DQA1*01:02-DQB1*02:02',\n 'HLA-DQA1*01:02-DQB1*05:02',\n 'HLA-DQA1*02:01-DQB1*02:02',\n 'HLA-DQA1*02:01-DQB1*05:02',\n ]\n" }, { "alpha_fraction": 0.6526548862457275, "alphanum_fraction": 0.6565265655517578, "avg_line_length": 25.58823585510254, "blob_id": "cd596fd7c39e26d361a8471de08acb19423a692f", "content_id": "11d566e4331e70caec5ca2ac9a3a09319e4edec4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1808, "license_type": "permissive", "max_line_length": 83, "num_lines": 68, "path": "/downloads-generation/allele_sequences/assign_pdb_sequences_to_alpha_or_beta.py", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "# Assign PDB sequences (searched by mmseqs against IMGT sequences)\n# to alpha vs beta based on mmseqs results\n\nimport argparse\nimport sys\nimport pandas\nimport os\n\nfrom mhc2flurry.fasta import read_fasta_to_dataframe\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n \"pdb_sequences\",\n metavar=\"FASTA\",\n help='PDB sequences')\nparser.add_argument(\n \"search_results\",\n metavar=\"TXT\",\n help='mmseqs search results')\nparser.add_argument(\n \"--mmseqs-output-format\",\n metavar=\"A,B,C\",\n required=True,\n help='mmseqs output format (comma separated list of fields)')\nparser.add_argument(\n \"--out-alpha\",\n metavar=\"FASTA\",\n help='Output file')\nparser.add_argument(\n \"--out-beta\",\n metavar=\"FASTA\",\n help='Output file')\nargs = parser.parse_args(sys.argv[1:])\n\nprint(args)\n\nsequences_df = read_fasta_to_dataframe(args.pdb_sequences).set_index(\"sequence_id\")\n\nsearch_df = pandas.read_csv(\n args.search_results,\n names=args.mmseqs_output_format.split(\",\"),\n sep=None)\nsearch_df[\"kind\"] = search_df.target.str.split(\".\").str.get(0)\n\ndf = search_df.loc[\n (search_df.qcov > 0.7) &\n (search_df.tcov > 0.5)\n].sort_values(\"evalue\").drop_duplicates(\"query\").set_index(\"query\")\n\nprint(df)\nprint(\"Breakdown by kind [should be equal or nearly equal]\")\nprint(df.kind.value_counts())\n\n\ndef write_fasta(filename, sub_df):\n with open(filename, \"w\") as fd:\n for name, row in sub_df.iterrows():\n seq = sequences_df.loc[name].sequence\n fd.write(\">pdb.%s\\n\" % name)\n fd.write(seq)\n fd.write(\"\\n\")\n print(\"Wrote\", filename, \"with\", len(sub_df), \"sequences\")\n\nif args.out_alpha:\n write_fasta(args.out_alpha, df.loc[df.kind == \"alpha\"])\n\nif args.out_beta:\n write_fasta(args.out_beta, df.loc[df.kind == \"beta\"])\n" }, { "alpha_fraction": 0.6019534468650818, "alphanum_fraction": 0.6267468333244324, "avg_line_length": 29.800926208496094, "blob_id": "a9bbb7125679e118bc2984a26d2e95f170dc95b6", "content_id": "84f854ce3138bba29fce20fd551189e5e219a7f4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6655, "license_type": "permissive", "max_line_length": 79, "num_lines": 216, "path": "/test/test_class2_neural_network.py", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "import logging\nlogging.getLogger('tensorflow').disabled = True\nlogging.getLogger('matplotlib').disabled = True\n\nimport numpy\nimport tensorflow.random\nnumpy.random.seed(0)\ntensorflow.random.set_seed(0)\n\nimport pandas\nfrom sklearn.metrics import roc_auc_score\n\nimport mhcgnomes\n\nfrom mhc2flurry.allele_encoding_pair import AlleleEncodingPair\nfrom mhc2flurry.allele_encoding import AlleleEncoding\nfrom mhc2flurry.class2_neural_network import Class2NeuralNetwork\nfrom mhc2flurry.common import random_peptides\n\nfrom mhc2flurry.testing_utils import cleanup, startup\nteardown = cleanup\nsetup = startup\n\n\ndef make_allele_encoding_pair(allele_names, alpha_sequences, beta_sequences):\n \"\"\"\n Given a list of allele names, return an AlleleEncodingPair\n \"\"\"\n parsed_alleles = pandas.Series([\n mhcgnomes.parse(name, infer_class2_pairing=True)\n for name in allele_names\n ])\n alpha = parsed_alleles.map(lambda p: p.alpha.to_string())\n beta = parsed_alleles.map(lambda p: p.beta.to_string())\n encoding = AlleleEncodingPair(\n AlleleEncoding(alpha, allele_to_sequence=alpha_sequences),\n AlleleEncoding(beta, allele_to_sequence=beta_sequences),\n )\n return encoding\n\n\ndef test_simple():\n # Fake pseudosequences\n alpha_sequences = {\n \"HLA-DRA*01:01\": \"AAAN\",\n }\n beta_sequences = {\n \"HLA-DRB1*01:01\": \"AAAQ\",\n \"HLA-DRB1*03:01\": \"AAAK\",\n }\n motifs = {\n \"HLA-DRB1*01:01\": \"A.K\",\n \"HLA-DRB1*03:01\": \"Q.Q\",\n }\n\n df = pandas.DataFrame(\n {\"peptide\": random_peptides(200000, length=15)}\n ).set_index(\"peptide\")\n\n for (allele, motif) in motifs.items():\n df[allele] = (df.index.str.contains(motif)).astype(int)\n\n # Resample to have 1:1 binder / non-binder\n positive_train_df = df.loc[df.max(1) > 0.8]\n train_df = pandas.concat([\n positive_train_df,\n df.loc[~df.index.isin(positive_train_df.index)].sample(\n n=len(positive_train_df))\n ])\n\n model = Class2NeuralNetwork(\n minibatch_size=1024,\n random_negative_rate=1.0,\n layer_sizes=[4],\n allele_positionwise_embedding_size=4,\n patience=10,\n max_epochs=500,\n peptide_convolutions=[\n {'kernel_size': 3, 'filters': 8, 'activation': \"relu\"},\n ],\n peptide_encoding={\n 'vector_encoding_name': 'BLOSUM62',\n 'alignment_method': 'right_pad',\n 'max_length': 20,\n },\n )\n\n train_and_check(train_df, model, alpha_sequences, beta_sequences)\n\n\ndef test_combination():\n # Fake pseudosequences\n alpha_sequences = {\n \"HLA-DRA*01:01\": \"AAAN\",\n }\n beta_sequences = {\n \"HLA-DRB1*01:01\": \"AAAA\",\n \"HLA-DRB1*03:01\": \"CAAA\",\n \"HLA-DRB1*04:01\": \"AAAC\",\n \"HLA-DRB1*05:01\": \"CAAC\",\n }\n motifs = {\n \"HLA-DRB1*01:01\": \"K.AK\",\n \"HLA-DRB1*03:01\": \"Q.CK\",\n \"HLA-DRB1*04:01\": \"K.DQ\",\n \"HLA-DRB1*05:01\": \"Q.EQ\",\n }\n\n df = pandas.DataFrame(\n {\"peptide\": random_peptides(500000, length=15)}\n ).set_index(\"peptide\")\n\n for (allele, motif) in motifs.items():\n df[allele] = (df.index.str.contains(motif)).astype(int)\n\n # Resample to have 1:1 binder / non-binder\n positive_train_df = df.loc[df.max(1) > 0.8]\n df = pandas.concat([\n positive_train_df,\n df.loc[~df.index.isin(positive_train_df.index)].sample(\n n=int(len(positive_train_df) / df.shape[1]))\n ])\n\n model = Class2NeuralNetwork(\n minibatch_size=1024,\n random_negative_rate=1.0,\n layer_sizes=[4],\n allele_positionwise_embedding_size=4,\n patience=10,\n peptide_convolutions=[\n {'kernel_size': 4, 'filters': 12, 'activation': \"relu\"},\n ],\n max_epochs=500,\n peptide_encoding={\n 'vector_encoding_name': 'BLOSUM62',\n 'alignment_method': 'right_pad',\n 'max_length': 15,\n },\n )\n\n train_df = df.sample(frac=0.8).copy()\n\n # Can we generalize to an unseen allele?\n # So far, haven't gotten this to work, so leaving this line commented.\n #train_df[\"HLA-DRB1*05:01\"] = numpy.nan\n\n train_and_check(\n df, model, alpha_sequences, beta_sequences, train_df=train_df)\n\n\ndef train_and_check(df, model, alpha_sequences, beta_sequences, train_df=None):\n print(\"Binders\")\n print((df > 0.8).sum())\n\n print(\"Binder rate\")\n print((df > 0.8).mean())\n\n if train_df is None:\n train_df = df.sample(frac=0.5)\n test_df = df.loc[~df.index.isin(train_df.index)]\n\n stacked = train_df.stack().reset_index().dropna()\n stacked.columns = ['peptide', 'allele', 'measurement_value']\n\n allele_encoding = make_allele_encoding_pair(\n stacked.allele, alpha_sequences, beta_sequences)\n\n print(model.hyperparameters)\n\n model.fit(\n stacked.peptide.values,\n affinities=stacked[\"measurement_value\"].values,\n allele_encoding_pair=allele_encoding\n )\n\n check_accuracy(\n train_df, model, alpha_sequences, beta_sequences, message=\"TRAIN\")\n check_accuracy(\n test_df, model, alpha_sequences, beta_sequences, message=\"TEST\")\n\n\ndef check_accuracy(df, network, alpha_sequences, beta_sequences, message=\"\"):\n stacked = df.stack().reset_index().dropna()\n stacked.columns = ['peptide', 'allele', 'measurement_value']\n\n allele_encoding = make_allele_encoding_pair(\n stacked.allele, alpha_sequences, beta_sequences)\n stacked[\"prediction\"] = network.predict(\n stacked.peptide, allele_encoding_pair=allele_encoding)\n\n # Overall AUC\n stacked[\"binder\"] = stacked.measurement_value > 0.8\n auc = roc_auc_score(stacked.binder, stacked.prediction)\n print(message, \"Overall AUC\", auc)\n assert auc > 0.7, message\n\n # Can we discern a binder for one allele from another?\n binder_peptides = stacked.loc[stacked.binder].peptide.unique()\n stacked_binders = stacked.loc[stacked.peptide.isin(binder_peptides)]\n allele_specific_aucs = []\n for (allele, sub_df) in stacked_binders.groupby(\"allele\"):\n print(allele)\n print(sub_df)\n auc = roc_auc_score(sub_df.binder.values, sub_df.prediction.values)\n allele_specific_aucs.append((allele, auc))\n\n allele_specific_aucs = pandas.DataFrame(\n allele_specific_aucs, columns=[\"allele\", \"auc\"])\n print(message, \"allele specific AUCs:\")\n print(allele_specific_aucs)\n\n print(message, \"Mean predictions\")\n print(stacked_binders.groupby([\"allele\", \"binder\"]).prediction.mean())\n\n for _, row in allele_specific_aucs.iterrows():\n assert row.auc > 0.8, (message, row.allele)\n\n\n" }, { "alpha_fraction": 0.7342657446861267, "alphanum_fraction": 0.7342657446861267, "avg_line_length": 14.666666984558105, "blob_id": "514548112b93ea39fc0e8317801806ade24ad227", "content_id": "40151693df88aebcb58caecc54d41d01fb356049", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 143, "license_type": "permissive", "max_line_length": 63, "num_lines": 9, "path": "/downloads-generation/data_published/README.md", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "# Published datasets\n\nThese datasets are derived from publications and do not change.\n\nTo generate this download run:\n\n```\n./GENERATE.sh\n```\n\n\n" }, { "alpha_fraction": 0.6544885039329529, "alphanum_fraction": 0.6555323600769043, "avg_line_length": 28.9375, "blob_id": "fb1c4bf22c0b73525fffff59a644164c05108890", "content_id": "4996e7fba98690e827333d1310a3185446b054ac", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 958, "license_type": "permissive", "max_line_length": 75, "num_lines": 32, "path": "/downloads-generation/allele_sequences/extract_pdb_sequences.py", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "# Given a set of PDB .cif.gz files, write out a fasta with the sequences of\n# each chain. This will be used to align MHC II PDB structures against\n# sequences from IMDB and other sources.\n\nimport argparse\nimport sys\nimport json\nimport os\nimport glob\n\nimport atomium\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n \"input\", metavar=\"JSON\", help='Director of .cif.gz files')\nparser.add_argument(\"out\", metavar=\"FILE.fasta\", help=\"Out fasta file\")\nargs = parser.parse_args(sys.argv[1:])\n\nprint(args)\n\nfiles = glob.glob(args.input + \"/*.cif.gz\")\nprint(\"Found %d files\" % len(files))\n\nwith open(args.out, \"w\") as fd:\n for file in files:\n structure = atomium.open(file)\n for chain in structure.model.chains():\n fd.write(\">%s_%s %s\\n\" % (\n structure.code, chain.id, os.path.basename(file)))\n fd.write(\"\".join(c.code for c in chain.residues()))\n fd.write(\"\\n\")\nprint(\"Wrote: \", args.out)\n" }, { "alpha_fraction": 0.6734693646430969, "alphanum_fraction": 0.6785714030265808, "avg_line_length": 19.63157844543457, "blob_id": "751c7f2cb8a89f5337754b306888f66cf2316e0b", "content_id": "314f9cd23ab163ad8a5f3c88b0e31901abcc653a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 392, "license_type": "permissive", "max_line_length": 62, "num_lines": 19, "path": "/mhc2flurry/testing_utils.py", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "\"\"\"\nUtilities used in MHC2flurry unit tests.\n\"\"\"\nfrom .common import configure_tensorflow\n\n\ndef startup():\n \"\"\"\n Configure Keras backend for running unit tests.\n \"\"\"\n configure_tensorflow(\"tensorflow-cpu\", num_threads=2)\n\n\ndef cleanup():\n \"\"\"\n Clear tensorflow session and other process-wide resources.\n \"\"\"\n import tensorflow.keras.backend as K\n K.clear_session()\n" }, { "alpha_fraction": 0.6859995126724243, "alphanum_fraction": 0.6919419765472412, "avg_line_length": 31.8671875, "blob_id": "45b51799b4e9d9c9806f2860edb0c700b0a01c5b", "content_id": "242b91f90da6a00baebedeec3c45caca6542d65d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4207, "license_type": "permissive", "max_line_length": 100, "num_lines": 128, "path": "/downloads-generation/data_curated/GENERATE.sh", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n# Create \"curated\" training data, which combines an IEDB download with additional\n# published data, removes unusable entries, normalizes allele name, and performs\n# other filtering and standardization.\n#\nset -e\nset -x\n\nDOWNLOAD_NAME=data_curated\nSCRATCH_DIR=${TMPDIR-/tmp}/mhc2flurry-downloads-generation\nSCRIPT_ABSOLUTE_PATH=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/$(basename \"${BASH_SOURCE[0]}\")\"\nSCRIPT_DIR=$(dirname \"$SCRIPT_ABSOLUTE_PATH\")\nexport PYTHONUNBUFFERED=1\n\n# Check that needed downloads are available.\nmhc2flurry-downloads path data_published\nmhc2flurry-downloads path data_iedb\nmhc2flurry-downloads path data_proteomes\n\nmkdir -p \"$SCRATCH_DIR\"\nrm -rf \"$SCRATCH_DIR/$DOWNLOAD_NAME\"\nmkdir \"$SCRATCH_DIR/$DOWNLOAD_NAME\"\n\n# Send stdout and stderr to a logfile included with the archive.\nexec > >(tee -ia \"$SCRATCH_DIR/$DOWNLOAD_NAME/LOG.txt\")\nexec 2> >(tee -ia \"$SCRATCH_DIR/$DOWNLOAD_NAME/LOG.txt\" >&2)\n\n# Log some environment info\ndate\npip freeze\ngit status\nmhc2flurry-downloads info\n\n\ncd $SCRATCH_DIR/$DOWNLOAD_NAME\n\ncp $SCRIPT_DIR/curate_mhc_ligands.py .\ncp $SCRIPT_DIR/curate_t_cell_epitopes.py .\ncp $SCRIPT_DIR/curate_ms_by_pmid.py .\ncp $SCRIPT_DIR/annotate_proteins.py .\n\n# Curate IEDB T cell epitopes\ntime python curate_t_cell_epitopes.py \\\n --data-iedb \"$(mhc2flurry-downloads path data_iedb)/tcell_full_v3.csv.bz2\" \\\n --out-csv \"$(pwd)/t_cell_epitopes.csv\"\n\n\nMS_DIR=\"$(mhc2flurry-downloads path data_published)/ms\"\ncp -r \"$MS_DIR\" .\n\nEXPRESSION_DIR=\"$(mhc2flurry-downloads path data_published)/expression\"\ncp -r \"$EXPRESSION_DIR\" .\n\nCURATE_BY_PMID_ARGS=\"\"\nfor pmid in $(ls ms)\ndo\n CURATE_BY_PMID_ARGS+=$(echo --ms-item $pmid ms/$pmid/* ' ')\ndone\nfor item in $(ls expression)\ndo\n CURATE_BY_PMID_ARGS+=$(echo --expression-item $item expression/$item/* ' ')\ndone\n\ntime python curate_ms_by_pmid.py $CURATE_BY_PMID_ARGS \\\n --ms-out ms.by_pmid.csv \\\n --expression-out rna_expression.csv \\\n --expression-metadata-out rna_expression.metadata.csv\n\nrm -rf ms\n\ntime python curate_mhc_ligands.py \\\n --data-iedb \\\n \"$(mhc2flurry-downloads path data_iedb)/mhc_ligand_full.csv.bz2\" \\\n --data-additional-ms \"$(pwd)/ms.by_pmid.csv\" \\\n --out-csv curated_training_data.csv \\\n --out-affinity-csv curated_training_data.affinity.csv \\\n --out-mass-spec-csv curated_training_data.mass_spec.csv\n\ntime python curate_mhc_ligands.py \\\n --data-iedb \\\n \"$(mhc2flurry-downloads path data_iedb)/mhc_ligand_full.csv.bz2\" \\\n --out-csv curated_training_data.no_additional_ms.csv\n\n# Annotate human proteins\ntime python annotate_proteins.py \\\n \"$(mhc2flurry-downloads path data_proteomes)/human.uniprot.isoforms.fasta.gz\" \\\n --annotate \"$(pwd)/ms.by_pmid.csv\" - \\\n --annotate \"$(pwd)/curated_training_data.csv\" - \\\n --annotate \"$(pwd)/curated_training_data.mass_spec.csv\" - \\\n --annotate \"$(pwd)/curated_training_data.no_additional_ms.csv\" - \\\n --annotate \"$(pwd)/t_cell_epitopes.csv\" - \\\n --fm-index-suffix .fm \\\n --protein-column proteins_human\n\n# Annotate mouse proteins\ntime python annotate_proteins.py \\\n \"$(mhc2flurry-downloads path data_proteomes)/mouse.uniprot.isoforms.fasta.gz\" \\\n --annotate \"$(pwd)/ms.by_pmid.csv\" - \\\n --annotate \"$(pwd)/curated_training_data.csv\" - \\\n --annotate \"$(pwd)/curated_training_data.mass_spec.csv\" - \\\n --annotate \"$(pwd)/curated_training_data.no_additional_ms.csv\" - \\\n --annotate \"$(pwd)/t_cell_epitopes.csv\" - \\\n --fm-index-suffix .fm \\\n --protein-column proteins_mouse\n\n# Annotate viral proteins\ntime python annotate_proteins.py \\\n \"$(mhc2flurry-downloads path data_proteomes)/viral.uniprot.fasta.gz\" \\\n --annotate \"$(pwd)/ms.by_pmid.csv\" - \\\n --annotate \"$(pwd)/curated_training_data.csv\" - \\\n --annotate \"$(pwd)/curated_training_data.mass_spec.csv\" - \\\n --annotate \"$(pwd)/curated_training_data.no_additional_ms.csv\" - \\\n --annotate \"$(pwd)/t_cell_epitopes.csv\" - \\\n --fm-index-suffix .fm \\\n --protein-column proteins_viral\n\n\nfor i in $(ls *.csv)\ndo\n bzip2 $i\ndone\n\ncp $SCRIPT_ABSOLUTE_PATH .\nbzip2 LOG.txt\nRESULT=\"$SCRATCH_DIR/${DOWNLOAD_NAME}.$(date +%Y%m%d).tar.bz2\"\ntar -cjf \"$RESULT\" *\necho \"Created archive: $RESULT\"\n" }, { "alpha_fraction": 0.6993243098258972, "alphanum_fraction": 0.7195945978164673, "avg_line_length": 20.14285659790039, "blob_id": "2cb4872846a2c4433d19b297d0306e50f6a314a7", "content_id": "08c532a6055f8da05ab85cf663695e6a8faa5060", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 296, "license_type": "permissive", "max_line_length": 63, "num_lines": 14, "path": "/mhc2flurry/__init__.py", "repo_name": "luoyuan3316/mhc2flurry", "src_encoding": "UTF-8", "text": "\"\"\"\nClass II MHC ligand prediction package\n\"\"\"\n\n#from .class2_affinity_predictor import Class2AffinityPredictor\n#from .class2_neural_network import Class2NeuralNetwork\n\nfrom .version import __version__\n\n__all__ = [\n \"__version__\",\n# \"Class2AffinityPredictor\",\n# \"Class2NeuralNetwork\",\n]\n" } ]
27
sunjinghua/gabor_sift_bovw
https://github.com/sunjinghua/gabor_sift_bovw
8c2d45f3bc7055f91cbaa5239448dfa9367f4af3
12d54f34226ec448f2e6f0fbc7c9a10052527368
8ae4f6719eb4df2555901e41dcfea6b86fd441ad
refs/heads/master
2022-01-24T03:14:51.780787
2019-07-20T08:32:55
2019-07-20T08:32:55
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5830701589584351, "alphanum_fraction": 0.5931017398834229, "avg_line_length": 39.407691955566406, "blob_id": "4a3b2df000c2c36bb83e40f2c7fdd973f856a53b", "content_id": "3d8865347a0963054a6c2f06e598e9cea0fd009f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16149, "license_type": "permissive", "max_line_length": 138, "num_lines": 390, "path": "/assignment1.py", "repo_name": "sunjinghua/gabor_sift_bovw", "src_encoding": "UTF-8", "text": "import numpy as np\r\nimport cv2\r\nimport os\r\nfrom scipy import ndimage\r\nfrom scipy.spatial import distance\r\nfrom sklearn.cluster import KMeans\r\n\r\n# takes two arrays as parameters and find the l1 distance\r\ndef L1_dist(vec1, vec2):\r\n return np.linalg.norm(np.subtract(np.array(vec1), np.array(vec2))) \r\n#This makes concatanetion of the images and wirte them\r\ndef images_print(images, feature_vectors, test_vectors, test):\r\n loop_num = 0\r\n samples_name = [\"iris\", \"teapot\", \"elk\"]\r\n for i in samples_name:\r\n cv2.imwrite(str(i)+\".png\", test[i][4])\r\n closest_images = closests(feature_vectors, test_vectors[i][4])\r\n x = []\r\n for ind in range(len(closest_images)):\r\n x.append(cv2.resize(images[closest_images[ind][0]][closest_images[ind][1]],(250,250))) \r\n img_concatanete = np.concatenate((x[0],x[1],x[2],x[3],x[4]),axis=1)\r\n cv2.imwrite('the_closest_images_to_'+ str(i)+\".png\",img_concatanete)\r\n\r\n# Returns the most 5 similar categories. \r\n# Takes 2 parameters image dictionary and test data\r\ndef closests(images, test):\r\n img = [[\"\", 0], [\"\", 0], [\"\",0], [\"\",0], [\"\",0]]\r\n dist = [np.inf, np.inf, np.inf, np.inf, np.inf]\r\n \r\n for key, value in images.items():\r\n for ind in range(len(value)):\r\n dist_val = distance.euclidean(test, value[ind])\r\n #dist_val = L1_dist(test, value[ind])\r\n for i in range(len(dist)):\r\n if(dist_val < dist[i]):\r\n dist[i] = dist_val\r\n img[i][0] = key\r\n img[i][1] = ind\r\n break\r\n return img\r\n\r\n# Takes 2 parameters. The first one is a dictionary that holds the descriptors that are separated class by class \r\n# And the second parameter is an array that holds the central points (visual words) of the k means clustering\r\n# Returns a dictionary that holds the histograms for each tiles of the images that are separated class by class. \r\ndef image_class_tiling(all_bovw, centers):\r\n dict_feature = {}\r\n for key,value in all_bovw.items():\r\n category = []\r\n for img in value:\r\n tiles_hist = []\r\n for val in img:\r\n histogram = np.zeros(len(centers))\r\n for each_feature in val:\r\n ind = find_index(each_feature, centers)\r\n histogram[ind] += 1\r\n \r\n \r\n tiles_hist.extend(histogram)\r\n category.append(histogram)\r\n dict_feature[key] = category\r\n return dict_feature\r\n\r\n# Creates descriptors using sift library for each tile\r\n# Takes one parameter that is images dictionary that holds the tiles not the pictures itselves\r\n# Return an array whose first index holds the decriptor_list without an order\r\n# And the second index holds the sift_vectors dictionary which holds the descriptors but this is seperated class by class\r\ndef sift_features_tiling(images):\r\n sift_vectors = {}\r\n descriptor_list = []\r\n sift = cv2.xfeatures2d.SIFT_create()\r\n for key,value in images.items():\r\n features = []\r\n for img in value:\r\n tiling = []\r\n for tile in img:\r\n \r\n kp, des = sift.detectAndCompute(tile,None)\r\n if(len(kp)>=1):\r\n\r\n descriptor_list.extend(des)\r\n\r\n tiling.append(des)\r\n features.append(tiling)\r\n sift_vectors[key] = features\r\n return [descriptor_list, sift_vectors]\r\n\r\n# Helps the tiling function which finds one of the multipliers of the k value.\r\n# Takes the k values as a parameter\r\n# Returns the one of the multipliers of the k value. \r\ndef find_multiplier(num):\r\n multiplier = 0\r\n if(num > 50):\r\n for i in range(10,50):\r\n if(num % i == 0):\r\n multiplier = i\r\n return multiplier\r\n else:\r\n for i in range(1,20):\r\n if(num % i == 0):\r\n multiplier = i\r\n return multiplier\r\n return multiplier\r\n\r\n# split the image k pieces.\r\n# Takes images dictionary and number of pieces\r\n# Return a dictionary that holds the tiles of the images which are seperated class by class\r\ndef tiling(images, k):\r\n images_tiling = {}\r\n for key,value in images.items():\r\n image_cat = []\r\n for img in value:\r\n image = []\r\n \r\n width = img.shape[1]\r\n height = img.shape[0]\r\n \r\n multiplier_width = find_multiplier(k)\r\n if(multiplier_width != 0):\r\n multiplier_height = int(k / multiplier_width)\r\n width_step = int(np.floor(width / multiplier_width))\r\n height_step = int(np.floor(height / multiplier_height))\r\n start_width = 0\r\n end_width = width_step\r\n start_height = 0\r\n end_height = height_step\r\n for step_width in range(multiplier_width):\r\n for step_height in range(multiplier_height):\r\n tile = img[start_height:end_height,start_width:end_width]\r\n image.append(tile)\r\n start_height = end_height\r\n end_height = start_height + height_step\r\n start_width = end_width\r\n end_width = start_width + width_step\r\n start_height = 0\r\n end_height = height_step\r\n\r\n\r\n else:\r\n resized = cv2.resize(img, (k, height), interpolation = cv2.INTER_AREA)\r\n width_step = 1\r\n start = 0\r\n end = width_step\r\n for step in range(k):\r\n tile = resized[0:height,start:end]\r\n start = end\r\n end = start + width_step\r\n image.append(tile)\r\n image_cat.append(image)\r\n images_tiling[key] = image_cat\r\n return images_tiling\r\n\r\n\r\n\r\n# Find the index of the closest central point to the each sift descriptor. \r\n# Takes 2 parameters the first one is a sift descriptor and the second one is the array of central points in k means\r\n# Returns the index of the closest central point. \r\ndef find_index(image, center):\r\n count = 0\r\n ind = 0\r\n for i in range(len(center)):\r\n if(i == 0):\r\n count = distance.euclidean(image, center[i]) \r\n #count = L1_dist(image, center[i])\r\n else:\r\n dist = distance.euclidean(image, center[i]) \r\n #dist = L1_dist(image, center[i])\r\n if(dist < count):\r\n ind = i\r\n count = dist\r\n return ind\r\n\r\n# Takes 2 parameters. The first one is a dictionary that holds the descriptors that are separated class by class \r\n# And the second parameter is an array that holds the central points (visual words) of the k means clustering\r\n# Returns a dictionary that holds the histograms for each images that are separated class by class. \r\ndef image_class(all_bovw, centers):\r\n dict_feature = {}\r\n for key,value in all_bovw.items():\r\n category = []\r\n for img in value:\r\n histogram = np.zeros(len(centers))\r\n for each_feature in img:\r\n ind = find_index(each_feature, centers)\r\n histogram[ind] += 1\r\n category.append(histogram)\r\n dict_feature[key] = category\r\n return dict_feature\r\n\r\n# A k-means clustering algorithm who takes 2 parameter which is number of cluster(k) and the other is descriptors list(unordered 1d array)\r\n# Returns an array that holds central points.\r\ndef kmeans(k, descriptor_list):\r\n kmeans = KMeans(n_clusters = k, n_init=10)\r\n kmeans.fit(descriptor_list)\r\n visual_words = kmeans.cluster_centers_ \r\n return visual_words\r\n\r\n# Creates descriptors using sift library\r\n# Takes one parameter that is images dictionary\r\n# Return an array whose first index holds the decriptor_list without an order\r\n# And the second index holds the sift_vectors dictionary which holds the descriptors but this is seperated class by class\r\ndef sift_features(images):\r\n sift_vectors = {}\r\n descriptor_list = []\r\n sift = cv2.xfeatures2d.SIFT_create()\r\n for key,value in images.items():\r\n features = []\r\n for img in value:\r\n kp, des = sift.detectAndCompute(img,None)\r\n \r\n \r\n descriptor_list.extend(des)\r\n features.append(des)\r\n sift_vectors[key] = features\r\n return [descriptor_list, sift_vectors]\r\n\r\n# Create the sift feature vectors(1X128) for each image.\r\n# Takes images as a parameter. It is the dictionary of images (class by class) whose features should be extracted\r\n# Return a dictianory that holds the features class by class\r\ndef sift_filters(images):\r\n sift_vectors = {}\r\n sift = cv2.xfeatures2d.SIFT_create()\r\n for key,value in images.items():\r\n features = []\r\n for img in value:\r\n kp, des = sift.detectAndCompute(img,None)\r\n features.append(des.mean(0)) # take the average and 1x128 matrix we get\r\n sift_vectors[key] = features\r\n return sift_vectors\r\n\r\n# Calculates the average accuracy and class based accuracies. \r\ndef accuracy(results):\r\n avg_accuracy = (results[1] / results[0]) * 100\r\n print(\"Average accuracy: %\" + str(avg_accuracy))\r\n print(\"\\nClass based accuracies: \\n\")\r\n for key,value in results[2].items():\r\n acc = (value[0] / value[1]) * 100\r\n print(key + \" : %\" + str(acc))\r\n\r\n# 1-NN algorithm. We use this for predict the class of test images.\r\n# Takes 2 parameters. images is the feature vectors of train images and tests is the feature vectors of test images\r\n# Returns an array that holds number of test images, number of correctly predicted images and records of class based images respectively\r\ndef knn(images, tests):\r\n num_test = 0\r\n correct_predict = 0\r\n class_based = {}\r\n \r\n for test_key, test_val in tests.items():\r\n class_based[test_key] = [0, 0] # [correct, all]\r\n for tst in test_val:\r\n predict_start = 0\r\n #print(test_key)\r\n minimum = 0\r\n key = \"a\" #predicted\r\n for train_key, train_val in images.items():\r\n for train in train_val:\r\n if(predict_start == 0):\r\n minimum = distance.euclidean(tst, train)\r\n #minimum = L1_dist(tst,train)\r\n key = train_key\r\n predict_start += 1\r\n else:\r\n dist = distance.euclidean(tst, train)\r\n #dist = L1_dist(tst,train)\r\n if(dist < minimum):\r\n minimum = dist\r\n key = train_key\r\n \r\n if(test_key == key):\r\n correct_predict += 1\r\n class_based[test_key][0] += 1\r\n num_test += 1\r\n class_based[test_key][1] += 1\r\n #print(minimum)\r\n return [num_test, correct_predict, class_based] \r\n\r\n# Creates the gabor feature vectors.\r\n# Takes images and filters as parameters. images holds the train images and filters holds the all filters\r\n# Returns the feature vectors that is an array\r\ndef gabor_feature_vector(images, filters):\r\n feature_vectors = {}\r\n for key,value in images.items():\r\n feature = []\r\n for img in value: \r\n means = process(img, filters)\r\n \r\n minimum = min(means)\r\n maximum = max(means)\r\n for score in range(len(means)):\r\n means[score] = (means[score] - minimum) / (maximum - minimum)\r\n feature.append(means)\r\n \r\n feature_vectors[key] = feature\r\n return feature_vectors\r\n \r\n# Makes convolution and take its mean. \r\n# Takes one image and all filters as parameters.\r\n# Returns the mean that is feature vector\r\ndef process(img, filters):\r\n means = []\r\n for flt in filters:\r\n filtered_image = ndimage.convolve(img, flt)\r\n mean = np.mean(filtered_image)\r\n means.append(mean)\r\n return means\r\n\r\n# takes all images and convert them to grayscale. \r\n# return a dictionary that holds all images category by category. \r\ndef load_images_from_folder(folder):\r\n images = {}\r\n for filename in os.listdir(folder):\r\n category = []\r\n path = folder + \"/\" + filename\r\n for cat in os.listdir(path):\r\n img = cv2.imread(path + \"/\" + cat,0)\r\n #img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n if img is not None:\r\n category.append(img)\r\n images[filename] = category\r\n return images\r\n\r\n# This function produces 40 differenet gabor filters. It takes no parameter.\r\n# Returns the filters that is a array holds each filter.\r\ndef build_filters():\r\n count = 0\r\n filters = []\r\n for theta in range(90):\r\n kern = cv2.getGaborKernel((3, 3), 8.0, count, 13.0, 0.9, 0, ktype=cv2.CV_32F)\r\n count += 2\r\n filters.append(kern)\r\n return filters\r\n\r\ndef main():\r\n \r\n images = load_images_from_folder('dataset/train') # take all images category by category \r\n test = load_images_from_folder(\"dataset/query\") # take test images \r\n \r\n \r\n ## gabor filter ##\r\n \r\n filters = build_filters() # take the all filters\r\n feature_vectors = gabor_feature_vector(images, filters) # create feature vectors for train dataset \r\n test_vectors = gabor_feature_vector(test,filters) #create feature vectors for test dataset\r\n results = knn(feature_vectors, test_vectors) # call the knn function\r\n accuracy(results) # calculates the accuracies and write the results to the console.\r\n images_print(images, feature_vectors, test_vectors, test)\r\n \r\n ## gabor filter end ##\r\n \r\n ## SIFT filter ##\r\n \r\n #sift_vectors = sift_filters(images) # extracts the sift vector fetaures for all train images\r\n #test_sift_vectors = sift_filters(test) # extracts the sift vector fetaures for all test images\r\n #results_sift = knn(sift_vectors, test_sift_vectors) # call the knn function\r\n #accuracy(results_sift) # calculates the accuracies and write the results to the console.\r\n #images_print(images, sift_vectors, test_sift_vectors, test)\r\n \r\n ## SIFT filter end ##\r\n \r\n ## Bag of Visual Words without spatial tiling ##\r\n \r\n \r\n #sifts = sift_features(images) \r\n #descriptor_list = sifts[0] # Takes the descriptor list which is unordered one\r\n #all_bovw_feature = sifts[1] # Takes the sift features that is seperated class by class for train data\r\n #visual_words = kmeans(150, descriptor_list) # Takes the central points which is visual words\r\n #bovw_train = image_class(all_bovw_feature, visual_words) # Creates histograms for train data\r\n #test_bovw_feature = sift_features(test)[1] # Takes the sift features that is seperated class by class for test data\r\n #bovw_test = image_class(test_bovw_feature, visual_words) # Creates histograms for test data\r\n #results_bowl = knn(bovw_train, bovw_test) # Call the knn function\r\n #accuracy(results_bowl) # Calculates the accuracies and write the results to the console.\r\n #images_print(images, bovw_train, bovw_test, test)\r\n \r\n ## Bag of Visual Words End ##\r\n \r\n ## Bag of Visual Words with spatial tiling ##\r\n \r\n #images_tiling = tiling(images,500)\r\n #test_tile = tiling(test, 500)\r\n #sifts_tile = sift_features_tiling(images_tiling)\r\n #descriptor_list_tile = sifts_tile[0]\r\n #all_bovw_feature_tile = sifts_tile[1]\r\n #visual_words = kmeans(150, descriptor_list_tile) \r\n #bovw_train = image_class_tiling(all_bovw_feature_tile, visual_words)\r\n #test_bovw_feature = sift_features_tiling(test_tile)[1]\r\n #bovw_test = image_class_tiling(test_bovw_feature, visual_words)\r\n #results_bowl = knn(bovw_train, bovw_test)\r\n #accuracy(results_bowl)\r\n #images_print(images, bovw_train, bovw_test, test)\r\n \r\n ## Bag of Visual Words End with spatial tiling End ##\r\nmain()\r\n" }, { "alpha_fraction": 0.762286365032196, "alphanum_fraction": 0.7673071622848511, "avg_line_length": 82.54917907714844, "blob_id": "a9c9fad215c9f93d648fc3c56448738919182d0a", "content_id": "579be4e61865f729cc057ede1ea2597c68fa841b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 10357, "license_type": "permissive", "max_line_length": 452, "num_lines": 122, "path": "/README.md", "repo_name": "sunjinghua/gabor_sift_bovw", "src_encoding": "UTF-8", "text": "## You can access the Dataset: https://drive.google.com/open?id=1PmeoRg3tbC_Cl94CYJ-1-gADmu77fYN0\r\n\r\n\r\n## Read my blog: https://medium.com/@aybukeyalcinerr/bag-of-visual-words-with-spatial-tiling-439d3663f7e2\r\n\r\n# How to run code\r\n\r\nTo compare the actual labels and predicted labels for query images, I separate the images class by class like in train dataset.\r\nTo run the code in spyder or pycharm, just put the dataset folder in the same location with python file. Then run the code. \r\n<br>\r\n# The organization of the code\r\n\r\nAfter I wrote all functions, I call all of them in the main function. To run the code, I just call the main() function. All\r\nother functions are called in main(). And I take the function in comment line, for example to see the accuracies for gabor filters\r\njust comment out the gabor filter functions and comment in the others. \r\n\r\n# Details of implementation\r\n\r\nNOT: I prefer to use dictionaries to separate class by class. All dictionaries are separated class by class.<br>\r\nimages = load_images_from_folder('dataset/train') # take all images category by category <br>\r\ntest = load_images_from_folder(\"dataset/query\") # take test images <br>\r\n\r\nIn the above code, just load the query images and train images into the dictionaries that are separated class by class\r\ndef load_images_from_folder(folder) => Takes the path of the folders as parameter and returns a dictionary.\r\n\r\n## Gabor filter bank\r\n\r\nTo see the effect of gabor filter bank; call the below functions in the main function respectively;\r\n\r\nfilters = build_filters() <br>\r\nfeature_vectors = gabor_feature_vector(images, filters) <br>\r\ntest_vectors = gabor_feature_vector(test,filters) <br>\r\nresults = knn(feature_vectors, test_vectors) <br>\r\naccuracy(results) <br>\r\n\r\nThe definition of the functions as follows:<br>\r\n\r\ndef build_filters() => Takes no parameter and returns the array of gabor filters with different orientations.<br>\r\ndef gabor_feature_vector(images, filters) => Takes train images dictionary and test images dictionary as parameter. And returns the dictionary of convolution between each filter and each image. To achieve these, it calls process() function in it.<br>\r\ndef process(img, filters) => Takes one image and array of gabor filters as parameters. Then takes the mean of the each convolved filtered_images then return the array of it.<br>\r\ndef knn(images, tests) => Takes feature vectors of train and test images that we get them using gabor_feature_vector() function. It is a classifying algorithm and the k value is 1 in this scenario. Return an array that holds number of images in query folder, number of images that we correctly predict the label and a dictionary that holds the number of coreectly predicted image and number of total images to calculate the class based accuracies.<br>\r\ndef accuracy(results) => Takes an array that return from knn(). Calculates the average and class based accuracies.\r\n<br>\r\n## SIFT feature vectors\r\n\r\nTo see the effect of SIFT feature vectors, call the below functions in the main function respectively;<br>\r\n\r\nsift_vectors = sift_filters(images) <br>\r\ntest_sift_vectors = sift_filters(test) <br>\r\nresults_sift = knn(sift_vectors, test_sift_vectors)<br>\r\naccuracy(results_sift) <br>\r\n\t\r\nThe definition of the functions as follows:<br>\r\n \r\ndef sift_filters(images) => Takes the dictionary of the images whose sift feature vectors should be extracted. Return a dictionary that holds the feature vectors of each image class by class<br>\r\ndef knn(images, tests) => Takes feature vectors of train and test images that we get them using sift_filter() function. It is a classifying algorithm and the k value is 1 in this scenario. Return an array that holds number of images in query folder, number of images that we correctly predict the label and a dictionary that holds the number of correctly predicted image and number of total images to calculate the class based accuracies.<br>\r\ndef accuracy(results) => Takes an array that return from knn(). Calculates the average and class based accuracies.<br>\r\n\t\r\n\t\r\n## Bag of Visual Words Without Spatial Tiling\r\n\r\nTo see the effect of bag of visual words, call the below functions in the main function respectively;<br>\r\n\r\nsifts = sift_features(images) <br>\r\ndescriptor_list = sifts[0] # Takes the descriptor list which is unordered one <br>\r\nall_bovw_feature = sifts[1] # Takes the sift features that is separated class by class for train data <br>\r\nvisual_words = kmeans(150, descriptor_list) # Takes the central points which is visual words <br>\r\nbovw_train = image_class(all_bovw_feature, visual_words) # Creates histograms for train data <br>\r\ntest_bovw_feature = sift_features(test)[1] # Takes the sift features that is separated class by class for test data <br>\r\nbovw_test = image_class(test_bovw_feature, visual_words) # Creates histograms for test data <br> \r\nresults_bowl = knn(bovw_train, bovw_test) # Call the knn function <br>\r\naccuracy(results_bowl) \t\r\n\t<br>\r\nThe definition of the functions as follows:<br>\r\n\r\ndef sift_features(images) => Takes just image dictionary and return an array whose first index holds the array of descriptor lists and the second one holds the dictionary of the descriptors but this time separated class by class<br>\r\ndef kmeans(k, descriptor_list) => Takes number of cluster and descriptor list as parameters and returns the central point of the clusters. This is just a clustering algorithm.<br>\r\ndef image_class(all_bovw, centers) => Takes the sift feature dictionary as parameter and the central points of the clusters that are visual words in this case. And returns a dictionary that holds histograms of the visual words for each image. To do that, it calls find_index() function. <br>\r\ndef find_index(image, center) => Find the index of the closest central point to the each sift descriptor. Takes one of the sift vector and visual words as parameter and returns the index of the closest visual word.<br>\r\ndef knn(images, tests) => Takes the histograms of train and test images that we get them using image_class() function. It is a classifying algorithm and the k value is 1 in this scenario. Return an array that holds number of images in query folder, number of images that we correctly predict the label and a dictionary that holds the number of correctly predicted image and number of total images to calculate the class based accuracies.<br>\r\ndef accuracy(results) => Takes an array that return from knn(). Calculates the average and class based accuracies.<br>\r\n\t\r\n## Bag of Visual Words With Spatial Tiling\r\n\r\nTo see the effect of bag of visual words with spatial tiling, call the below functions in the main function respectively;<br>\r\n\r\nimages_tiling = tiling(images,500)<br>\r\ntest_tile = tiling(test, 500)<br>\r\nsifts_tile = sift_features_tiling(images_tiling)<br>\r\ndescriptor_list_tile = sifts_tile[0]<br>\r\nall_bovw_feature_tile = sifts_tile[1]<br>\r\nvisual_words = kmeans(200, descriptor_list_tile) <br>\r\nbovw_train = image_class_tiling(all_bovw_feature_tile, visual_words)<br>\r\ntest_bovw_feature = sift_features_tiling(test_tile)[1]<br>\r\nbovw_test = image_class_tiling(test_bovw_feature, visual_words)<br>\r\nresults_bowl = knn(bovw_train, bovw_test)<br>\r\naccuracy(results_bowl)<br>\r\n\r\nThe definition of the functions as follows:<br>\r\n\r\ndef tiling(images, k) => Takes images dictionary and number of tiles as parameters. Then split each images into number of tiles then a dictionary that holds the tiles of the images which are separated class by class. In this function find_multiplier(num) is called. <br>\r\ndef find_multiplier(num) => Helps the tiling function to find out one of the multipliers of the number of tile. Takes number of tile as parameter. And returns one of the multipliers. <br>\r\ndef sift_features_tiling(images) => Creates descriptors using sift library for each tile. Takes one parameter that is images dictionary that holds the tiles not the pictures itselves.Return an array whose first index holds the decriptor_list without an order. And the second index holds the sift_vectors dictionary which holds the descriptors but this is separated class by class.<br>\r\ndef kmeans(k, descriptor_list) => Takes number of cluster and descriptor list as parameters and returns the central point of the clusters. This is just a clustering algorithm.<br>\r\ndef image_class_tiling(all_bovw, centers) => Takes 2 parameters. The first one is a dictionary that holds the descriptors that are separated class by class. And the second parameter is an array that holds the central points (visual words) of the k means clustering. Returns a dictionary that holds the histograms for each tiles of the images that are separated class by class. <br>\r\ndef knn(images, tests) => Takes the histograms of train and test images that we get them using image_class() function. It is a classifying algorithm and the k value is 1 in this scenario. Return an array that holds number of images in query folder, number of images that we correctly predict the label and a dictionary that holds the number of correctly predicted image and number of total images to calculate the class based accuracies.<br>\r\ndef accuracy(results) => Takes an array that return from knn(). Calculates the average and class based accuracies.<br>\r\n\r\n## Find the 5 most similar images from train dataset to the 3 images from 3 different class of query dataset.\r\n\r\nimages_print(images, feature_vectors, test_vectors, test) #for gabor filter bank<br>\r\nimages_print(images, sift_vectors, test_sift_vectors, test) #for sift feature vector<br>\r\nimages_print(images, bovw_train, bovw_test, test) #for bag of visual words with/without spatial tiling<br>\r\n\r\nThe definition of the images_print() as follows:<br>\r\n\r\ndef images_print(images, feature_vectors, test_vectors, test) => Takes image dictionary, 2 dictionaries that we pass to knn() and test dictionary as parameters respectively. Makes the concatenation of the 5 images and save them for each 3 different test image. Call closest() function. <br>\r\ndef closests(images, test) => Returns the 5 most similar categories and their index. Takes images dictionary and just one test image as parameters. \r\n<br>\r\n## BONUS : I used L1-Distance(Manhattan Distance) \r\n\r\ndef L1_dist(vec1, vec2) => Takes 2 vectors and return the distance between them\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" } ]
2
indrekots/py-challanges
https://github.com/indrekots/py-challanges
d581cf9bb0527fbbf15aaf7f3646faac8796b147
760c3d901e4f0162f0f3b2462d6733ef3204898b
10e6ef47a5391bcabc794598443f8a3fcd6ed4a1
refs/heads/master
2021-01-10T09:47:02.550353
2015-11-25T20:23:45
2015-11-25T20:23:45
46,884,349
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6496350169181824, "alphanum_fraction": 0.65450119972229, "avg_line_length": 24.5625, "blob_id": "5d78754ae9270c183bc73bb0f11f87639ecd32d0", "content_id": "10bd226a8d59e67ba60d272982d5c550e31f29e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 411, "license_type": "no_license", "max_line_length": 52, "num_lines": 16, "path": "/charswap/test_charswap.py", "repo_name": "indrekots/py-challanges", "src_encoding": "UTF-8", "text": "import unittest\nfrom charswap import charswap\n\nclass TestCharswap(unittest.TestCase):\n\n def test_input(self):\n self.assertEqual(charswap(\"hello\"), \"oellh\")\n\n def test_zero_length_input(self):\n self.assertEqual(charswap(\"\"), \"\")\n\n def test_single_char_input(self):\n self.assertEqual(charswap(\"a\"), \"a\")\n\n def test_number_input(self):\n self.assertEqual(charswap(3), \"3\")\n\n\n" }, { "alpha_fraction": 0.5552763938903809, "alphanum_fraction": 0.5653266310691833, "avg_line_length": 21.16666603088379, "blob_id": "32ddcdc429c2ddf06f32a25b2558893c1271a486", "content_id": "417b17ec22450fa17524dc21d50b2fd7f78b102b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 398, "license_type": "no_license", "max_line_length": 60, "num_lines": 18, "path": "/draw_sword/i_draw_my_sword.py", "repo_name": "indrekots/py-challanges", "src_encoding": "UTF-8", "text": "def i_draw_my_sword(hilt, blade, material):\n if hilt < 1 or blade < 1:\n return False\n else: return get_hilt(hilt) + get_blade(blade, material)\n\ndef get_hilt(length):\n hilt = \"O\"\n for i in range(0, length):\n hilt += \"=\"\n\n return hilt + \"||\"\n\ndef get_blade(length, material):\n blade = \"\"\n for i in range(0, length):\n blade += material\n\n return blade + \">\"" }, { "alpha_fraction": 0.44285714626312256, "alphanum_fraction": 0.47857141494750977, "avg_line_length": 22.5, "blob_id": "bd68be478ff7c80341c42663f2b39505c1ff311a", "content_id": "c27271566b9f72f69dcc30e58c75023729b511ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 140, "license_type": "no_license", "max_line_length": 49, "num_lines": 6, "path": "/charswap/charswap.py", "repo_name": "indrekots/py-challanges", "src_encoding": "UTF-8", "text": "def charswap(input):\n s = str(input)\n if len(str(s)) > 1:\n return s[len(s)-1] + s[1:len(s)-1] + s[0]\n else:\n return s" }, { "alpha_fraction": 0.6406844258308411, "alphanum_fraction": 0.6730037927627563, "avg_line_length": 31.9375, "blob_id": "82bad5f4b540ab0c905950a5a5a59d8b92331d55", "content_id": "13c1557f837f9a73eb512fe2267e22f0c9c2ee12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 526, "license_type": "no_license", "max_line_length": 82, "num_lines": 16, "path": "/dict_to_string/test_dictToString.py", "repo_name": "indrekots/py-challanges", "src_encoding": "UTF-8", "text": "import unittest\nfrom dictToString import dictToString\n\nclass TestDictToString(unittest.TestCase):\n\n def test_simple_dictionary(self):\n self.assertEqual(dictToString({'test1':1}), 'test1=1;')\n\n def test_with_none_value(self):\n self.assertEqual(dictToString({'test1':1, 'test2':None}), 'test1=1;')\n\n def test_longer_input(self):\n self.assertEqual(dictToString({'test1':1, 'test2':2}), 'test1=1;test2=2;')\n\n def test_one_none_value(self):\n self.assertEqual(dictToString({'test':None}), '')" }, { "alpha_fraction": 0.5058139562606812, "alphanum_fraction": 0.5058139562606812, "avg_line_length": 27.83333396911621, "blob_id": "33043f5bae80532baeadc49ff224bc6ef009f155", "content_id": "7f290352c8d7190e28bc62efbd80c0322c2de292", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 172, "license_type": "no_license", "max_line_length": 59, "num_lines": 6, "path": "/dict_to_string/dictToString.py", "repo_name": "indrekots/py-challanges", "src_encoding": "UTF-8", "text": "def dictToString(dict):\n result = ''\n for i in dict:\n if dict.get(i) is not None:\n result += str(i) + '=' + str(dict.get(i)) + ';'\n return result" } ]
5
geooooo/linux-labs-31pg
https://github.com/geooooo/linux-labs-31pg
6e8adcd028e3f762f90496b471f38aa72f7175e2
5b22ae4c271a02996779ef260b881dddf5175a7c
705895083c8566147c76d24a87d62edc5a431b83
refs/heads/master
2021-08-30T06:14:17.356963
2017-12-16T11:48:12
2017-12-16T11:48:12
111,319,844
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6675224900245667, "alphanum_fraction": 0.6752246618270874, "avg_line_length": 30.15999984741211, "blob_id": "0c032750f01eca8660b4bc3d8f69dd79ed5c5b57", "content_id": "5ea2200c2e03fa107979892b9eb788fbd1453445", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1140, "license_type": "no_license", "max_line_length": 66, "num_lines": 25, "path": "/lab-4/5.c", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#include <sys/types.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n\n\nint main(int argc, char *argv[], char *envp[])\n{\n /* Программа запускает команду \"cat 1.c\",\n которая должна вывести содержимое данного файла на экран.\n Для функции execle в качестве имени программы мы указываем\n ее полное имя с путем от корневого каталога /bin/cat\n (аргумент с индексом 0). Первое слово в командной\n строке должно совпадать с именем запускаемой программы.\n Второе слово в командной строке - это имя файла,\n содержимое которого распечатывается. */\n execlp(\"cat\", \"cat\", \"lab-4/1.c\", NULL);\n\n /* Это сообщение печатается только при возникновении ошибки */\n printf(\"Error on program start\\n \");\n exit(-1);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 17.75, "blob_id": "101a82281ab48d612e0bae65c671a4e44ae6c373", "content_id": "85f456a7e2a0241095a9c34874a4f37b8c0b7ae3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 212, "license_type": "no_license", "max_line_length": 46, "num_lines": 8, "path": "/lab-3/6.sh", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# Запрос и ввод имени файла в текущем каталоге\n# и вывод сообщения о типе файла.\n\necho \"Input file name:\"\nread fname\nfile $fname\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.692307710647583, "avg_line_length": 16.33333396911621, "blob_id": "192d00c37a8642f4b6b68970c7c5cae33ed06197", "content_id": "8e3d941c09ee4d34a2522568da765129aec00052", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 283, "license_type": "no_license", "max_line_length": 51, "num_lines": 12, "path": "/lab-3/1.sh", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# Вывод на экран списка параметров командной строки\n# с указанием номера каждого параметра.\n\necho \"0: $0\"\nnumber=1\nfor arg in $*\ndo\n echo \"$number: $arg\"\n let number=$number+1\ndone\n" }, { "alpha_fraction": 0.42912301421165466, "alphanum_fraction": 0.43849971890449524, "avg_line_length": 23.835617065429688, "blob_id": "a2f151a6a9c0398d2a994fad93280f405b33f0a4", "content_id": "9abf4a646a20a23580397a0852320d128b25b6db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1845, "license_type": "no_license", "max_line_length": 95, "num_lines": 73, "path": "/lab-5/2.c", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#include <sys/types.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\n#define IN 0\n#define OUT 1\n#define FOREVER 1\n#define FILE_NAME_LEN 32\n#define MSG_LEN 32\n\n\n\nint main(){\n int fd_pc[2];\n int fd_cp[2];\n int pid;\n char msg[MSG_LEN];\n char file_name[FILE_NAME_LEN];\n\n if (pipe(fd_pc) == -1) {\n printf(\"Ошибка pipe !\\n\");\n exit(EXIT_FAILURE);\n }\n\n if (pipe(fd_cp) == -1) {\n printf(\"Ошибка pipe !\\n\");\n exit(EXIT_FAILURE);\n }\n\n if ((pid = fork()) == -1) {\n printf(\"Ошибка fork !\\n\");\n exit(EXIT_FAILURE);\n }\n\n if (pid > 0) {\n close(fd_pc[IN]);\n close(fd_cp[OUT]);\n while (FOREVER) {\n printf(\"Input new file name: \");\n scanf(\"%s\", file_name);\n int file_name_len = strlen(file_name);\n write(fd_pc[OUT], file_name, file_name_len);\n if (file_name_len == 0) {\n printf(\"Bye !\\n\");\n break;\n }\n size_t size = read(fd_cp[IN], msg, MSG_LEN);\n printf(\"# %s\\n\", msg);\n }\n close(fd_pc[OUT]);\n close(fd_cp[IN]);\n } else {;\n // Дочерний\n while (FOREVER) {\n size_t size = read(fd_pc[IN], file_name, FILE_NAME_LEN);\n printf(\"%lu\\n%s\\n\", size, file_name);\n if (size == 0) {\n break;\n }\n switch (fork()) {\n case -1: printf(\"Ошибка fork !\\n\");\n exit(EXIT_FAILURE);\n case 0: write(fd_cp[OUT], \"Create new file...\", strlen(\"Create new file...\"));\n execlp(\"touch\", \"touch\", file_name, NULL);\n }\n }\n }\n\n return EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.4118811786174774, "alphanum_fraction": 0.420462042093277, "avg_line_length": 22.30769157409668, "blob_id": "95afc945da7137598c4b9275f05e1861c6717dab", "content_id": "6a1cc95b34ec29cf5ac9a7653fba92b38688c1d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1541, "license_type": "no_license", "max_line_length": 67, "num_lines": 65, "path": "/lab-5/1.c", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#include <sys/types.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\n#define IN 0\n#define OUT 1\n#define FOREVER 1\n#define FILE_NAME_LEN 32\n\n\n\nint main(){\n int fd[2];\n int pid;\n char file_name[FILE_NAME_LEN];\n\n if (pipe(fd) == -1) {\n printf(\"Ошибка pipe !\\n\");\n exit(EXIT_FAILURE);\n }\n\n if ((pid = fork()) == -1) {\n printf(\"Ошибка fork !\\n\");\n exit(EXIT_FAILURE);\n }\n\n if (pid > 0) {\n close(fd[IN]);\n while (FOREVER) {\n printf(\"Input new file name: \");\n scanf(\"%s\", file_name);\n int file_name_len = strlen(file_name);\n write(fd[OUT], file_name, file_name_len);\n if (file_name_len == 0) {\n printf(\"Bye !\\n\");\n break;\n }\n }\n close(fd[OUT]);\n } else {;\n // Дочерний\n close(fd[OUT]);\n while (FOREVER) {\n size_t size = read(fd[IN], file_name, FILE_NAME_LEN);\n printf(\"%lu\\n%s\\n\", size, file_name);\n if (size == 0) {\n break;\n }\n switch (fork()) {\n case -1: printf(\"Ошибка fork !\\n\");\n exit(EXIT_FAILURE);\n case 0: close(fd[IN]);\n close(fd[OUT]);\n execlp(\"touch\", \"touch\", file_name, NULL);\n }\n\n }\n close(fd[IN]);\n }\n\n return EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.5990415215492249, "alphanum_fraction": 0.6022364497184753, "avg_line_length": 12.911110877990723, "blob_id": "dab0291af2064857fea336b796baa9891cc8dbbb", "content_id": "783e6aeea7b98c187aac5b983b3ba204e528bb59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 632, "license_type": "no_license", "max_line_length": 46, "num_lines": 45, "path": "/lab-4/6.c", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#include <sys/types.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n\nvoid trigger_error(void);\nvoid child_function(void);\nvoid parent_function(void);\n\n\n\nint main()\n{\n switch (fork()) {\n case -1: trigger_error();\n case 0: child_function();\n default: parent_function();\n }\n\n return EXIT_SUCCESS;\n}\n\n\nvoid trigger_error(void)\n{\n printf(\"Ошибка !\\n\");\n exit(EXIT_FAILURE);\n}\n\n\n\nvoid child_function(void)\n{\n execlp(\"date\", \"date\", \"+%T\", NULL);\n exit(EXIT_SUCCESS);\n}\n\n\n\nvoid parent_function(void)\n{\n execlp(\"watch\", \"watch\", \"sensors\", NULL);\n exit(EXIT_SUCCESS);\n}\n" }, { "alpha_fraction": 0.7201492786407471, "alphanum_fraction": 0.7238805890083313, "avg_line_length": 23.363636016845703, "blob_id": "0b0e67b678920aad268e8b6f45c1f5a8194e4ada", "content_id": "2c1ad6b39fa0b8327e01a089e41936f4760bdef0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 397, "license_type": "no_license", "max_line_length": 78, "num_lines": 11, "path": "/lab-3/3.sh", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# Формирование файла со списком файлов в домашнем каталоге,\n# вывод на экран этого списка в алфавитном порядке и общего количества файлов.\n\nfname=\"res3.txt\"\nls ~ > $fname\n\ncat $fname | sort -fi\necho \"Количество файлов: \"\necho `cat $fname | wc -l`\n" }, { "alpha_fraction": 0.5174537897109985, "alphanum_fraction": 0.5379877090454102, "avg_line_length": 13.757575988769531, "blob_id": "626ff898796682deb9a380410ee4c70fa9cdb4fe", "content_id": "eee80d9a821ac99fbbc9123ec5b5e1c217309243", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 487, "license_type": "no_license", "max_line_length": 38, "num_lines": 33, "path": "/lab-5/5/reader.c", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <stdio.h>\n\n\n#define FOREVER 1\n#define BUF_LEN 32\n\n\n\nint main(){\n int fd;\n char name[] = \"aaa.fifo\";\n size_t size;\n char buf[BUF_LEN];\n\n (void)umask(0);\n mknod(name, S_IFIFO | 0666, 0);\n\n fd = open(name, O_RDONLY);\n\n while (FOREVER) {\n size = read(fd, buf, BUF_LEN);\n printf(\"%s\", buf);\n fflush(stdout);\n }\n\n close(fd);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5916542410850525, "alphanum_fraction": 0.5976154804229736, "avg_line_length": 12.979166984558105, "blob_id": "9715ebf2ab798f68c4ab8668a51fd656ec079a58", "content_id": "a61a3531ade36dcda7aa014f3377a8eb81d1e4b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 702, "license_type": "no_license", "max_line_length": 45, "num_lines": 48, "path": "/lab-4/3.c", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#include <sys/types.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n\nvoid trigger_error(void);\nvoid zombie_function(void);\nvoid parent_function(void);\n\n\n\nint main()\n{\n switch (fork()) {\n case -1: trigger_error();\n case 0: zombie_function();\n default: parent_function();\n }\n\n return EXIT_SUCCESS;\n}\n\n\nvoid trigger_error(void)\n{\n printf(\"Ошибка !\\n\");\n exit(EXIT_FAILURE);\n}\n\n\n\nvoid zombie_function(void)\n{\n printf(\"zombie %d ready :}\\n\", getpid());\n exit(EXIT_SUCCESS);\n}\n\n\n\nvoid parent_function(void)\n{\n // Убить из диспетчера задач или ctrl+C\n while (1) {\n sleep(1);\n }\n exit(EXIT_SUCCESS);\n}\n" }, { "alpha_fraction": 0.5574506521224976, "alphanum_fraction": 0.5736086368560791, "avg_line_length": 25.5238094329834, "blob_id": "705ae3f17f21c7f922b7464d5e18be6ac130bbb0", "content_id": "93a55797805bee9cf5966890a9863309d06a40bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1403, "license_type": "no_license", "max_line_length": 73, "num_lines": 42, "path": "/lab-5/4.c", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <stdio.h>\n\n\n\nint main(){\n int fd;\n int result;\n size_t size;\n char resstring[14];\n char name[] = \"aaa.fifo\";\n\n /* Права доступа файла FIFO должны соответствовать параметру mknod */\n (void)umask(0);\n mknod(name, S_IFIFO | 0666, 0); /* Создаем FIFO */\n\n result = fork(); /* Порождаем новый процесс */\n\n if (result > 0) {\n /* Родительский процесс. FIFO открываем на запись.*/\n fd = open(name, O_WRONLY);\n /* Запись в FIFO 14 байт */\n size = write(fd, \"Hello, world!\", 14);\n /*Закрываем входной поток данных. Родитель прекращает работу */\n close(fd);\n printf(\"Parent exit\\n\");}\n else {\n /* Порожденный процесс. Открываем FIFO на чтение.*/\n fd = open(name, O_RDONLY);\n /*Чтение из FIFO 14 байт в массив */\n size = read(fd, resstring, 14);\n /* Печатаем прочитанную строку */\n printf(\"%s\\n \", resstring);\n /* Закрываем входной поток и завершаем работу */\n close(fd);\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6182795763015747, "alphanum_fraction": 0.6182795763015747, "avg_line_length": 13.307692527770996, "blob_id": "7a9ea6bfe08cfe5e4542eeebb6a85002291f15a6", "content_id": "a1e51ffda602dcc1676636b346dfbccae4e37f43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 186, "license_type": "no_license", "max_line_length": 55, "num_lines": 13, "path": "/lab-4/1.c", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <unistd.h>\n\n\n\nint main(void)\n{\n printf(\"PID: %d\\nPPID: %d\\n\", getpid(), getppid());\n\n return EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.71875, "avg_line_length": 17.66666603088379, "blob_id": "bb376ccebe614e8c2f91bf6d6f44f2a13401be68", "content_id": "d42a0577941e6c404277a29985ed04ca30322b52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 308, "license_type": "no_license", "max_line_length": 56, "num_lines": 12, "path": "/lab-3/4.sh", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# Переход в другой каталог, формирование файла\n# с листингом каталога и возвращение в исходный каталог.\n\nsrc_path=`pwd`\ndst_path=\"./dir\"\nfname=\"$src_path/res4.txt\"\n\ncd $dst_path\nls > $fname\ncd $src_path\n" }, { "alpha_fraction": 0.5401069521903992, "alphanum_fraction": 0.6470588445663452, "avg_line_length": 16, "blob_id": "c99b5eeaecbee9b92392b54cdd30160145097835", "content_id": "6693a0af585e0f6c6af066a44f87fea8ea3c8657", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 256, "license_type": "no_license", "max_line_length": 60, "num_lines": 11, "path": "/lab-3/2.sh", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# Присвоение переменным А, В и С значений 10, 100 и 200,\n# вычисление и вывод результатов по формуле D=(A*2 + B/3)*C.\n\nA=10\nB=100\nC=200\nlet D=($A*2+$B/3)*$C\n\necho $D\n" }, { "alpha_fraction": 0.49714285135269165, "alphanum_fraction": 0.508571445941925, "avg_line_length": 16.5, "blob_id": "84bfbb5005ca80fafe222c7a064764fa342cdb59", "content_id": "f404906ebbb52d61478158b08139cee522426afe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 706, "license_type": "no_license", "max_line_length": 74, "num_lines": 40, "path": "/lab-5/3.c", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#include <sys/types.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\n#define IN 0\n#define OUT 1\n\n\n\nint main(){\n int fd[2];\n unsigned long long size;\n char* data = \"*\";\n int pid;\n\n if (pipe(fd) == -1) {\n printf(\"Ошибка pipe !\\n\");\n exit(EXIT_FAILURE);\n }\n\n pid = fork();\n\n if (pid == -1) {\n exit(EXIT_FAILURE);\n } else if (pid == 0) {\n ;\n } else {\n close(fd[IN]);\n for (size = 0; write(fd[OUT], data, 1); ++size) ;\n close(fd[OUT]);\n }\n\n printf(\"unsigned long long size = %lu\\n\", sizeof(unsigned long long));\n printf(\"Pipe size = %llu\\n\", size);\n\n return EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.6066452264785767, "alphanum_fraction": 0.6130760908126831, "avg_line_length": 19.282608032226562, "blob_id": "3c0bde3435806d0111de4c4203236d183940a85c", "content_id": "a29fec1865eac3142ad978af08836eb99b25e37b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1166, "license_type": "no_license", "max_line_length": 60, "num_lines": 46, "path": "/lab-6/wr_process.py", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "\"\"\"\n Задача \"Писатель - Читатель\"\n\"\"\"\n\n\nfrom multiprocessing import (\n Process,\n Queue\n)\n\n\n# Функция процесса - писателя\ndef writer(queue):\n print(\"Процесс-писатель готов !\")\n while True:\n if queue.full():\n continue\n try:\n number = int(input())\n queue.put(number)\n except ValueError:\n break\n print(\"Поток-писатель завершается !\")\n\n\n# Функция процесса - читателя\ndef reader(queue):\n print(\"Процесс-читатель готов !\")\n while True:\n if queue.empty():\n continue\n number = queue.get()\n print(\"{0} ** 2 == {1}\".format(number, number ** 2))\n\n\n# Создание канала связи для процессов\nqueue = Queue(10)\n\n# Запуск процесса - читателя\nprocess_reader = Process(target=reader, args=(queue, ))\nprocess_reader.start()\n\n# Работа процесса - писателя\nwriter(queue)\nprocess_reader.terminate()\nprint(\"Процесс-читатель завершается !\")\n" }, { "alpha_fraction": 0.5770609378814697, "alphanum_fraction": 0.5806451439857483, "avg_line_length": 16.4375, "blob_id": "7514bfc88680123bb12fa5985b6e06c6a1aa5c98", "content_id": "f93819da890bed36b2c37b7d3fbcbf1045ed71ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 342, "license_type": "no_license", "max_line_length": 39, "num_lines": 16, "path": "/lab-3/7.sh", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# Циклическое чтение системного времени\n# и очистка экрана в заданный момент.\n\nprev_date=\"\"\nwhile [ 1 ]\ndo\n cur_date=`date '+%T'`\n if [ \"$prev_date\" <> \"$cur_date\" ]\n then\n prev_date=$cur_date\n clear\n echo $cur_date\n fi\ndone\n" }, { "alpha_fraction": 0.6284152865409851, "alphanum_fraction": 0.6284152865409851, "avg_line_length": 13.076923370361328, "blob_id": "73d076d5a0ef1ec6e7e00aff3882743b8c3d4a36", "content_id": "6c025c55bbe12567dad37a844b4080ec5e247647", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 183, "license_type": "no_license", "max_line_length": 43, "num_lines": 13, "path": "/lab-4/4.c", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#include <sys/types.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n\n\nint main(int argc, char** argv, char** env)\n{\n execvp(\"env\", env);\n\n return EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.6948529481887817, "alphanum_fraction": 0.7095588445663452, "avg_line_length": 18.428571701049805, "blob_id": "a94fa5d2fe413b47eca0f34bc238791e1498a358", "content_id": "6d58900aa2be6b5c0beb86c004eb7f1e554097ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 372, "license_type": "no_license", "max_line_length": 66, "num_lines": 14, "path": "/lab-3/5.sh", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# Запрос и ввод имени пользователя, сравнение с текущим\n# логическим именем пользователя и вывод сообщения: верно/неверно.\n\nlogin2=\"v@sia\"\necho \"Input login:\"\nread login1\nif [ \"$login1\" = \"$login2\" ]\nthen\n echo \"SUCCESS\"\nelse\n echo \"FAILURE\"\nfi\n" }, { "alpha_fraction": 0.5488958954811096, "alphanum_fraction": 0.5552050471305847, "avg_line_length": 15.684210777282715, "blob_id": "d8b5f76374a3acd08793b202064a279df1eb6b5b", "content_id": "a4028b582951877dd77535db45411a5d22824139", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 397, "license_type": "no_license", "max_line_length": 58, "num_lines": 19, "path": "/lab-3/8.sh", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# Циклический просмотр списка файлов и\n# выдача сообщения при появлении заданного имени в списке.\n\necho \"Input file name:\"\nread fname\n\nwhile [ 1 ]\ndo\n for fn in `ls -a`\n do\n if [ \"$fn\" = \"$fname\" ]\n then\n echo \"I see !\"\n break 2\n fi\n done\ndone\n" }, { "alpha_fraction": 0.5588932633399963, "alphanum_fraction": 0.5636363625526428, "avg_line_length": 21.589284896850586, "blob_id": "98eff1c7367c61ee4018276b96cd68b800494a51", "content_id": "6f35d2a8c0c70316069693464451c4e9d2a18fec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1543, "license_type": "no_license", "max_line_length": 60, "num_lines": 56, "path": "/lab-6/wr_thread.py", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "\"\"\"\n Задача \"Писатель - Читатель\"\n\"\"\"\n\n\nfrom threading import Thread\nfrom buffer import Buffer\n\n\n# Функция потока - писатель\ndef writer(buffer):\n global is_terminate\n print(\"Поток-писатель готов !\")\n while True:\n # === Блокировка записи в буфер ===\n if buffer.is_full():\n continue\n # =================================\n try:\n number = int(input())\n buffer.add(number)\n except ValueError:\n is_terminate = True\n break\n print(\"Поток-писатель завершается !\")\n\n\n# Функция потока - читателя\ndef reader(buffer):\n global terminate\n print(\"Поток-читатель готов !\")\n while True:\n if is_terminate:\n break\n # === Блокировка чтения из буфера ===\n if buffer.is_empty():\n continue\n # =================================\n number = buffer.get()\n print(\"{0} ** 2 == {1}\".format(number, number ** 2))\n print(\"Поток-читатель завершается !\")\n\n\n# Общий буфер чисел\nbuffer = Buffer(10)\n\n# Признак завершения работы потока\nis_terminate = False\n\n# Запуск потока-читателя\nthread_reader = Thread(target=reader, args=(buffer, ))\nthread_reader.start()\n\n# Работа потока - писателя\nwriter(buffer)\nthread_reader.join()\n" }, { "alpha_fraction": 0.5191256999969482, "alphanum_fraction": 0.5264116525650024, "avg_line_length": 20.115385055541992, "blob_id": "6c555c8b6d46f0735c79b87b0907ced73fadd8b7", "content_id": "89e0263affe24f689597dfd95422affba660f61a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 574, "license_type": "no_license", "max_line_length": 47, "num_lines": 26, "path": "/lab-6/buffer.py", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "class Buffer:\n \"\"\"\n Буфер ограниченного размера\n \"\"\"\n\n def __init__(self, max_size):\n self._max_size = max_size\n self._cur_size = 0\n self._buffer = []\n\n def add(self, value):\n self._buffer.append(value)\n self._cur_size += 1\n\n def get(self):\n self._cur_size -= 1\n return self._buffer.pop()\n\n def is_full(self):\n return self._cur_size == self._max_size\n\n def is_empty(self):\n return self._cur_size == 0\n\n def print_buffer(self):\n print(self._buffer)\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5264550447463989, "avg_line_length": 12.034482955932617, "blob_id": "8dc1feae1fae7a9aedea4fa964882c22f1d4ee86", "content_id": "ab30cdb2ae473935d0d0e13a651aac76eb336c5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 378, "license_type": "no_license", "max_line_length": 35, "num_lines": 29, "path": "/lab-5/5/writer.c", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <stdio.h>\n\n\n#define FOREVER 1\n\n\n\nint main(){\n int fd;\n char name[] = \"aaa.fifo\";\n\n (void)umask(0);\n mknod(name, S_IFIFO | 0666, 0);\n\n fd = open(name, O_WRONLY);\n\n while (FOREVER) {\n sleep(1);\n write(fd, \"*\", 1);\n }\n\n close(fd);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.48923078179359436, "alphanum_fraction": 0.510769248008728, "avg_line_length": 13.1304349899292, "blob_id": "4c723437e4d1aa732bd1f7801edb3b79699f9bd5", "content_id": "a76b8d4427622800e3423eee42494e33b82d2115", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 325, "license_type": "no_license", "max_line_length": 56, "num_lines": 23, "path": "/lab-4/21.c", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "#include <sys/types.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n\n#define MAX_A 10\n#define DELAY 1\n\n\n\nint main()\n{\n pid_t pid = fork();\n\n for (int a = 0; a < MAX_A; a += (pid == 0)? 2 : 3) {\n sleep(DELAY);\n printf(\"%d \", a);\n fflush(stdout);\n }\n\n return EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.6083669066429138, "alphanum_fraction": 0.6118951439857483, "avg_line_length": 23.49382781982422, "blob_id": "7ba9780bc6b8ebcc866931b9558e06fa6f33fab6", "content_id": "bd2bef645762e1a92e5fd131ce593d12118a4560", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2525, "license_type": "no_license", "max_line_length": 78, "num_lines": 81, "path": "/lab-7/wr_thread.py", "repo_name": "geooooo/linux-labs-31pg", "src_encoding": "UTF-8", "text": "\"\"\"\n 2. Процесс писатель записывает содержимое некоторого файла.\n Процессы - читатели считывают данные, записанные процессом - писателем.\n Необходимо обеспечить взаимное исключение доступа\n к данным писателя и любого из читателей.\n Предполагаются следующие варианты задачи:\n * синхронизация с помощью семафоров\n * обмен данными через общую память\n * программные каналы или очереди.\n\"\"\"\n\n\nfrom threading import (\n Thread,\n Lock\n)\n\n\ndef reader(file_name, thread_number):\n global is_terminate\n global lock\n print(\"### Чтец {0} готов!\\n\".format(thread_number))\n with open(file_name, \"r\") as f:\n while True:\n if is_terminate:\n break\n with lock:\n line = f.readline().strip()\n if line == \"\":\n continue\n print(\">>> Чтец {0}: {1}\".format(thread_number, line.encode()))\n print(\"### Чтец {0} завершается!\\n\".format(thread_number))\n\n\ndef writer(file_name):\n global is_terminate\n global lock\n print(\"### Писатель готов!\\n\")\n with open(file_name, \"a\") as f:\n while True:\n try:\n line = input()\n with lock:\n f.write(line + \"\\n\")\n f.flush()\n except KeyboardInterrupt:\n is_terminate = True\n break\n print(\"### Писатель завершается!\\n\")\n\n\n# Файл для записи и чтения строк\nFILE_NAME = \"test.txt\"\n\n# Количество потоков-чтецов\nREADER_COUNT = 3\n\n\n# Признак завершения всех потоков\nis_terminate = False\n\n# Блокировка\nlock = Lock()\n\n\n# Создание файла\nopen(FILE_NAME, \"w\").close()\n\n\n# Создание потоков-чтецов\nthreads_reader_list = []\nfor i in range(READER_COUNT):\n threads_reader_list.append(Thread(target=reader, args=(FILE_NAME, i + 1)))\n threads_reader_list[i].start()\n\n# Начать процес записи\nwriter(FILE_NAME)\n\n# Ожидание завершения остальных потоков\nfor thread_reader in threads_reader_list:\n thread_reader.join()\n" } ]
24
LiJianfei06/tensorflow_projects
https://github.com/LiJianfei06/tensorflow_projects
ba72775494632943e1d0adea6d0c4333b4e2e31a
3e4e1b9aa5a5e21828bdababe0238258c7e3d5b4
624cff915c8a48a2a61adfc25de3c87350ce9844
refs/heads/master
2021-09-26T16:26:06.596237
2018-10-31T15:16:34
2018-10-31T15:16:34
108,412,897
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.5485670566558838, "alphanum_fraction": 0.5863307118415833, "avg_line_length": 36.583133697509766, "blob_id": "e83b3e6e3dd4b969ac34520df8fd416bc8cb50d6", "content_id": "9e3dbb0a74442c29dd7267bc8d594f1fe80f11a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17529, "license_type": "no_license", "max_line_length": 121, "num_lines": 415, "path": "/cifar10_tfrecord_ResNet/ResNet.py", "repo_name": "LiJianfei06/tensorflow_projects", "src_encoding": "UTF-8", "text": "# coding:UTF-8\n\"\"\"\n\nTypical use:\n\n from tensorflow.contrib.slim.nets import resnet_v2\n\nResNet-101 for image classification into 1000 classes:\n\n # inputs has shape [batch, 224, 224, 3]\n with slim.arg_scope(resnet_v2.resnet_arg_scope(is_training)):\n net, end_points = resnet_v2.resnet_v2_101(inputs, 1000)\n\nResNet-101 for semantic segmentation into 21 classes:\n\n # inputs has shape [batch, 513, 513, 3]\n with slim.arg_scope(resnet_v2.resnet_arg_scope(is_training)):\n net, end_points = resnet_v2.resnet_v2_101(inputs,\n 21,\n global_pool=False,\n output_stride=16)\n\"\"\"\nimport collections # 原生的collections库\nimport tensorflow as tf\nimport numpy as np\nimport sys\nfrom datetime import datetime\nimport math\nimport time\nfrom tensorflow.python.ops import init_ops\n\n\n\nslim = tf.contrib.slim # 使用方便的contrib.slim库来辅助创建ResNet\n\nFLAGS = tf.app.flags.FLAGS\n\n\n# 图像大小 \nIMAGE_WIDTH = 32\nIMAGE_HEIGHT = 32 \n\nclass Block(collections.namedtuple('Block', ['scope', 'unit_fn', 'args'])):\n '''\n 使用collections.namedtuple设计ResNet基本模块组的name tuple,并用它创建Block的类\n 只包含数据结构,不包含具体方法。\n 定义一个典型的Block,需要输入三个参数:\n scope:Block的名称\n unit_fn:ResNet V2中的残差学习单元 \n args:Block的args。\n '''\n\n\n\"\"\"\n shortcut\n 是否需要下采样\n\"\"\"\ndef subsample(inputs, stride, num_outputs,is_training=True,keep_prob=1.0,scope=None): \n if stride == 1: # 平常的shortcut\n return inputs\n else: # 下采样时的shortcut 用1x1卷积\n #return slim.max_pool2d(inputs, [1, 1], stride=stride, scope=scope)\n shortcut=slim.conv2d(inputs, num_outputs, 1, stride=stride,\n #normalizer_fn=None, activation_fn=None,\n padding='SAME', scope=scope)\n #shortcut = slim.dropout(shortcut, keep_prob)\n #return slim.batch_norm(shortcut, is_training=is_training,activation_fn=tf.nn.relu) \n return shortcut\n\n\n\n\"\"\"\n创建一个卷积层 \n\"\"\"\ndef conv2d_same(inputs, num_outputs, kernel_size, stride, scope=None): \n return slim.conv2d(inputs, num_outputs, kernel_size, stride=stride,padding='SAME', scope=scope)\n if stride == 1:\n return slim.conv2d(inputs, num_outputs, kernel_size, stride=1,\n padding='SAME', scope=scope)\n else: # 如果不为1,则显式的pad zero,pad zero总数为kernel_size - 1\n #kernel_size_effective = kernel_size + (kernel_size - 1) * (rate - 1)\n pad_total = kernel_size - 1\n pad_beg = pad_total // 2\n pad_end = pad_total - pad_beg\n inputs = tf.pad(inputs, # 对输入变量进行补零操作\n [[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]])\n return slim.conv2d(inputs, num_outputs, kernel_size, stride=stride,\n #normalizer_fn=None, activation_fn=None,\n padding='VALID', scope=scope)\n\n\n\"\"\"\n定义堆叠Blocks的函数 \n\"\"\"\[email protected]_arg_scope\ndef stack_blocks_dense(net, blocks,\n outputs_collections=None,is_training=True,keep_prob=1.0):\n \"\"\"\n Args:\n net: A `Tensor` of size [batch, height, width, channels].输入。\n blocks: 是之前定义的Block的class的列表。\n outputs_collections: 收集各个end_points的collections。\n\n Returns:\n net: Output tensor \n\n \"\"\"\n # 使用两层循环,逐个Residual Unit地堆叠\n for block in blocks: # 先使用两个tf.variable_scope将残差学习单元命名为block1/unit_1的形式\n #print \"block:\",block\n with tf.variable_scope(block.scope, 'block', [net]) as sc:\n for i, unit in enumerate(block.args):\n #print \"i:\",i\n #print \"unit:\",unit\n with tf.variable_scope('unit_%d' % (i + 1), values=[net]):\n # 在第2层循环中,我们拿到每个block中每个Residual Unit的args并展开为下面四个参数\n unit_depth, unit_depth_bottleneck, unit_stride = unit\n print unit_depth, unit_depth_bottleneck, unit_stride\n net = block.unit_fn(net, # 使用残差学习单元的生成函数顺序的创建并连接所有的残差学习单元\n depth=unit_depth,\n depth_bottleneck=unit_depth_bottleneck,\n stride=unit_stride,is_training=is_training,keep_prob=keep_prob)\n #print \"net:\",net\n net = slim.utils.collect_named_outputs(outputs_collections, sc.name, net) # 将输出net添加到collections中\n\n return net # 当所有block中的所有Residual Unit都堆叠完成之后,再返回最后的net作为stack_blocks_dense\n\n\n\n\n\n\"\"\"\n创建ResNet通用的arg_scope,arg_scope用来定义某些函数的参数默认值 \n\"\"\"\ndef resnet_arg_scope(is_training=True, # 训练标记\n weight_decay=5e-4, # 权重衰减速率\n batch_norm_decay=0.997, # BN的衰减速率\n batch_norm_epsilon=1e-5, # BN的epsilon默认1e-5\n batch_norm_scale=True): # BN的scale默认值\n\n batch_norm_params = { # 定义batch normalization(标准化)的参数字典\n 'is_training': is_training,\n 'decay': batch_norm_decay,\n 'epsilon': batch_norm_epsilon,\n 'scale': batch_norm_scale,\n 'updates_collections': tf.GraphKeys.UPDATE_OPS,\n }\n\n with slim.arg_scope( # 通过slim.arg_scope将[slim.conv2d]的几个默认参数设置好\n [slim.conv2d],\n weights_regularizer=slim.l2_regularizer(weight_decay), # 权重正则器设置为L2正则 \n weights_initializer=slim.xavier_initializer(), # 权重初始化器\n biases_initializer=init_ops.zeros_initializer(),\n biases_regularizer=None,\n activation_fn=tf.nn.relu, # 激活函数\n normalizer_fn=slim.batch_norm, # 标准化器设置为BN\n normalizer_params=batch_norm_params):\n with slim.arg_scope([slim.batch_norm], **batch_norm_params):\n with slim.arg_scope([slim.max_pool2d], padding='SAME') as arg_sc: # ResNet原论文是VALID模式,SAME模式可让特征对齐更简单\n return arg_sc # 最后将基层嵌套的arg_scope作为结果返回\n\n\[email protected]_arg_scope\ndef bottleneck1(inputs, depth, depth_bottleneck, stride,\n outputs_collections=None, scope=None,is_training=True,keep_prob=1.0):\n \"\"\"\n Args:\n inputs: A tensor of size [batch, height, width, channels].\n depth、depth_bottleneck:、stride三个参数是前面blocks类中的args\n rate: An integer, rate for atrous convolution.\n outputs_collections: 是收集end_points的collection\n scope: 是这个unit的名称。\n \"\"\"\n with tf.variable_scope(scope, 'bottleneck_v2', [inputs]) as sc: \n #depth_in = slim.utils.last_dimension(inputs.get_shape(), min_rank=4) # 可以限定最少为四个维度\n\n shortcut = subsample(inputs, stride,depth,is_training,keep_prob, 'shortcut')\n\n # 先是一个1*1尺寸,步长1,输出通道数为depth_bottleneck的卷积\n # 然后是3*3尺寸,步长为stride,输出通道数为depth_bottleneck的卷积\n residual = slim.conv2d(inputs, depth_bottleneck, 3, stride=stride,padding='SAME', scope='conv1')\n print \"residual:\",residual\n tf.summary.histogram('conv1', residual)\n\n # 最后是1*1卷积,步长1,输出通道数depth的卷积,得到最终的residual。最后一层没有正则项也没有激活函数\n residual = slim.conv2d(residual, depth, 3, stride=1,padding='SAME', scope='conv2')\n print \"residual:\",residual\n tf.summary.histogram('conv2', residual)\n\n output = shortcut + residual # 将降采样的结果和residual相加\n\n return slim.utils.collect_named_outputs(outputs_collections, # 将output添加进collection并返回output作为函数结果\n sc.name,\n output)\n \n\n\n########定义生成resnet_v2的主函数########\ndef resnet_v2(inputs, # A tensor of size [batch, height_in, width_in, channels].输入\n blocks, # 定义好的Block类的列表\n num_classes=None, # 最后输出的类数\n global_pool=True, # 是否加上最后的一层全局平均池化\n include_root_block=True, # 是否加上ResNet网络最前面通常使用的卷积和最大池化\n reuse=None, # 是否重用\n scope=None,# 整个网络的名称\n is_training=True,\n keep_prob=1.0): \n # 在函数体先定义好variable_scope和end_points_collection\n with tf.variable_scope(scope, 'resnet_v2', [inputs], reuse=reuse) as sc:\n end_points_collection = sc.original_name_scope + 'end_points' # 定义end_points_collection\n #sys.exit()\n with slim.arg_scope([slim.conv2d, bottleneck1, # bottleneck1bottleneck1bottleneck1bottleneck1\n stack_blocks_dense],\n outputs_collections=end_points_collection): # 将三个参数的outputs_collections默认设置为end_points_collection\n\n net = inputs\n #print \"net:\",net \n if include_root_block: # 根据标记值\n with slim.arg_scope([slim.conv2d],\n #activation_fn=None, normalizer_fn=None\n ):\n net = slim.conv2d(net, 16, 3, stride=1,padding='SAME', scope='conv1')\n \n net = stack_blocks_dense(net, blocks,is_training=is_training,keep_prob=keep_prob) # 将残差学习模块组生成好\n\n if global_pool: # 根据标记添加全局平均池化层\n net=slim.avg_pool2d(net, [np.shape(net)[1], np.shape(net)[2]], stride=1, scope='pool5')\n print 'Avg_pool:',net\n if num_classes is not None: # 是否有通道数\n net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, # 无激活函数和正则项\n #normalizer_fn=None,\n scope='logits') # 添加一个输出通道num_classes的1*1的卷积\n #net=slim.fully_connected(net, num_classes, weights_initializer=slim.xavier_initializer(),\n # activation_fn=None, # 无激活函数和正则项\n # normalizer_fn=None, scope='logits') # 添加一个输出通道num_classes的1*1的卷积\n net = tf.reshape(net, [-1, num_classes])\n end_points = slim.utils.convert_collection_to_dict(end_points_collection) # 将collection转化为python的dict\n if num_classes is not None:\n end_points['predictions'] = slim.softmax(net, scope='predictions') # 输出网络结果\n print \"net:\",net\n print \"end_points['predictions']:\",end_points['predictions']\n return net, end_points\n#------------------------------ResNet的生成函数定义好了----------------------------------------\n \n\n\n\n\"\"\"\n ResNet-20 \n for cifar10\n\"\"\"\ndef resnet_20(inputs, # 图像尺寸缩小了32倍\n num_classes=None,\n global_pool=True,\n reuse=None, # 是否重用\n is_training=True,\n keep_prob=1.0,\n scope='resnet_v2_5_ljf'):\n\n blocks = [\n Block('block1', bottleneck1, [(16, 16, 1)] * 1 + [(16, 16, 1)]*2), # (输入通道数,输出通道数,stride)\n Block('block2', bottleneck1, [(32, 32, 2)] * 1 + [(32, 32, 1)]*2),\n Block('block3', bottleneck1, [(64, 64, 2)] * 1 + [(64, 64, 1)]*2),\n ]\n #print \"blocks:\",blocks\n return resnet_v2(inputs, blocks, num_classes, global_pool,\n include_root_block=True, reuse=reuse, scope=scope,is_training=is_training,keep_prob=keep_prob)\n\n\n\n#def resnet_v2_50(inputs, # 图像尺寸缩小了32倍\n# num_classes=None,\n# global_pool=True,\n# reuse=None, # 是否重用\n# is_training=True,\n# scope='resnet_v2_50'):\n# blocks = [\n# Block('block1', bottleneck, [(256, 64, 1)] * 2 + [(256, 64, 2)]),\n#\n#\n#\n# # Args::\n# # 'block1':Block名称(或scope)\n# # bottleneck:ResNet V2残差学习单元\n# # [(256, 64, 1)] * 2 + [(256, 64, 2)]:Block的Args,Args是一个列表。其中每个元素都对应一个bottleneck\n# # 前两个元素都是(256, 64, 1),最后一个是(256, 64, 2)。每个元素\n# # 都是一个三元tuple,即(depth,depth_bottleneck,stride)。\n# # (256, 64, 3)代表构建的bottleneck残差学习单元(每个残差学习单元包含三个卷积层)中,第三层输出通道数\n# # depth为256,前两层输出通道数depth_bottleneck为64,且中间那层步长3。这个残差学习单元结构为:\n# # [(1*1/s1,64),(3*3/s2,64),(1*1/s1,256)]\n#\n#\n#\n# Block(\n# 'block2', bottleneck, [(512, 128, 1)] * 3 + [(512, 128, 2)]),\n# Block(\n# 'block3', bottleneck, [(1024, 256, 1)] * 5 + [(1024, 256, 2)]),\n# Block(\n# 'block4', bottleneck, [(2048, 512, 1)] * 3)]\n# #print \"blocks:\",blocks\n# return resnet_v2(inputs, blocks, num_classes, global_pool,\n# include_root_block=True, reuse=reuse, scope=scope,is_training=is_training)\n#\n#\n#def resnet_v2_101(inputs, # unit提升的主要场所是block3\n# num_classes=None,\n# global_pool=True,\n# reuse=None,\n# scope='resnet_v2_101'):\n# \"\"\"ResNet-101 model of [1]. See resnet_v2() for arg and return description.\"\"\"\n# blocks = [\n# Block(\n# 'block1', bottleneck, [(256, 64, 1)] * 2 + [(256, 64, 2)]),\n# Block(\n# 'block2', bottleneck, [(512, 128, 1)] * 3 + [(512, 128, 2)]),\n# Block(\n# 'block3', bottleneck, [(1024, 256, 1)] * 22 + [(1024, 256, 2)]),\n# Block(\n# 'block4', bottleneck, [(2048, 512, 1)] * 3)]\n# return resnet_v2(inputs, blocks, num_classes, global_pool,\n# include_root_block=False, reuse=reuse, scope=scope)\n#\n#\n#def resnet_v2_152(inputs, # unit提升的主要场所是block3\n# num_classes=None,\n# global_pool=True,\n# reuse=None,\n# scope='resnet_v2_152'):\n# \"\"\"ResNet-152 model of [1]. See resnet_v2() for arg and return description.\"\"\"\n# blocks = [\n# Block(\n# 'block1', bottleneck, [(256, 64, 1)] * 2 + [(256, 64, 2)]),\n# Block(\n# 'block2', bottleneck, [(512, 128, 1)] * 7 + [(512, 128, 2)]),\n# Block(\n# 'block3', bottleneck, [(1024, 256, 1)] * 35 + [(1024, 256, 2)]),\n# Block(\n# 'block4', bottleneck, [(2048, 512, 1)] * 3)]\n# return resnet_v2(inputs, blocks, num_classes, global_pool,\n# include_root_block=True, reuse=reuse, scope=scope)\n#\n#\n#def resnet_v2_200(inputs, # unit提升的主要场所是block2\n# num_classes=None,\n# global_pool=True,\n# reuse=None,\n# scope='resnet_v2_200'):\n# \"\"\"ResNet-200 model of [2]. See resnet_v2() for arg and return description.\"\"\"\n# blocks = [\n# Block(\n# 'block1', bottleneck, [(256, 64, 1)] * 2 + [(256, 64, 2)]),\n# Block(\n# 'block2', bottleneck, [(512, 128, 1)] * 23 + [(512, 128, 2)]),\n# Block(\n# 'block3', bottleneck, [(1024, 256, 1)] * 35 + [(1024, 256, 2)]),\n# Block(\n# 'block4', bottleneck, [(2048, 512, 1)] * 3)]\n# return resnet_v2(inputs, blocks, num_classes, global_pool,\n# include_root_block=True, reuse=reuse, scope=scope)\n#\n#\n\n\n\n\n#-------------------评测函数---------------------------------\n## 测试152层深的ResNet的forward性能\n#def time_tensorflow_run(session, target, info_string):\n# \n# \n# \n# \n# num_steps_burn_in = 10\n# total_duration = 0.0\n# total_duration_squared = 0.0\n# for i in range(num_batches + num_steps_burn_in):\n# start_time = time.time()\n# _ = session.run(target)\n# duration = time.time() - start_time\n# if i >= num_steps_burn_in:\n# if not i % 10:\n# print ('%s: step %d, duration = %.3f' %\n# (datetime.now(), i - num_steps_burn_in, duration))\n# total_duration += duration\n# total_duration_squared += duration * duration\n# mn = total_duration / num_batches\n# vr = total_duration_squared / num_batches - mn * mn\n# sd = math.sqrt(vr)\n# print ('%s: %s across %d steps, %.3f +/- %.3f sec / batch' %\n# (datetime.now(), info_string, num_batches, mn, sd))\n\n#batch_size = 32\n#height, width = 224, 224\n#inputs = tf.random_uniform((batch_size, height, width, 3))\n#with slim.arg_scope(resnet_arg_scope(is_training=False)): # is_training设置为false\n# net, end_points = resnet_v2_50(inputs, 1000)\n#\n#init = tf.global_variables_initializer()\n#\n# \n#config = tf.ConfigProto()\n#config.gpu_options.allow_growth = True\n#sess = tf.Session(config=config,)\n##------------------------------------------- \n#summary = tf.summary.merge_all()\n#saver = tf.train.Saver() \n#summary_writer_train = tf.summary.FileWriter(\"logs\"+\"/train\", sess.graph)\n#summary_writer_test = tf.summary.FileWriter(\"logs\"+\"/test\", sess.graph)\n##sess = tf.Session()\n#sess.run(init) \n#num_batches=100\n#\n#time_tensorflow_run(sess, net, \"Forward\") \n#\n## forward计算耗时相比VGGNet和Inception V3大概只增加了50%,是一个实用的卷积神经网络。\n" }, { "alpha_fraction": 0.4956052601337433, "alphanum_fraction": 0.5151817798614502, "avg_line_length": 31.66666603088379, "blob_id": "340de846fa36e317e436b34fd5a0e04c56108bf6", "content_id": "24208563a2b9da0c1b9c75d26b3299d9105a2396", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5272, "license_type": "no_license", "max_line_length": 117, "num_lines": 153, "path": "/cifar10_tfrecord_ResNet/read_write_tfrecords.py", "repo_name": "LiJianfei06/tensorflow_projects", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport tensorflow as tf \nfrom PIL import Image\nimport numpy as np \ncwd = os.getcwd() # get dir of this file\n\n'''\n\n ------------------------------\n测试字母(n位)\n...\n'''\n \n \n\n\n\n\n\ndef save_tfrecords(train_or_test):\n i=0\n classes = [train_or_test];#目录 分别改成train 和 val 各跑一次就行了\n writer = tf.python_io.TFRecordWriter(train_or_test+\".tfrecords\") #分别改成train 和 val 各跑一次就行了\n for index, name in enumerate(classes):\n #print index, name\n #print cwd\n #class_path = cwd + \"/\"+name + \"/\"\n class_path = \"/home/lijianfei/datasets/cifar10_40/\"+train_or_test+\"/\"\n print class_path\n for img_name in os.listdir(class_path):\n img_path = class_path + img_name\n #print img_name[0],img_name[1]\n \n img = Image.open(img_path)\n #img = img.resize((32, 32))\n img_raw = img.tobytes() #将图片转化为原生bytes\n i+=1\n label_val=0\n\n if img_name[0:4]==\"airp\":\n idx=0\n elif img_name[0:4]==\"auto\":\n idx=1\n elif img_name[0:4]==\"bird\":\n idx=2\n elif img_name[0:3]==\"cat\":\n idx=3\n elif img_name[0:4]==\"deer\":\n idx=4\n elif img_name[0:3]==\"dog\":\n idx=5\n elif img_name[0:4]==\"frog\":\n idx=6\n elif img_name[0:4]==\"hors\":\n idx=7\n elif img_name[0:4]==\"ship\":\n idx=8\n elif img_name[0:4]==\"truc\":\n idx=9\n\n label_val=idx\n \n\n example = tf.train.Example(features=tf.train.Features(feature={\n \"label\": tf.train.Feature(int64_list=tf.train.Int64List(value=[label_val])),\n 'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))\n }))\n writer.write(example.SerializeToString()) #序列化为字符串\n writer.close()\n\n\n for serialized_example in tf.python_io.tf_record_iterator(train_or_test+\".tfrecords\"): #分别改成train 和 val 各跑一次就行了\n example = tf.train.Example()\n example.ParseFromString(serialized_example)\n\n image = example.features.feature['image'].bytes_list.value\n label = example.features.feature['label'].int64_list.value\n # 可以做一些预处理之类的\n #print image, label\n \n \n\n\n\n\n \ndef read_and_decode(filename,w_h):\n #根据文件名生成一个队列\n filename_queue = tf.train.string_input_producer([filename])\n\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue) #返回文件名和文件\n features = tf.parse_single_example(serialized_example,\n features={\n 'label': tf.FixedLenFeature([], tf.int64),\n 'img_raw' : tf.FixedLenFeature([], tf.string),})\n\n img = tf.decode_raw(features['img_raw'], tf.uint8)\n img = tf.reshape(img, [w_h, w_h, 3]) # check!\n #img = tf.cast(img, tf.float32) * (1. / 255) - 0.5\n label = tf.cast(features['label'], tf.int32)\n #print \"OK!\"\n return img, label\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n print \"make train datasets...\"\n save_tfrecords('train')\n print \"seccuss!\"\n\n print \"make test datasets...\"\n save_tfrecords('test')\n print \"seccuss!\"\n\n #分别改成train 和 val 各跑一次就行了\n img_train, label_train = read_and_decode(\"train.tfrecords\",40) \n img_test, label_test = read_and_decode(\"test.tfrecords\",32) \n\n\n #img_batch, label_batch = tf.train.batch([img_train, label_train],\n # batch_size=10, capacity=200,\n # num_threads=1)\n\n #使用shuffle_batch可以随机打乱输入\n img_batch_shuffle_train, label_batch_shuffle_train = tf.train.shuffle_batch([img_train, label_train],\n batch_size=10, capacity=200,\n min_after_dequeue=100,num_threads=4)\n img_batch_shuffle_test, label_batch_shuffle_test = tf.train.shuffle_batch([img_test, label_test],\n batch_size=10, capacity=200,\n min_after_dequeue=100,num_threads=4)\n\n init = tf.initialize_all_variables()\n\n with tf.Session() as sess:\n sess.run(init)\n threads = tf.train.start_queue_runners(sess=sess)\n for i in range(10):\n #val, l= sess.run([img_batch, label_batch]) # 打乱\n val_train, l_train= sess.run([img_batch_shuffle_train, label_batch_shuffle_train]) # 打乱\n val_test, l_test= sess.run([img_batch_shuffle_test, label_batch_shuffle_test]) # 打乱\n #我们也可以根据需要对val, l进行处理\n #l = to_categorical(l, 12) \n print(val_train.shape, l_train)\n print(val_test.shape, l_test)\n #print val[0,:,:,0]\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5397305488586426, "alphanum_fraction": 0.5768490433692932, "avg_line_length": 35.73737335205078, "blob_id": "904a5ce1bbe2d64a678c67a1a4d0e30765ab4899", "content_id": "dc8414ff9f125745766b54a5f4770d611f0f7ad9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3757, "license_type": "no_license", "max_line_length": 139, "num_lines": 99, "path": "/cifar10_tfrecord_ResNet/eval_image.py", "repo_name": "LiJianfei06/tensorflow_projects", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 12 08:20:54 2017\n\n@author: root\n\"\"\"\n\n\nimport cv2\nimport os\nimport sys\n#import argparse # argparse是python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块。\nfrom os import listdir\nimport os.path\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom PIL import ImageFilter,ImageEnhance\n#import time\nimport random\nfrom datetime import datetime\nimport numpy as np \nimport tensorflow as tf \nimport ResNet\nfrom tensorflow.python.ops import control_flow_ops \nfrom tensorflow.python.training import moving_averages \nslim = tf.contrib.slim # 使用方便的contrib.slim库来辅助创建ResNet\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.app.flags.DEFINE_integer('test_size_eval', 10000,\n \"\"\"Number of images to test.\"\"\")\n\ndef forward_run(model_name,labels_filename): \n\n print \"start...\"\n with tf.Graph().as_default():\n _inputRGB = tf.placeholder(tf.float32,[None, ResNet.IMAGE_HEIGHT, ResNet.IMAGE_WIDTH,3 ]) \n keep_prob = tf.placeholder(tf.float32) # dropout \n is_train = tf.placeholder(tf.bool) \n \n with slim.arg_scope(ResNet.resnet_arg_scope(is_training=is_train)): # is_training设置为false\n logits, end_points = ResNet.resnet_20(_inputRGB, 10,is_training=is_train)\n\n saver = tf.train.Saver() \n #------------------------------------------- 按需求增长显存 \n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config,)\n \n saver.restore(sess,model_name) # 读取模型 \n \n #predict = tf.argmax(tf.reshape(logits, [-1, 1, 10]), 2) slim.softmax(logits)\n predict1 = tf.argmax(tf.reshape(end_points['predictions'] , [-1, 1, 10]), 2) \n \n my_root=\"/home/lijianfei/datasets/cifar10_40/test/\"\n name_list =list(os.path.join(my_root,name)for name in os.listdir(my_root))\n #random_name_list=list(random.choice(name_list)for _ in range(FLAGS.test_size_eval))\n \n labels = np.loadtxt(labels_filename, str, delimiter='\\t')\n \n ture_mun=0.0\n false_mun=0.0\n for root_str in name_list:\n text=(root_str.split('/')[-1]).split('.')[0][0:4]\n text = ''.join(text)\n #image = convert2gray(image) \n bgrImg_temp = cv2.imread(root_str)#* (1.0 / 255.0) - 0.5\n #bgrImg_temp = bgrImg_temp * (1.0 / 255.0) \n #bgrImg_temp=cv2.resize(bgrImg_temp,(28,28))\n rgbImg=cv2.cvtColor(bgrImg_temp, cv2.COLOR_BGR2RGB)\n #img = tf.cast(rgbImg, tf.float32) * (1. / 255)\n img = rgbImg[:][:][:]* (1. / 255.0)\n #ROI = rgbImg[2:2+28, 2:2+28] \n #image = (image.flatten() *0.00390625)-0.5\n \n text_list = sess.run(predict1, feed_dict={_inputRGB: [img],is_train:False, keep_prob: 1.0}) \n \n predict_text = text_list[0].tolist() \n\n if labels[predict_text][0][0:3]== root_str.split(\"/\")[-1][0:3]:\n hint=\"True\" \n ture_mun+=1.\n else:\n hint=\"False\"\n false_mun+=1. \n #print(\"正确: %20s 预测: %10s /check:%5s\"%(root_str.split(\"/\")[-1].split(\".\")[0], labels[predict_text][0],hint))\n print(\"%d images true:%d false:%d accuracy:%.4f%%\"%(ture_mun+false_mun,ture_mun,false_mun,ture_mun*100.0/(ture_mun+false_mun)))\n \n \n\n\ndef main(argv=None): # pylint: disable=unused-argument\n model_name=\"./logs/model.ckpt-64000\"\n labels_filename = './labels.txt'\n forward_run(model_name,labels_filename) \n\n\nif __name__ == '__main__':\n tf.app.run()\n" }, { "alpha_fraction": 0.7443478107452393, "alphanum_fraction": 0.7652173638343811, "avg_line_length": 51.272727966308594, "blob_id": "d260ed04923676076ac69b68ef8013c3de9c72cb", "content_id": "339a6a2fa4bbd8b031abec3ababe0bf2b27c3fa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 953, "license_type": "no_license", "max_line_length": 101, "num_lines": 11, "path": "/tfrecord_test/readme.txt", "repo_name": "LiJianfei06/tensorflow_projects", "src_encoding": "UTF-8", "text": "read_write_data_test.py 演示了tfrecord的功能,把read_test_alphabet1文件夹下的文件按照0,1,2……的顺序打标签,测试打乱取batch和顺序取batch\n..............>python read_write_data_test.py 执行即可(必须是.py当前目录下),会看到输出的两大段\n\n\nread_write_data_alphabet.py 演示了tfrecord的功能,把read_test_alphabet1文件夹下的文件按照0-62打标签(数字加字母大小写),测试打乱取batch\n..............>python read_write_data_alphabet.py 执行即可(必须是.py当前目录下),会看到输出的两大段\n\n\nread_write_data_alphabet_n.py 演示了tfrecord的功能,把read_test_alphabet4文件夹下的文件按照0-62打标签\n(最后两位代表第一位字符,倒着来方便n位验证码),测试打乱取batch和顺序取batch\n..............>python read_write_data_alphabet_n.py 执行即可(必须是.py当前目录下),会看到输出的两大段\n" }, { "alpha_fraction": 0.7318181991577148, "alphanum_fraction": 0.7363636493682861, "avg_line_length": 26.5, "blob_id": "7b5c3fb7cf02fe43ebdcf711f3c7fc89bd0b3001", "content_id": "d57f13cb2fe5f645d542c771d4bc335c5abf0226", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 376, "license_type": "no_license", "max_line_length": 84, "num_lines": 8, "path": "/save_test/readme.txt", "repo_name": "LiJianfei06/tensorflow_projects", "src_encoding": "UTF-8", "text": "演示了Saver的功能,可以掉电保存,停了继续,只要保存了模型,以计数器为例\n\n..............>python start_tensorflow3_counter.py 执行即可(必须是.py当前目录下),会看到输出的计数值。\n\n\n\n开saver.restore(sess, \"counter_model/counter_model.ckpt\")这条,屏蔽sess.run(init_op)这条,是继续\n反之,是从头计数\n" }, { "alpha_fraction": 0.5209351181983948, "alphanum_fraction": 0.5453593730926514, "avg_line_length": 32.717647552490234, "blob_id": "020d84897988e603b242b9f2b99f1a5651cb3226", "content_id": "850edd7c17f4256066bd67833df2c1d23c280c26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2936, "license_type": "no_license", "max_line_length": 126, "num_lines": 85, "path": "/alphabet_tfrecord/eval_captcha.py", "repo_name": "LiJianfei06/tensorflow_projects", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 12 08:20:54 2017\n\n@author: root\n\"\"\"\n\nfrom gen_captcha import gen_captcha_text_and_image \nfrom gen_captcha import number \nfrom gen_captcha import alphabet \nfrom gen_captcha import ALPHABET \nimport os\nimport sys\n#import argparse # argparse是python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块。\nfrom os import listdir\nimport os.path\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom PIL import ImageFilter,ImageEnhance\n#import time\nimport random\nfrom datetime import datetime\nimport numpy as np \nimport tensorflow as tf \nimport mynet\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.app.flags.DEFINE_integer('test_size_eval', 1000,\n \"\"\"Number of images to test.\"\"\")\n\nprint \"start...\"\ndef crack_captcha(): \n with tf.Graph().as_default():\n \n with tf.device('/cpu:0'):\n X = tf.placeholder(tf.float32, [None, mynet.IMAGE_HEIGHT*mynet.IMAGE_WIDTH]) \n #Y = tf.placeholder(tf.float32, [None, mynet.MAX_CAPTCHA*mynet.CHAR_SET_LEN])\n \n keep_prob = tf.placeholder(tf.float32) # dropout \n \n logits = mynet.inference(X,keep_prob) \n# \n saver = tf.train.Saver() \n with tf.Session() as sess: \n saver.restore(sess,\"./logs/model.ckpt-300000\") \n \n predict = tf.argmax(tf.reshape(logits, [-1, mynet.MAX_CAPTCHA, mynet.CHAR_SET_LEN]), 2) \n \n my_root=\"test\"\n name_list =list(os.path.join(my_root,name)for name in os.listdir(my_root))\n random_name_list=list(random.choice(name_list)for _ in range(FLAGS.test_size_eval))\n \n ture_mun=0.0\n false_mun=0.0\n for root_str in random_name_list:\n text=(root_str.split('/')[-1]).split('.')[0][0:4]\n text = ''.join(text)\n image=np.array(Image.open(root_str)) \n #image = convert2gray(image) \n image = (image.flatten() *0.00390625)\n print text\n \n text_list = sess.run(predict, feed_dict={X: [image], keep_prob: 1}) \n predict_text = text_list[0].tolist() \n \n text_pre=mynet.vec2text(predict_text)\n if (((abs(ord(text[0])-ord(text_pre[0]))==32 and ord(text_pre[0])>48) or (ord(text[0])-ord(text_pre[0])==0))):\n hint=\"True\" \n ture_mun+=1\n else:\n hint=\"False\"\n false_mun+=1 \n print(\"正确: {} 预测: {} check:{}\".format(text[0], text_pre,hint))\n print(\"accuracy:%.4f%%\"%(ture_mun*100/(ture_mun+false_mun)))\n \n \n\n\ndef main(argv=None): # pylint: disable=unused-argument\n crack_captcha() \n\n\nif __name__ == '__main__':\n tf.app.run()\n" }, { "alpha_fraction": 0.5111033916473389, "alphanum_fraction": 0.5275850296020508, "avg_line_length": 44.20784378051758, "blob_id": "391b7f3b2f413525e3e731f33b01b0a025660711", "content_id": "c00ac16c05f10d79e49b2264d694b9cc3f2c3324", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11774, "license_type": "no_license", "max_line_length": 247, "num_lines": 255, "path": "/captcha_tfrecord/tensorflow_train_mynet.py", "repo_name": "LiJianfei06/tensorflow_projects", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\nfrom gen_captcha import gen_captcha_text_and_image \nfrom gen_captcha import number \nfrom gen_captcha import alphabet \nfrom gen_captcha import ALPHABET \nimport os\nimport sys\nimport argparse # argparse是python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块。\nfrom os import listdir\nimport os.path\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom PIL import ImageFilter,ImageEnhance\nimport time\nfrom datetime import datetime\nimport numpy as np \nimport tensorflow as tf \nimport random\n#reload(mynet)\nimport mynet\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.app.flags.DEFINE_integer('test_batch', 100,\n \"\"\"test_batch*test_num should equal to number of test size.\"\"\")\ntf.app.flags.DEFINE_float('test_num', 100,\n \"\"\"test_batch*test_num should equal to number of test size....\"\"\")\ntf.app.flags.DEFINE_integer('log_frequency', 100,\n \"\"\"log_frequency.\"\"\")\ntf.app.flags.DEFINE_string('test_dir', 'val',\n \"\"\"test_dir.\"\"\")\n\nclear=False # 是否清空从头训练\n\n\ndef read_and_decode(filename):\n #根据文件名生成一个队列\n filename_queue = tf.train.string_input_producer([filename])\n\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue) #返回文件名和文件\n features = tf.parse_single_example(serialized_example,\n features={\n 'label': tf.FixedLenFeature([], tf.int64),\n 'img_raw' : tf.FixedLenFeature([], tf.string),\n })\n\n img = tf.decode_raw(features['img_raw'], tf.uint8)\n img = tf.reshape(img, [32, 64, 1]) # check!\n #img = tf.cast(img, tf.float32) * (1. / 255) - 0.5\n img = 1-tf.cast(img, tf.float32) * 0.00390625\n\n label = tf.cast(features['label'], tf.int32)\n print \"OK!\"\n return img, label\n\n\n\n\n# 训练 \ndef train_crack_captcha_cnn(): \n# batch_x_train, batch_y_train = mynet.get_next_batch(batch_size=FLAGS.train_size,root_str=FLAGS.train_dir) \n# batch_x_test, batch_y_test = mynet.get_next_batch(batch_size=FLAGS.test_size,root_str=FLAGS.test_dir) \n start_time = time.time()\n total_duration_time=0 # total_time\n\n \n with tf.Graph().as_default(): \n with tf.device('/gpu:0'):\n X = tf.placeholder(tf.float32, [None, mynet.IMAGE_HEIGHT*mynet.IMAGE_WIDTH]) \n Y = tf.placeholder(tf.float32, [None, mynet.MAX_CAPTCHA*mynet.CHAR_SET_LEN])\n \n batch_x_train, batch_y_train = read_and_decode(\"train.tfrecords\")\n batch_x_test, batch_y_test = read_and_decode(\"val.tfrecords\")\n \n This_batch = tf.placeholder(tf.int32) # dropout\n print \"batch_x_train:\",batch_x_train\n print \"batch_y_train:\",batch_y_train\n\n img_batch_train, label_batch_train = tf.train.shuffle_batch([batch_x_train, batch_y_train],\n batch_size=This_batch, capacity=1024,\n min_after_dequeue=128,num_threads=16) \n img_batch_test, label_batch_test = tf.train.batch([batch_x_test, batch_y_test],\n batch_size=This_batch, capacity=2048,\n #min_after_dequeue=512,\n num_threads=16) \n \n global_ = tf.Variable(tf.constant(0)) \n keep_prob = tf.placeholder(tf.float32) # dropout \n \n logits = mynet.inference(X,keep_prob) \n #print 222\n loss=mynet.loss_fun(logits=logits, labels=Y)\n tf.summary.scalar('loss', loss)\n train_op,lr = mynet.training(loss,global_step=global_)\n \n accuracy = mynet.evaluation(logits=logits, labels=Y)\n \n tf.summary.scalar('accurate', accuracy) # display accurate in TensorBoard\n \n summary = tf.summary.merge_all()\n \n saver = tf.train.Saver() \n \n \n \n #sess = tf.Session()\n#------------------------------------------- 按比例限制显存 \n# config = tf.ConfigProto()\n# config.gpu_options.per_process_gpu_memory_fraction = 0.4\n# sess = tf.Session(config=config)\n#------------------------------------------- \n #------------------------------------------- 按需求增长显存 \n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config,)\n#------------------------------------------- \n \n # Instantiate a SummaryWriter to output summaries and the Graph.\n summary_writer_train = tf.summary.FileWriter(FLAGS.log_dir+\"/train\", sess.graph)\n summary_writer_test = tf.summary.FileWriter(FLAGS.log_dir+\"/test\", sess.graph)\n \n #with tf.Session() as sess: \n init_op = tf.global_variables_initializer() \n if clear==True:\n#------------------------------------------- 从头训练 \n sess.run(init_op) \n init_step=0\n else:\n#------------------------------------------- 断电继续(利用之前训练好的sess继续训练) \n saver.restore(sess, \"logs/model.ckpt-200000\") #要改\n print \"Model restored.\" \n init_step=200000 #要改\n \n \n coord = tf.train.Coordinator() #创建一个协调器,管理线程\n threads = tf.train.start_queue_runners(sess=sess,coord=coord)\n \n \n duration = time.time() - start_time\n total_duration_time+=duration\n start_time = time.time()\n acc=0\n for step in range(init_step,FLAGS.max_steps):\n #batch_x, batch_y = mynet.get_next_batch(batch_size=FLAGS.batch_size,root_str=FLAGS.train_dir) \n \n# k_index=np.array(random.sample(range(FLAGS.train_size),FLAGS.batch_size))\n# batch_x=batch_x_train[k_index]\n# batch_y=batch_y_train[k_index]\n #print \"\\n\\n\\n\\n\"\n\n batch_x, l= sess.run([img_batch_train, label_batch_train], feed_dict={This_batch: FLAGS.batch_size})\n batch_y= np.zeros([FLAGS.batch_size,mynet.MAX_CAPTCHA*mynet.CHAR_SET_LEN]) #1*62\n for i in range(FLAGS.batch_size):\n for j in range(mynet.MAX_CAPTCHA):\n batch_y[i,(l[i])%pow(100,j+1)/pow(100,j)-10+mynet.CHAR_SET_LEN*j] = 1 \n batch_x = np.reshape(batch_x, (-1, mynet.IMAGE_HEIGHT*mynet.IMAGE_WIDTH)) \n \n #print type(batch_x),type(batch_y)\n #print batch_x.shape,batch_y.shape\n #sys.exit(0)\n _, learn_lr,loss_ = sess.run([train_op,lr, loss], feed_dict={X: batch_x, Y: batch_y, keep_prob: 0.5+float(step)/2.0/float(FLAGS.max_steps),global_:step}) \n #print(step, loss_) \n if (step+1) % FLAGS.log_frequency == 0:\n duration = time.time() - start_time\n total_duration_time+=duration\n start_time = time.time()\n \n print \"ljf-tf:[%s] Iteration:%d/%d (%.1f examples/sec, %.3f sec/%.3f iters) ,loss=%.5f ,lr=%.5f\"%(datetime.now(),(step+1),FLAGS.max_steps,FLAGS.batch_size*FLAGS.log_frequency/duration,duration,FLAGS.log_frequency,loss_,learn_lr)\n\n\n \n# k_index=np.array(random.sample(range(FLAGS.test_size),FLAGS.test_batch))\n# batch_x=batch_x_test[k_index]\n# batch_y=batch_y_test[k_index] \n# batch_x, l= sess.run([img_batch_train, label_batch_train], feed_dict={This_batch: FLAGS.test_batch})\n# batch_y= np.zeros([FLAGS.test_batch,mynet.MAX_CAPTCHA*mynet.CHAR_SET_LEN]) #1*62\n# for i in range(FLAGS.test_batch):\n# for j in range(mynet.MAX_CAPTCHA):\n# batch_y[i,(l[i])%pow(100,j+1)/pow(100,j)-10+mynet.CHAR_SET_LEN*j] = 1 \n# batch_x = np.reshape(batch_x, (-1, mynet.IMAGE_HEIGHT*mynet.IMAGE_WIDTH)) \n \n summary_str = sess.run(summary, feed_dict={X: batch_x, Y: batch_y, keep_prob: 1.,global_:step})\n summary_writer_train.add_summary(summary_str, step)\n summary_writer_train.flush()\n\n# k_index=np.array(random.sample(range(FLAGS.test_size),FLAGS.test_batch))\n# batch_x=batch_x_test[k_index]\n# batch_y=batch_y_test[k_index] \n\n # 每100 step计算一次准确率 \n if (((step+1) % (FLAGS.log_frequency*5)== 0) or (step==0)): \n acc=0\n for i in range(FLAGS.test_num): #测试集 扫完\n # k_index=np.array(random.sample(range(i*FLAGS.test_batch,(i+1)*FLAGS.test_batch),FLAGS.test_batch))\n # batch_x=batch_x_train[k_index]\n # batch_y=batch_y_train[k_index] \n batch_x, l= sess.run([img_batch_test, label_batch_test], feed_dict={This_batch: FLAGS.test_batch})\n batch_y= np.zeros([FLAGS.test_batch,mynet.MAX_CAPTCHA*mynet.CHAR_SET_LEN]) #1*62\n for i in range(FLAGS.test_batch):\n for j in range(mynet.MAX_CAPTCHA):\n batch_y[i,(l[i])%pow(100,j+1)/pow(100,j)-10+mynet.CHAR_SET_LEN*j] = 1 \n batch_x = np.reshape(batch_x, (-1, mynet.IMAGE_HEIGHT*mynet.IMAGE_WIDTH)) \n \n acc += sess.run(accuracy, feed_dict={X: batch_x, Y: batch_y, keep_prob: 1.,global_:step}) \n acc=acc/FLAGS.test_num\n \n duration = time.time() - start_time\n total_duration_time+=duration\n start_time = time.time()\n print \"TensorFlow test net output: test accuracy:%.4f%% %.3f sec/1 test keep_prob:%.3f test time:%.3f sec total time:%.3f sec)\"%(acc*100,duration,0.5+float(step)/2.0/float(FLAGS.max_steps),duration,total_duration_time) \n \n else:\n batch_x, l= sess.run([img_batch_test, label_batch_test], feed_dict={This_batch: FLAGS.test_batch})\n batch_y= np.zeros([FLAGS.test_batch,mynet.MAX_CAPTCHA*mynet.CHAR_SET_LEN]) #1*62\n for i in range(FLAGS.test_batch):\n for j in range(mynet.MAX_CAPTCHA):\n batch_y[i,(l[i])%pow(100,j+1)/pow(100,j)-10+mynet.CHAR_SET_LEN*j] = 1 \n batch_x = np.reshape(batch_x, (-1, mynet.IMAGE_HEIGHT*mynet.IMAGE_WIDTH)) \n \n summary_str = sess.run(summary, feed_dict={X: batch_x, Y: batch_y, keep_prob: 1.,global_:step})\n summary_writer_test.add_summary(summary_str, step)\n summary_writer_test.flush() \n\n\n\n\n\n if (step+1) % 10000 == 0: \n checkpoint_file = os.path.join(FLAGS.log_dir, 'model.ckpt')\n saver.save(sess, checkpoint_file, global_step=step+1) \n\n coord.request_stop()\n\n # Wait for threads to finish.\n coord.join(threads)\n sess.close() \n\n\n\n\n\n\ndef main(argv=None): # pylint: disable=unused-argument\n if clear==True:\n if tf.gfile.Exists(FLAGS.log_dir):\n tf.gfile.DeleteRecursively(FLAGS.log_dir)\n tf.gfile.MakeDirs(FLAGS.log_dir)\n train_crack_captcha_cnn() \n\n\nif __name__ == '__main__':\n tf.app.run()\n" }, { "alpha_fraction": 0.5448076128959656, "alphanum_fraction": 0.5610964894294739, "avg_line_length": 44.60095977783203, "blob_id": "c7936834bfaeb8e66b0fefab8c83a1b8bc805568", "content_id": "aba0f7826f75b9c341c162f0c4b01ba0a6a925df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19530, "license_type": "no_license", "max_line_length": 247, "num_lines": 416, "path": "/cifar10_tfrecord_ResNet/train.py", "repo_name": "LiJianfei06/tensorflow_projects", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport argparse # argparse是python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块。\nfrom os import listdir\nimport os.path\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom PIL import ImageFilter,ImageEnhance\nimport time\nfrom datetime import datetime\nimport numpy as np \nimport tensorflow as tf \nimport random\nimport sklearn.preprocessing as prep # 提供了各种公共函数\n#reload(ResNet)\nimport collections # 原生的collections库\nimport tensorflow as tf\nslim = tf.contrib.slim # 使用方便的contrib.slim库来辅助创建ResNet\n\nimport ResNet\n\n\ndef load_weights( weight_file, sess):\n parameters = []\n weights = np.load(weight_file)\n keys = sorted(weights.keys())\n for i, k in enumerate(keys):\n # if i not in [30,31]:\n sess.run(parameters[i].assign(weights[k]))\n print(\"-----------all done---------------\")\n\n\n# Basic model parameters.\nFLAGS = tf.app.flags.FLAGS\n\ntf.app.flags.DEFINE_integer('train_size', 50000,\n \"\"\"Number of images to process in a batch.\"\"\")\ntf.app.flags.DEFINE_integer('test_size', 10000,\n \"\"\"Number of images to process in a batch.\"\"\")\ntf.app.flags.DEFINE_integer('test_batch', 20,\n \"\"\"test_batch*test_num should equal to number of test size.\"\"\")\ntf.app.flags.DEFINE_float('test_num', 500,\n \"\"\"test_batch*test_num should equal to number of test size....\"\"\")\ntf.app.flags.DEFINE_integer('batch_size', 128,\n \"\"\"Number of images to process in a batch.\"\"\")\n\ntf.app.flags.DEFINE_float('Initial_learning_rate', 0.1,\n \"\"\"Initial_learning_rate.\"\"\")\ntf.app.flags.DEFINE_integer('max_steps', 64000,\n \"\"\"max_steps.\"\"\")\ntf.app.flags.DEFINE_integer('log_frequency', 100,\n \"\"\"log_frequency.\"\"\")\ntf.app.flags.DEFINE_string('test_dir', 'val',\n \"\"\"test_dir.\"\"\")\ntf.app.flags.DEFINE_string('log_dir', 'logs',\n \"\"\"log_dir.\"\"\")\ntf.app.flags.DEFINE_string('train_dir', 'train',\n#tf.app.flags.DEFINE_boolean('use_fp16', False,\"\"\"Train the model using fp16.\"\"\")\n \"\"\"train_dir.\"\"\")\n\nclear=True # 是否清空从头训练\nis_on_subdivisions = True\nsubdivisions = 1\nsubdivisions_batch_size = int(np.ceil(FLAGS.batch_size / subdivisions))\n\n\n\n\n\n\n\n\n\"\"\"解析rfrecord \"\"\"\ndef read_and_decode(filename,w_h,phase=\"train\"):\n #根据文件名生成一个队列\n filename_queue = tf.train.string_input_producer([filename])\n\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue) #返回文件名和文件\n features = tf.parse_single_example(serialized_example,\n features={\n 'label': tf.FixedLenFeature([], tf.int64),\n 'img_raw' : tf.FixedLenFeature([], tf.string),\n })\n\n img = tf.decode_raw(features['img_raw'], tf.uint8)\n img = tf.reshape(img, [w_h, w_h,3])\n \n if phase==\"train\":\n img = tf.image.random_flip_left_right(img)\n #img = tf.image.flip_up_down(img)\n \n #img = tf.image.random_brightness(img, 0.2) # 亮度\n #img = tf.image.random_contrast(img, 0.1,0.2) # 对比度\n #img = tf.image.random_hue(img, 0.2) # 色相\n #img = tf.image.random_saturation(img, 0.1,0.2) # 饱和度\n\n\n img = tf.cast(img, tf.float32) * (1. / 255)\n distorted_image = tf.random_crop(img,[ResNet.IMAGE_HEIGHT,ResNet.IMAGE_WIDTH,3])\n distorted_image = tf.cast(distorted_image, tf.float32)\n\n label = tf.cast(features['label'], tf.int32)\n print \"OK!\"\n return distorted_image, label\n\n\n\n\"\"\"学习策略\"\"\"\n\"\"\"return:学习率\"\"\"\ndef training(loss,global_step):\n boundaries = [32000, 48000, 64000]\n values = [FLAGS.Initial_learning_rate, FLAGS.Initial_learning_rate/10.0, FLAGS.Initial_learning_rate/100.0,FLAGS.Initial_learning_rate/100.0]\n lr = tf.train.piecewise_constant(global_step, boundaries, values)\n \n opt = tf.train.MomentumOptimizer(lr,momentum=0.9,use_nesterov=True)\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n\n with tf.control_dependencies([tf.group(*update_ops)]):\n #train_op = slim.learning.create_train_op(loss, opt, global_step)\n #train_op = optimizer.minimize(loss) \n train_op = slim.learning.create_train_op(loss, opt,global_step=tf.train.get_or_create_global_step())\n return train_op,lr\n\n\n\"\"\"学习策略\"\"\"\n\"\"\"return:损失\"\"\"\ndef loss_fun(logits, labels):\n #logits1=tf.reshape(logits, [-1, 10])\n pose_loss = tf.losses.sparse_softmax_cross_entropy(logits=logits, labels=labels)\n #slim.losses.add_loss(pose_loss) #will be removed after 2016-12-30.\n tf.losses.add_loss(pose_loss)\n #regularization_loss = tf.add_n(slim.losses.get_regularization_losses()) \n #total_loss2 = pose_loss + regularization_loss \n #total_loss2 = slim.losses.get_total_loss() #will be removed after 2016-12-30\n total_loss2 = tf.losses.get_total_loss()\n #cross_entropy_mean = tf.reduce_mean(total_loss2) \n return total_loss2\n\n\n\"\"\"return:top_k_精度(分类)\"\"\"\ndef top_k_error(logits, labels,k_=1):\n #logits1=tf.reshape(logits, [-1, 10])\n #labels1=tf.reshape(labels, [-1, 10])\n #print logits1,labels\n correct = tf.nn.in_top_k(logits, labels, k=k_)\n return tf.reduce_sum(tf.cast(correct, tf.float32))/subdivisions_batch_size\n\n\n\"\"\"训练\"\"\"\ndef train_crack_captcha_cnn(): \n start_time = time.time()\n total_duration_time=0 # total_time\n\n with tf.Graph().as_default(): \n with tf.device('/cpu:0'):\n batch_x_train, batch_y_train = read_and_decode(\"train.tfrecords\",40,phase=\"train\")\n batch_x_test, batch_y_test = read_and_decode(\"test.tfrecords\",32,phase=\"test\")\n\n print \"batch_x_train:\",batch_x_train\n print \"batch_y_train:\",batch_y_train\n print \"batch_x_test:\",batch_x_test\n print \"batch_y_test:\",batch_y_test\n \n img_batch_train, label_batch_train = tf.train.shuffle_batch([batch_x_train, batch_y_train],\n batch_size=FLAGS.batch_size, capacity=int(FLAGS.train_size*0.02)+3*FLAGS.batch_size,\n min_after_dequeue=int(FLAGS.train_size*0.02),num_threads=4) \n img_batch_test, label_batch_test = tf.train.batch([batch_x_test, batch_y_test],\n batch_size=FLAGS.batch_size, capacity=int(FLAGS.train_size*0.02)+3*FLAGS.batch_size,\n #min_after_dequeue=512,\n num_threads=4) \n print \"img_batch_train:\",img_batch_train\n print \"label_batch_train:\",label_batch_train\n print \"img_batch_test:\",img_batch_test\n print \"label_batch_test:\",label_batch_test\n\n # Define \n _labels = tf.placeholder(tf.int32,[None,]) # 标签\n _inputRGB = tf.placeholder(tf.float32,[None,ResNet.IMAGE_HEIGHT,ResNet.IMAGE_WIDTH,3]) # 图像\n global_ = tf.placeholder(tf.int32) # 迭代次数\n is_train = tf.placeholder(tf.bool) # train or test 用于BN层\n keep_prob = tf.placeholder(tf.float32) # dropout \n \n with slim.arg_scope(ResNet.resnet_arg_scope(is_training=is_train)): \n net, end_points = ResNet.resnet_20(_inputRGB, 10,is_training=is_train,keep_prob=keep_prob)\n \n loss=loss_fun(logits=net, labels=_labels)\n print \"loss:\",loss\n #loss_test=loss_fun(logits=logits_test, labels=label_batch_test)\n \n tf.summary.scalar('loss', loss)\n #tf.summary.scalar('loss_test', loss_test) \n \n boundaries = [32000, 48000, 64000]\n values = [FLAGS.Initial_learning_rate, FLAGS.Initial_learning_rate/10.0, FLAGS.Initial_learning_rate/100.0,FLAGS.Initial_learning_rate/100.0]\n lr = tf.train.piecewise_constant(global_, boundaries, values)\n \n opt = tf.train.MomentumOptimizer(lr,momentum=0.9,use_nesterov=True)\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n\n\n grads = opt.compute_gradients(loss)\n #for grad, var in grads:\n # print (\"grad:\",grad)\n # print (\"var:\",var)\n\n # 删掉没梯度的参数, 倒序删除,减少麻烦\n for i in range(len(grads))[::-1]:\n if grads[i][0] is None:\n del grads[i]\n # 生成梯度缓存\n grads_cache = [tf.Variable(np.zeros(t[0].shape.as_list(), np.float32), trainable=False) for t in grads]\n # 清空梯度缓存op,每一 batch 开始前调用\n clear_grads_cache_op = tf.group(*[gc.assign(tf.zeros_like(gc)) for gc in grads_cache])\n # 累积梯度op,累积每个 sub batch 的梯度\n #print \"zip(grads_cache, grads_vars):\",zip(grads_cache, grads_vars)\n accumulate_grad_op = tf.group(*[gc.assign_add(gv[0]) for gc, gv in zip(grads_cache, grads)])\n # 求平均梯度,\n mean_grad = [gc/tf.to_float(subdivisions) for gc in grads_cache]\n # 组装梯度列表\n new_grads_vars = [(g, gv[1]) for g, gv in zip(mean_grad, grads)]\n\n apply_gradient_op = opt.apply_gradients(new_grads_vars)#, global_step=global_)\n #print \"grads:\",grads\n #print \"apply_gradient_op:\",apply_gradient_op\n #print \"*update_ops:\",update_ops\n \n train_op_new = tf.group(apply_gradient_op,*update_ops) \n \n\n #train_op,lr = training(loss,global_step=global_)\n\n tf.summary.scalar('learning_rate', lr)\n accuracy = top_k_error(logits=end_points['predictions'] , labels=_labels, k_=1)\n \n tf.summary.scalar('accurate', accuracy) # display accurate in TensorBoard\n\n image_train = img_batch_train \n image_test = img_batch_test \n tf.summary.image(\"image_train\", image_train)\n tf.summary.image(\"image_test\", image_test)\n \n summary = tf.summary.merge_all()\n \n saver = tf.train.Saver(max_to_keep=0) \n \n #sv = tf.train.Supervisor(logdir=FLAGS.log_dir)\n #sys.exit(0)\n \n#------------------------------------------ 吃光显存\n #sess = tf.Session()\n#------------------------------------------- 按比例限制显存 \n# config = tf.ConfigProto()\n# config.gpu_options.per_process_gpu_memory_fraction = 0.4\n# sess = tf.Session(config=config)\n#------------------------------------------- \n #------------------------------------------- 按需求增长显存 \n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config,)\n##------------------------------------------- \n \n # Instantiate a SummaryWriter to output summaries and the Graph.\n summary_writer_train = tf.summary.FileWriter(FLAGS.log_dir+\"/train\", sess.graph)\n summary_writer_test = tf.summary.FileWriter(FLAGS.log_dir+\"/test\", sess.graph)\n \n #with tf.Session() as sess: \n init_op = tf.global_variables_initializer() \n\n if clear==True:\n#------------------------------------------- 从头训练 \n sess.run(init_op) \n init_step=0\n else:\n#------------------------------------------- 断电继续(利用之前训练好的sess继续训练) \n #saver.restore(sess, \"./logs/model.ckpt-50000\") #要改\n saver = tf.train.import_meta_graph('./logs/model.ckpt-50000.meta')\n saver.restore(sess, tf.train.latest_checkpoint(\"./logs/\"))\n print \"Model restored.\" \n init_step=50000 #要改\n for var in tf.trainable_variables():\n print var\n fine_tune_var_list = [v for v in tf.trainable_variables() ]\n\n\n\n\n #fine_tune_var_list = [v for v in tf.trainable_variables() if v.name.split('/')[0] in train_layers]\n #print \"fine_tune_var_list:\",fine_tune_var_list\n \n #load_weights( \"./logs/model.ckpt-50000\", sess ) \n \n coord = tf.train.Coordinator() #创建一个协调器,管理线程\n threads = tf.train.start_queue_runners(sess=sess,coord=coord)\n\n \n duration = time.time() - start_time\n total_duration_time+=duration\n start_time = time.time()\n max_acc=0\n max_acc_iter=0\n acc=0\n loss_sum = 0 \n for step in range(init_step,FLAGS.max_steps):\n loss_sum = 0 \n batch_x, batch_y= sess.run([img_batch_train, label_batch_train])\n if is_on_subdivisions:\n sess.run(clear_grads_cache_op) # 每一批开始前需要清空梯度缓存\n sub_loss_sum = 0\n for s in range(subdivisions):\n\n x_sub_batch = batch_x[s * subdivisions_batch_size: (s + 1) * subdivisions_batch_size]\n y_sub_batch = batch_y[s * subdivisions_batch_size: (s + 1) * subdivisions_batch_size]\n # #_, learn_lr,loss_ = sess.run([train_op,lr, loss], feed_dict={ _inputRGB:x_sub_batch ,_labels:y_sub_batch,keep_prob: 0.8,is_train:True,global_:step}) \n feed_dict = {_inputRGB: x_sub_batch, _labels: y_sub_batch,keep_prob: 0.5,is_train:True,global_:step}\n _, los = sess.run([accumulate_grad_op, loss], feed_dict)\n sub_loss_sum += los\n loss_sum += sub_loss_sum / subdivisions\n feed_dict = {_inputRGB: x_sub_batch, _labels: y_sub_batch,keep_prob: 0.5,is_train:True,global_:step}\n _ = sess.run([train_op_new,lr],feed_dict) # 梯度累积完成,开始应用梯度\n learn_lr = _[1]\n #print \"_:\",_\n\n #batch_x, batch_y= sess.run([img_batch_train, label_batch_train])\n\n #sys.exit(0)\n #_, learn_lr,loss_ = sess.run([train_op,lr, loss], feed_dict={ _inputRGB:batch_x ,_labels:batch_y,keep_prob: 0.8,is_train:True,global_:step}) \n #loss_ = sess.run(loss, feed_dict={ _inputRGB:batch_x ,_labels:batch_y,keep_prob: 0.8,is_train:True,global_:step}) \n #_, = sess.run([train_op_new], feed_dict={ _inputRGB:batch_x ,_labels:batch_y,keep_prob: 0.8,is_train:True,global_:step}) \n\n \n if (step+1) % FLAGS.log_frequency == 0:\n duration = time.time() - start_time\n total_duration_time+=duration\n start_time = time.time()\n \n #print \"[%s] ljf-tf-train: Iter:%d/%d (%.1f examples/sec, %.3f sec/%d iters) ,loss=%.5f ,lr=%.5f\"%(datetime.now(),(step+1),FLAGS.max_steps,FLAGS.batch_size*FLAGS.log_frequency/duration,duration,FLAGS.log_frequency,loss_,learn_lr)\n print \"[%s] ljf-tf-train: Iter:%d/%d (%.1f examples/sec, %.3f sec/%d iters) ,loss=%.5f ,lr=%.5f\"%(datetime.now(),(step+1),FLAGS.max_steps,FLAGS.batch_size*FLAGS.log_frequency/duration,duration,FLAGS.log_frequency,loss_sum,learn_lr)\n # 每100 step计算一次准确率 \n if (((step+1) % (FLAGS.log_frequency*5)== 0) or (step==0)): \n acc_train=0\n acc_test=0\n for i in range(FLAGS.test_num): #train\n batch_x, batch_y= sess.run([img_batch_train, label_batch_train]) \n sub_acc=0\n for s in range(subdivisions):\n x_sub_batch = batch_x[s * subdivisions_batch_size: (s + 1) * subdivisions_batch_size]\n y_sub_batch = batch_y[s * subdivisions_batch_size: (s + 1) * subdivisions_batch_size]\n sub_acc += sess.run(accuracy, feed_dict={_inputRGB:x_sub_batch ,_labels:y_sub_batch,keep_prob: 1.,is_train:False,global_:step})\n\n acc_train+=sub_acc/subdivisions\n #acc += sess.run(accuracy, feed_dict={_inputRGB:batch_x ,_labels:batch_y,keep_prob: 1.,is_train:False,global_:step})\n acc_train=acc_train/FLAGS.test_num\n \n \n summary_str = sess.run(summary, feed_dict={_inputRGB:x_sub_batch ,_labels:y_sub_batch,is_train:False,keep_prob: 1.,global_:step}) # 训练的tensorboard\n summary_writer_train.add_summary(summary_str, step)\n summary_writer_train.flush()\n\n for i in range(FLAGS.test_num): #test\n batch_x, batch_y= sess.run([img_batch_test, label_batch_test]) \n sub_acc=0\n for s in range(subdivisions):\n x_sub_batch = batch_x[s * subdivisions_batch_size: (s + 1) * subdivisions_batch_size]\n y_sub_batch = batch_y[s * subdivisions_batch_size: (s + 1) * subdivisions_batch_size]\n sub_acc += sess.run(accuracy, feed_dict={_inputRGB:x_sub_batch ,_labels:y_sub_batch,keep_prob: 1.,is_train:False,global_:step})\n #acc_test += sess.run(accuracy, feed_dict={ _inputRGB:batch_x ,_labels:batch_y,keep_prob: 1.,is_train:False,global_:step})\n acc_test+=sub_acc/subdivisions\n acc_test=acc_test/FLAGS.test_num\n \n loss_test = sess.run(loss, feed_dict={ _inputRGB:x_sub_batch ,_labels:y_sub_batch,keep_prob: 1,is_train:True,global_:step}) # 测试的tensorboard\n \n summary_str = sess.run(summary, feed_dict={_inputRGB:x_sub_batch ,_labels:y_sub_batch,is_train:False,keep_prob: 1.,global_:step})\n summary_writer_test.add_summary(summary_str, step)\n summary_writer_test.flush() \n\n duration = time.time() - start_time\n total_duration_time+=duration\n start_time = time.time()\n \n if(acc_test>max_acc):\n max_acc=acc_test\n max_acc_iter=step+1\n checkpoint_file = os.path.join(FLAGS.log_dir, 'model.ckpt')\n saver.save(sess, checkpoint_file, global_step=step+1) \n\n print \"[%s] ljf-tf-test : train accuracy:%.4f%%, test accuracy:%.4f%% , max accuracy:%.4f%% , max accuracy step:%d\"%(datetime.now(),acc_train*100,acc_test*100,max_acc*100,max_acc_iter) \n print \"[%s] ljf-tf-test : test loss=%.5f, test time:%.3f sec, total time:%.3f sec\"%(datetime.now(),loss_test,duration,total_duration_time)\n\n if (step+1) % 10000 == 0 or (step+1)==FLAGS.max_steps: \n checkpoint_file = os.path.join(FLAGS.log_dir, 'model.ckpt')\n saver.save(sess, checkpoint_file, global_step=step+1) \n\n \n coord.request_stop()\n # Wait for threads to finish.\n coord.join(threads)\n sess.close() \n\n\n\n\n\ndef main(argv=None): # pylint: disable=unused-argument\n print(\"Tensorflow version \" + tf.__version__)\n if clear==True:\n if tf.gfile.Exists(FLAGS.log_dir):\n tf.gfile.DeleteRecursively(FLAGS.log_dir)\n tf.gfile.MakeDirs(FLAGS.log_dir)\n train_crack_captcha_cnn() \n\n\nif __name__ == '__main__':\n tf.app.run()\n" }, { "alpha_fraction": 0.535289466381073, "alphanum_fraction": 0.5693894028663635, "avg_line_length": 32.87387466430664, "blob_id": "02c49d4adeb643367c14dbc543df5e9108c56d9f", "content_id": "6e4ef9a7b8fe241f260f94a23035f6d010cba206", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3931, "license_type": "no_license", "max_line_length": 121, "num_lines": 111, "path": "/alphabet_tfrecord/generate_captcha_samples.py", "repo_name": "LiJianfei06/tensorflow_projects", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 11 21:32:34 2017\n设置好各自数量,直接执行即可\n@author: root\n\"\"\"\n\nfrom gen_captcha import gen_captcha_text_and_image \nfrom gen_captcha import number \nfrom gen_captcha import alphabet \nfrom gen_captcha import ALPHABET \nfrom PIL import Image \nimport shutil\nfrom numpy import *\nimport os\nimport sys\nfrom os import listdir\nimport os.path\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom PIL import ImageFilter,ImageEnhance\nimport time\n\nfrom datetime import datetime\nimport random\n\ntrain_mun = 100000 \nval_mun = 10000 \ntest_mun = 1000 \n\n\n\n\n#generate\ndef random_captcha_generate(num=2,file_train_flag=1,file_val_flag=0,file_test_flag=0):\n for i in range(num):\n text, image = gen_captcha_text_and_image(file_train_flag,file_val_flag,file_test_flag,i=i)\n #print i,text\n if (i+1)%(num/100)==0:\n if file_train_flag==1:\n sys.stdout.write('\\r>> Generate train samples... %.3f%%' % (float(i+1) / float(num) * 100.0)) \n elif file_val_flag==1:\n sys.stdout.write('\\r>> Generate val samples... %.3f%%' % (float(i+1) / float(num) * 100.0)) \n elif file_test_flag==1:\n sys.stdout.write('\\r>> Generate test samples... %.3f%%' % (float(i+1) / float(num) * 100.0)) \n sys.stdout.flush() # 这句代码的意思是刷新输出\n print \"\\n %d samples generate succeed!\"%num \n \n \n\n#resize\ndef random_captcha_resize(str_place):\n #filename1=\"val.txt\"\n \n #fp=open(filename1,\"w\")\n i=0\n for dirpath, dirnames, filenames in os.walk(str_place):\n print \"Directory:%s\"%dirpath\n #print type(filenames) #返回的是一个list\n file_mun=len(filenames)\n for filename in filenames:\n if (i+1)%(file_mun/100)==0:\n sys.stdout.write('\\r>> resize Directory samples... %.3f%%' % (float(i+1) / float(file_mun) * 100.0)) \n sys.stdout.flush() # 这句代码的意思是刷新输出\n #print i,filename,filename[0]\n i=i+1\n img = Image.open(str_place+filename)\n img = img.crop((0,0,40,60)) # 裁剪\n img=img.convert('L') #灰度化\n #img=img.convert('1')#二值化\n# for ii in range(2):\n# img=img.filter(ImageFilter.MedianFilter) #中值滤波\n \n out = img.resize((32,32),Image.ANTIALIAS)\n out.save(str_place+filename,quality=100)\n \n # if(ord(filename[0])<=57 and ord(filename[0])>=48):\n # fp.write(filename+' '+filename[0]+'\\n')\n # elif(ord(filename[0])<=90 and ord(filename[0])>=65): # A....\n # fp.write(filename+' '+str(ord(filename[0])-65+10)+'\\n')\n # elif(ord(filename[0])<=122 and ord(filename[0])>=97): # A....\n # fp.write(filename+' '+str(ord(filename[0])-97+36)+'\\n') \n #fp.close()\n print \"\\n succeed!\"\n\n\n\nstart_time = time.time()\n\n#if os.path.exists('train'): # 如果目录存在\n# shutil.rmtree(r'train') \n#if os.path.exists('val'): # 如果目录存在\n# shutil.rmtree(r'val') \nif os.path.exists('test'): # 如果目录存在\n shutil.rmtree(r'test') \n\n#os.makedirs(\"train\")\n#os.makedirs(\"val\")\nos.makedirs(\"test\")\n#random_captcha_generate(num=train_mun,file_train_flag=1,file_val_flag=0,file_test_flag=0)\n#random_captcha_generate(num=val_mun,file_train_flag=0,file_val_flag=1,file_test_flag=0)\nrandom_captcha_generate(num=test_mun,file_train_flag=0,file_val_flag=0,file_test_flag=1)\n\n\n#random_captcha_resize(\"train/\")\n#random_captcha_resize(\"val/\")\nrandom_captcha_resize(\"test/\")\n\nduration = time.time() - start_time\n\nprint('Spend time: %.3f sec' % (duration))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5616580247879028, "alphanum_fraction": 0.5658031105995178, "avg_line_length": 20.772727966308594, "blob_id": "16031ab3872f55a3ac4c00726e431bb0560843e2", "content_id": "4455809102a2cd37e7418644b89f0f421d2c59c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1027, "license_type": "no_license", "max_line_length": 68, "num_lines": 44, "path": "/save_test/start_tensorflow3_counter.py", "repo_name": "LiJianfei06/tensorflow_projects", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nSaver \nPlease read readme.txt\n\"\"\"\n\n# 进入一个交互式 TensorFlow 会话.\nimport tensorflow as tf\n\nif __name__ == '__main__': \n\n state = tf.Variable(0, name=\"counter\")\n\n one = tf.constant(1)\n new_value = tf.add(state, one)\n update = tf.assign(state, new_value)\n \n\n init_op = tf.global_variables_initializer()\n \n saver = tf.train.Saver()\n \n \n # 启动图, 运行 op\n #with tf.Session() as sess:\n sess = tf.Session()\n # 运行 'init' op\n \n #sess.run(init_op)\n saver.restore(sess, \"counter_model/counter_model.ckpt\")\n print \"Model restored.\"\n # # 打印 'state' 的初始值\n #print sess.run(state)\n #print state.eval()\n \n print ' '\n # 运行 op, 更新 'state', 并打印 'state'\n for _ in range(3):\n sess.run(update)\n print sess.run(state)\n #print state.eval()\n save_path = saver.save(sess, \"counter_model/counter_model.ckpt\")\n print \"Model saved in file: \", save_path\n # 输出:\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.521321177482605, "alphanum_fraction": 0.546462893486023, "avg_line_length": 31.19841194152832, "blob_id": "d042cce4c6b1bb8d888e0be29ce3a6f8e3c19bce", "content_id": "6c396e4e48ad943835ee61e56301aee3776a171d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4445, "license_type": "no_license", "max_line_length": 102, "num_lines": 126, "path": "/alphabet_tfrecord/read_write_data_alphabet_n.py", "repo_name": "LiJianfei06/tensorflow_projects", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport tensorflow as tf \nfrom PIL import Image\nimport numpy as np \ncwd = os.getcwd() # get dir of this file\n\n'''\n此处我加载的数据目录如下:\n0 -- img1.jpg\n img2.jpg\n img3.jpg\n ...\n1 -- img1.jpg\n img2.jpg\n ...\n2 -- ...\n 这里的0, 1, 2...就是类别,也就是下文中的classes\n classes是我根据自己数据类型定义的一个列表,大家可以根据自己的数据情况灵活运用\n \n \n \n ------------------------------\n测试字母(n位)\n...\n'''\nMAX_CAPTCHA = 1\nCHAR_SET_LEN=62*MAX_CAPTCHA\n\n\ni=0\nclasses = [\"val\" ];#目录 分别改成train 和 val 各跑一次就行了\nprint \"start...\"\nwriter = tf.python_io.TFRecordWriter(\"val.tfrecords\") #分别改成train 和 val 各跑一次就行了\nfor index, name in enumerate(classes):\n print index, name\n print cwd\n class_path = cwd + \"/\"+name + \"/\"\n print class_path\n for img_name in os.listdir(class_path):\n img_path = class_path + img_name\n #print img_name[0],img_name[1]\n \n img = Image.open(img_path)\n #img = img.resize((32, 32))\n img_raw = img.tobytes() #将图片转化为原生bytes\n i+=1\n label_val=0\n for n in range(MAX_CAPTCHA):\n vector = np.zeros(1*CHAR_SET_LEN,int) #4*62\n if(ord(img_name[n])<=57 and ord(img_name[n])>=48):\n idx = ord(img_name[n])-48\n elif(ord(img_name[n])<=90 and ord(img_name[n])>=65): # A....\n idx = ord(img_name[n])-65+10\n elif(ord(img_name[n])<=122 and ord(img_name[n])>=97): # a....\n idx = ord(img_name[n])-97+36\n idx+=10\n label_val+=idx*pow(100, n)\n #print label_val\n# vector[idx] = 1 \n #print vector.tolist()\n #idx=i\n example = tf.train.Example(features=tf.train.Features(feature={\n \"label\": tf.train.Feature(int64_list=tf.train.Int64List(value=[label_val])),\n 'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))\n }))\n writer.write(example.SerializeToString()) #序列化为字符串\nwriter.close()\n\n\n\nfor serialized_example in tf.python_io.tf_record_iterator(\"val.tfrecords\"): #分别改成train 和 val 各跑一次就行了\n example = tf.train.Example()\n example.ParseFromString(serialized_example)\n\n image = example.features.feature['image'].bytes_list.value\n label = example.features.feature['label'].int64_list.value\n # 可以做一些预处理之类的\n #print image, label\n \n \n \n \ndef read_and_decode(filename):\n #根据文件名生成一个队列\n filename_queue = tf.train.string_input_producer([filename])\n\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue) #返回文件名和文件\n features = tf.parse_single_example(serialized_example,\n features={\n 'label': tf.FixedLenFeature([], tf.int64),\n 'img_raw' : tf.FixedLenFeature([], tf.string),\n })\n\n img = tf.decode_raw(features['img_raw'], tf.uint8)\n img = tf.reshape(img, [32, 32, 1]) # check!\n img = tf.cast(img, tf.float32) * (1. / 255) - 0.5\n label = tf.cast(features['label'], tf.int32)\n print \"OK!\"\n return img, label\n\n\n\n#分别改成train 和 val 各跑一次就行了\nimg, label = read_and_decode(\"val.tfrecords\") \n\n#使用shuffle_batch可以随机打乱输入\nimg_batch_shuffle, label_batch_shuffle = tf.train.shuffle_batch([img, label],\n batch_size=10, capacity=200,\n min_after_dequeue=100,num_threads=1)\nimg_batch, label_batch = tf.train.batch([img, label],\n batch_size=10, capacity=200,\n num_threads=1)\ninit = tf.initialize_all_variables()\n\nwith tf.Session() as sess:\n sess.run(init)\n threads = tf.train.start_queue_runners(sess=sess)\n for i in range(10):\n val, l= sess.run([img_batch_shuffle, label_batch_shuffle]) # 打乱\n #我们也可以根据需要对val, l进行处理\n #l = to_categorical(l, 12) \n print(val.shape, l)\n #print val[0,:,:,0]\n" }, { "alpha_fraction": 0.6608315110206604, "alphanum_fraction": 0.7199124693870544, "avg_line_length": 31.64285659790039, "blob_id": "33235efae5dcdb9e344deeb7b6a262927352fc2e", "content_id": "37fd2b701dd7e0f832658d7fd97ecbb1dc9c610c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 715, "license_type": "no_license", "max_line_length": 103, "num_lines": 14, "path": "/alphabet_tfrecord/readme.txt", "repo_name": "LiJianfei06/tensorflow_projects", "src_encoding": "UTF-8", "text": "python tensorflow_captcha_generate_samples.py 生成样本,必须在当前目录下,默认100k个训练样本,10K个测试集,1000个用来测试预测的(跑网络时用不到)\n\nread_write_data_alphabet_n.py \t\t生成train.tfrecords和val.tfrecords训练文件(后面训练我是用16线程读取的,视自己计算机性能而定)\n\npython tensorflow_train_mynet.py \t\t训练,必须在当前目录下\n...........................>tensorboard --logdir=\"logs\" 查看训练曲线,必须在当前目录下\n\nmynet.py \t\t\t\t\t网络结构什么的都在这里面\npython eval_captcha.py \t\t\t预测,必须在当前目录下\n\n\n\n支持tfrecord \t\t 2017-10-19\n支持saver 断电续训练 \t 2017-10-22\n" }, { "alpha_fraction": 0.5376368761062622, "alphanum_fraction": 0.581055223941803, "avg_line_length": 39.68224334716797, "blob_id": "72cff8d4c938e5fdb2b22c4044344b3520e0a707", "content_id": "e90631cf9b716acd0311ea140fa7c0db524abd57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13657, "license_type": "no_license", "max_line_length": 148, "num_lines": 321, "path": "/captcha_tfrecord/mynet.py", "repo_name": "LiJianfei06/tensorflow_projects", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 11 19:51:42 2017\n\n@author: root\n\"\"\"\n\n\nfrom gen_captcha import gen_captcha_text_and_image \nfrom gen_captcha import number \nfrom gen_captcha import alphabet \nfrom gen_captcha import ALPHABET \nimport os\nimport sys\n#import argparse # argparse是python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块。\nimport random\nfrom os import listdir\nimport os.path\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom PIL import ImageFilter,ImageEnhance\nimport time\nfrom datetime import datetime\nimport numpy as np \nimport tensorflow as tf \n\nFLAGS = tf.app.flags.FLAGS\n\n# Basic model parameters.\ntf.app.flags.DEFINE_integer('train_size', 100000,\n \"\"\"Number of images to process in a batch.\"\"\")\ntf.app.flags.DEFINE_integer('test_size', 10000,\n \"\"\"Number of images to process in a batch.\"\"\")\ntf.app.flags.DEFINE_integer('batch_size', 128,\n \"\"\"Number of images to process in a batch.\"\"\")\ntf.app.flags.DEFINE_float('Initial_learning_rate', 1e-2*128/256,\n \"\"\"max_steps.\"\"\")\ntf.app.flags.DEFINE_integer('max_steps', 500000,\n \"\"\"max_steps.\"\"\")\ntf.app.flags.DEFINE_string('log_dir', 'logs',\n \"\"\"log_dir.\"\"\")\ntf.app.flags.DEFINE_string('train_dir', 'train',\n \"\"\"train_dir.\"\"\")\ntf.app.flags.DEFINE_boolean('use_fp16', False,\n \"\"\"Train the model using fp16.\"\"\")\n\n\n\n\n\nchar_set = number + alphabet + ALPHABET # 验证码长度 62\nCHAR_SET_LEN = len(char_set) \n\nname_list =list(os.path.join(FLAGS.train_dir,name)for name in os.listdir(FLAGS.train_dir))\nrandom_name_list=list(random.choice(name_list)for _ in range(1))\nfor root_str in random_name_list:\n text=(root_str.split('/')[-1]).split('.')[0][0:4] # 0 or 0:4 \n text = ''.join(text)\n image=np.array(Image.open(root_str)) \n\nMAX_CAPTCHA = len(text)\n# 图像大小 \nIMAGE_WIDTH = image.shape[0] \nIMAGE_HEIGHT = image.shape[1] \nprint IMAGE_WIDTH ,IMAGE_HEIGHT\nprint u\"图像channel:\",image.shape\nprint u\"输出个数:\", MAX_CAPTCHA # 验证码最长4字符; 我全部固定为4,可以不固定. 如果验证码长度小于4,用'_'补齐 \n\n\n\n\n# 把彩色图像转为灰度图像(色彩对识别验证码没有什么用) \ndef convert2gray(img): \n if len(img.shape) > 2: \n gray = np.mean(img, -1) \n # 上面的转法较快,正规转法如下 \n # r, g, b = img[:,:,0], img[:,:,1], img[:,:,2] \n # gray = 0.2989 * r + 0.5870 * g + 0.1140 * b \n return gray \n else: \n return img \n \n\n# 文本转向量 \ndef text2vec(text): \n \n vector = np.zeros(MAX_CAPTCHA*CHAR_SET_LEN) #1*62\n \n for i in range(len(text)):\n if(ord(text[i])<=57 and ord(text[i])>=48):\n idx = i * CHAR_SET_LEN + ord(text[i])-48\n elif(ord(text[i])<=90 and ord(text[i])>=65): # A....\n idx = i * CHAR_SET_LEN + ord(text[i])-65+10\n elif(ord(text[i])<=122 and ord(text[i])>=97): # A....\n idx = i * CHAR_SET_LEN + ord(text[i])-97+36\n vector[idx] = 1 \n #print vector\n return vector \n\n# 向量转回文本 \ndef vec2text(vec): \n text=[] \n for c in vec: \n #print c\n #char_at_pos = i #c/63 \n char_idx = c % CHAR_SET_LEN \n if char_idx < 10: \n char_code = char_idx + ord('0') \n elif char_idx <36: \n char_code = char_idx - 10 + ord('A') \n elif char_idx < 62: \n char_code = char_idx- 36 + ord('a') \n else: \n raise ValueError('error') \n text.append(chr(char_code)) \n return \"\".join(text) \n\n\n\n\n#by LiJianfei\n#def get_next_batch(batch_size=128,root_str=\"train\"): \n# batch_x = np.zeros([batch_size, IMAGE_HEIGHT*IMAGE_WIDTH]) \n# batch_y = np.zeros([batch_size, MAX_CAPTCHA*CHAR_SET_LEN]) \n# i=0\n# name_list =list(os.path.join(root_str,name)for name in os.listdir(root_str))\n# random_name_list=list(random.choice(name_list)for _ in range(batch_size))\n# for root_str in random_name_list:\n# text=(root_str.split('/')[-1]).split('.')[0][0:4] # 0 or 0:4 \n# text = ''.join(text)\n# image=np.array(Image.open(root_str)) \n# #print text,image\n# batch_x[i,:] = 1.0-(image.flatten() *0.00390625) # (image.flatten()-128)/128 mean为0 \n# batch_y[i,:] = text2vec(text) \n# if (((i+1)%(batch_size/100)==0) and (batch_size==FLAGS.train_size)):\n# sys.stdout.write('\\r>> loading samples... %.3f%%' % ((float(i+1) / float(batch_size)) * 100.0))\n# sys.stdout.flush() # 这句代码的意思是刷新输出\n# #print batch_x[i,:],batch_y[i,:]\n# i=i+1\n# return batch_x, batch_y \n\n#################################################################### \ndef _variable_on_cpu(name, shape, initializer):\n \"\"\"Helper to create a Variable stored on CPU memory.\n\n Args:\n name: name of the variable\n shape: list of ints\n initializer: initializer for Variable\n\n Returns:\n Variable Tensor\n \"\"\"\n with tf.device('/gpu:0'):\n dtype = tf.float16 if FLAGS.use_fp16 else tf.float32\n var = tf.get_variable(name, shape, initializer=initializer, dtype=dtype) #变量初始化\n return var\n\ndef _variable_with_weight_decay(name, shape, stddev, wd):\n \"\"\"Helper to create an initialized Variable with weight decay.\n\n Note that the Variable is initialized with a truncated normal distribution.\n A weight decay is added only if one is specified.\n \n Args:\n name: name of the variable\n shape: list of ints\n stddev: standard deviation of a truncated Gaussian\n wd: add L2Loss weight decay multiplied by this float. If None, weight\n decay is not added for this Variable.\n\n Returns:\n Variable Tensor\n \"\"\"\n dtype = tf.float16 if FLAGS.use_fp16 else tf.float32\n var = _variable_on_cpu(name,shape,tf.truncated_normal_initializer(stddev=stddev, dtype=dtype)) # 截取的正态分布\n if wd is not None:\n weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss') # L2 正则化\n tf.add_to_collection('losses', weight_decay) # 把变量放入一个集合,把很多变量变成一个列表\n return var\n\n\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1) #这个函数产生正太分布,均值和标准差自己设定。默认:shape,mean=0.0,stddev=1.0,dtype=dtypes.float32,seed=None,name=None\n return tf.Variable(initial)\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\n\n# 定义CNN \ndef inference(images,keep_prob): \n x = tf.reshape(images, shape=[-1, IMAGE_WIDTH, IMAGE_HEIGHT, 1]) \n \n # conv layer \n with tf.variable_scope('conv1') as scope:#每一层都创建于一个唯一的 tf.name_scope 之下,创建于该作用域之下的所有元素都将带有其前缀\n kernel = _variable_with_weight_decay('weights',shape=[3, 3, 1, 32],stddev=0.1,wd=0.00) # 权值\n conv = tf.nn.conv2d(x, kernel, [1, 1, 1, 1], padding='SAME') # 实现卷积 \n biases = _variable_on_cpu('biases', [32], tf.constant_initializer(0.0)) # 偏置\n conv1 = tf.nn.bias_add(conv, biases) # 这个函数的作用是将偏差项 bias 加到 conv 上面\n print ('conv1',conv1) \n #_activation_summary(conv1)\n # relu1\n relu1 = tf.nn.relu(conv1, name=scope.name) # 激活函数 \n # pool1\n pool1 = tf.nn.max_pool(relu1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1],padding='SAME', name='pool1')\n # norm1\n norm1 = tf.nn.lrn(pool1, 5, bias=1.0, alpha=0.001 / 9.0, beta=0.75,name='norm1') #局部响应归一化函数 \n \n tf.summary.histogram('norm1', norm1)\n print ('norm1',norm1) #32*16\n \n \n # =============================================\n with tf.variable_scope('conv2') as scope:\n kernel = _variable_with_weight_decay('weights',shape=[3, 3, 32, 48],stddev=0.1,wd=0.00)\n conv = tf.nn.conv2d(norm1, kernel, [1, 1, 1, 1], padding='SAME')\n biases = _variable_on_cpu('biases', [48], tf.constant_initializer(0.1))\n conv2 = tf.nn.bias_add(conv, biases)\n print ('conv2',conv2)\n #_activation_summary(conv2)\n relu2 = tf.nn.relu(conv2, name=scope.name)\n pool2 = tf.nn.max_pool(relu2, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME', name='pool2') \n norm2 = tf.nn.lrn(pool2, 5, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm2')\n tf.summary.histogram('norm2', norm2)\n print ('norm2',norm2) #8*8\n\n # ======================================\n with tf.variable_scope('conv3') as scope:\n kernel = _variable_with_weight_decay('weights',shape=[3, 3, 48, 64],stddev=0.1,wd=0.0)\n conv = tf.nn.conv2d(norm2, kernel, [1, 1, 1, 1], padding='SAME')\n biases = _variable_on_cpu('biases', [64], tf.constant_initializer(0.1))\n conv3 = tf.nn.bias_add(conv, biases)\n print ('conv3',conv3)\n #_activation_summary(conv2)\n relu3 = tf.nn.relu(conv3, name=scope.name)\n pool3 = tf.nn.max_pool(relu3, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME', name='pool3') \n norm3 = tf.nn.lrn(pool3, 5, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm3')\n #pool3 = tf.nn.dropout(pool3, keep_prob)\n print ('norm3',norm3) #4*4\n \n # ======================================\n with tf.variable_scope('conv4') as scope:\n kernel = _variable_with_weight_decay('weights',shape=[3, 3, 64, 64],stddev=0.1,wd=0.0)\n conv = tf.nn.conv2d(norm3, kernel, [1, 1, 1, 1], padding='SAME')\n biases = _variable_on_cpu('biases', [64], tf.constant_initializer(0.1))\n conv4 = tf.nn.bias_add(conv, biases)\n print ('conv4',conv4)\n #_activation_summary(conv2)\n relu4 = tf.nn.relu(conv4, name=scope.name)\n pool4 = tf.nn.max_pool(relu4, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME', name='pool3') \n norm4 = tf.nn.lrn(pool4, 5, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm3')\n #pool3 = tf.nn.dropout(pool3, keep_prob)\n print ('norm4',norm4) #4*2\n \n # ======================================\n with tf.variable_scope('fc101') as scope:\n # Move everything into depth so we can perform a single matrix multiply.\n reshape = tf.reshape(norm4, [FLAGS.batch_size, -1])\n dim = reshape.get_shape()[1].value\n print ('reshape',reshape)\n print ('dim',dim)\n weights = _variable_with_weight_decay('weights', shape=[4*2*64, 512],stddev=1/512.0, wd=0.0000)\n biases = _variable_on_cpu('biases', [512], tf.constant_initializer(0.0))\n reshape = tf.reshape(norm4, [-1, weights.get_shape().as_list()[0]]) \n relu101 = tf.nn.relu(tf.matmul(reshape, weights) + biases, name=scope.name)\n drop101 = tf.nn.dropout(relu101, keep_prob)\n tf.summary.histogram('relu101', relu101)\n print ('relu101',relu101)\n #_activation_summary(local3) \n \n # ====================================== \n# with tf.variable_scope('fc102') as scope:\n# weights = _variable_with_weight_decay('weights', shape=[256, 256],stddev=1/256.0, wd=0.0000)\n# biases = _variable_on_cpu('biases', [256], tf.constant_initializer(0.0))\n# relu102 = tf.nn.relu(tf.matmul(drop101, weights) + biases, name=scope.name)\n# drop102 = tf.nn.dropout(relu102, keep_prob) \n# print ('relu102',relu102)\n\n \n # ======================================\n with tf.variable_scope('softmax_linear') as scope:\n weights = _variable_with_weight_decay('weights', [512, MAX_CAPTCHA*CHAR_SET_LEN],stddev=1/512.0, wd=0.0)\n biases = _variable_on_cpu('biases', [MAX_CAPTCHA*CHAR_SET_LEN],tf.constant_initializer(0.0))\n softmax_linear = tf.add(tf.matmul(drop101, weights), biases, name=scope.name)\n tf.summary.histogram('softmax_linear', softmax_linear)\n #_activation_summary(softmax_linear)\n\n #out = tf.nn.softmax(out) \n return softmax_linear \n\ndef loss_fun(logits, labels):\n #labels = tf.to_int64(labels)\n cross_entropy=tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels)\n cross_entropy_mean=tf.reduce_mean(cross_entropy)\n tf.add_to_collection('losses', cross_entropy_mean)\n #return cross_entropy_mean #实现一个列表的元素的相加\n return tf.add_n(tf.get_collection('losses'), name='total_loss') #实现一个列表的元素的相加\n\n\ndef evaluation(logits, labels):\n max_idx_p = tf.argmax(tf.reshape(logits, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2) \n max_idx_l = tf.argmax(tf.reshape(labels, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2) \n eval_correct=tf.equal(max_idx_p, max_idx_l) \n return tf.reduce_mean(tf.cast(eval_correct, tf.float32)) \n\ndef training(loss,global_step):\n \n # Decay the learning rate exponentially based on the number of steps.\n lr = tf.train.exponential_decay(FLAGS.Initial_learning_rate, #0.01\n global_step, #0\n int(FLAGS.train_size/FLAGS.batch_size), #136500\n 0.96, #0.1\n staircase=False)\n \n tf.summary.scalar('learning_rate', lr)\n \n\n train_op = tf.train.AdamOptimizer(lr).minimize(loss) \n# print \"train_op:\",train_op\n return train_op,lr\n" }, { "alpha_fraction": 0.7135134935379028, "alphanum_fraction": 0.745945930480957, "avg_line_length": 45.25, "blob_id": "e0c988deec35a52696d991157786702c42a11be5", "content_id": "fd61bb3d078159c685d177a5acc59f1002b8b5a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 253, "license_type": "no_license", "max_line_length": 66, "num_lines": 4, "path": "/README.txt", "repo_name": "LiJianfei06/tensorflow_projects", "src_encoding": "UTF-8", "text": "tfrecord_test: \t\ttfrecord 测试\nsave_test: \t\tsaver 测试\nalphabet_tfrecord: \t识别62个字符(0-9,a-z,A-Z) 支持tfrecord;支持saver 断点续训练\ncaptcha_tfrecord: \t识别四位验证码(0-9,a-z,A-Z) 支持tfrecord;支持saver 断点续训练\n" } ]
14
lsheiba/caffe2-python
https://github.com/lsheiba/caffe2-python
ba799a3be55e3157bd1ce0908a1015fa5171b9e2
90fc07a78a919702a11af11ad482477e24248dc4
de457bd570f8e21f34a47b7caac579b507c1ea03
refs/heads/master
2020-06-26T13:26:45.972632
2017-07-13T01:26:41
2017-07-13T01:26:41
97,024,057
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5766590237617493, "alphanum_fraction": 0.5812357068061829, "avg_line_length": 20.850000381469727, "blob_id": "0fb40c9a821cc8b19e53714d441166175f506ceb", "content_id": "5b73168c207c8e8fa025b3a3c26a685c7e5d6fe2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 437, "license_type": "no_license", "max_line_length": 80, "num_lines": 20, "path": "/main.py", "repo_name": "lsheiba/caffe2-python", "src_encoding": "UTF-8", "text": "# ==============================================================================\n\n\"\"\"\n\"\"\"\n# Disable linter warnings to maintain consistency with tutorial.\n# pylint: disable=invalid-name\n# pylint: disable=g-bad-import-order\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport sys\nimport os\n\nimport caffe2 as c2\n\nif __name__ == '__main__':\n tf.app.run()\n" }, { "alpha_fraction": 0.6875, "alphanum_fraction": 0.75, "avg_line_length": 15, "blob_id": "20ddaeedce7d13003b4cb0f46b350f0b807b3262", "content_id": "f27c90f5553973d988d5212a0c045150387703d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 16, "license_type": "no_license", "max_line_length": 15, "num_lines": 1, "path": "/README.md", "repo_name": "lsheiba/caffe2-python", "src_encoding": "UTF-8", "text": "# caffe2-python\n" } ]
2
ricEsco/pythonoise
https://github.com/ricEsco/pythonoise
feb30668dfe6efcec526d5dd25cbb99690f51823
0ea628f4d47a34803dbf647bd57bbe87fa107509
e22f5220c7782c1cabe9f9627b40b819530465e6
refs/heads/master
2022-06-11T07:31:28.238314
2020-05-03T05:03:30
2020-05-03T05:03:30
259,097,359
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.7953668236732483, "alphanum_fraction": 0.7953668236732483, "avg_line_length": 42.16666793823242, "blob_id": "98eff09affa64cc8260c71740fe442780bee1b7e", "content_id": "e85ad6f4b2259caa40c74f3a5dd7b814d7de2b37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 259, "license_type": "no_license", "max_line_length": 109, "num_lines": 6, "path": "/README.md", "repo_name": "ricEsco/pythonoise", "src_encoding": "UTF-8", "text": "# pythonoise\nMain goal of this project is to get aquainted with the MIDIUtil library that creates MIDI files using python.\n\nThis is a stepping-stone project towards the goal of creating pseudo-randomly generated music using PDF's.\n\nWe'll see how that goes...\n" }, { "alpha_fraction": 0.5632860660552979, "alphanum_fraction": 0.6350013613700867, "avg_line_length": 36.747474670410156, "blob_id": "7391dcfcf0919d8adced4b49f1f0bb99636b54cb", "content_id": "18f1b6505317cd76a780fbac6ab19bb373a98921", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3737, "license_type": "no_license", "max_line_length": 175, "num_lines": 99, "path": "/MyFirstSong.py", "repo_name": "ricEsco/pythonoise", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom midiutil import MIDIFile\n\n# Defining variables -----------------------------------------------------------------------------\nch2 = [68, 71, 68, 71, 69, 71, 69, 71, 69, 71, 69, 71, 68, 71, 68, 71, 68, 76, 71, 76, 75, 81, 71, 75, 71, 76, 68, 71, 69, 71, 69, 71, 69, 71, 69, 71, 68, 71, 68, 71, 68]\nch1 = [73, 75, 73, 75, 73, 75, 73, 75]\nch0A = [80, 80, 78]\nch0B = [81, 81, 80]\nch0C = [83, 81, 80, 75, 76]\nch0D = [80, 80, 78]\ntrack = 0\nchannel = 0\ntime = 0 # In beats\nduration = 1 # In beats\nqnote = 1 # quarter note\nenote = 0.5 # eigth note\nsnote = 0.25 # sixteenth note\ntempo = 36 # Integer in BPM\nvolume = 100\n\n# MIDIFile() creates the midi file ---------------------------------------------------------------\n# removeDuplicates -> If set to True (the default), duplicate notes will be removed from the file.\nmf = MIDIFile(1, removeDuplicates=False)\n# MIDIFileArgs:(numTracks=1, removeDuplicates=True, deinterleave=True, adjust_origin=False, file_format=1, ticks_per_quarternote=960, eventtime_is_ticks=False)\n\n# Adds the tempo to the file\nmf.addTempo(track, time, tempo)\n# TempoArgs:(track, time, tempo)\n\n# ProgramChange -> Change the voice (instrument) of the pitch\n# Have to do it for each channel being used and they can be different\nmf.addProgramChange(track, 0, time, 0)\nmf.addProgramChange(track, 1, time, 0)\nmf.addProgramChange(track, 2, time, 0)\n# ProgramChangeArgs:(track, channel, time, program)\n\n# ControllerChange -> Controls various dynamics of pitch .i.e. mod wheel(1), pan(10), and sustain(64)\nmf.addControllerEvent(track, 0, time, 10, 0)\nmf.addControllerEvent(track, 1, time, 10, 0)\nmf.addControllerEvent(track, 2, time, 10, 127)\n# ControllerEventArgs(track, channel, time, controller_number, parameter)\n\n# Start adding music notes -----------------------------------------------------\ntime = 0\n# Beginning note is a dotted quarter note\nmf.addNote(track, 0, 71, time + 0.5, enote, volume)\n# NoteArgs:(track,channel, pitch, time, duration, volume, annotation=None)\n\n# Begin the following notes after the dotted quarter note\ntime = 1\n# Channel 2 notes are lowest notes\nfor i, pitch in enumerate(ch2):\n mf.addNote(track, 2, pitch, time, snote, volume)\n time += snote\n\n# Restart time to overlay notes of different channels\ntime = 1\n# Channel 1 notes are middle notes\nmf.addNote(track, 1, 75, 2 , qnote, volume)\nmf.addNote(track, 1, 75, 3.5, snote, volume)\nmf.addNote(track, 1, 76, 4 , snote, volume)\ntime = 8\nfor i, pitch in enumerate(ch1):\n mf.addNote(track, 1, pitch, time, snote, volume)\n time += snote\n\n# Restart time to overlay notes of different channels\ntime = 1\n# Channel 0 notes are highest notes\nmf.addNote(track, 0, 76, time, qnote, volume)\nmf.addNote(track, 0, 75, 1.5 , snote, volume)\nmf.addNote(track, 0, 76, 1.75, snote, volume)\nmf.addNote(track, 0, 78, 2 , qnote, volume)\ntime = 3.25\nfor i, pitch in enumerate(ch0A):\n mf.addNote(track, 0, pitch, time, snote, volume)\n time += snote\nmf.addNote(track, 0, 80, 4 , qnote, volume)\ntime = 5.25\nfor i, pitch in enumerate(ch0B):\n mf.addNote(track, 0, pitch, time, snote, volume)\n time += snote\nmf.addNote(track, 0, 85, 6 , 0.75 , volume)\ntime = 6.75\nfor i, pitch in enumerate(ch0C):\n mf.addNote(track, 0, pitch, time, qnote, volume)\n time += snote\nmf.addNote(track, 0, 78, 8 , qnote, volume)\ntime = 9.25\nfor i, pitch in enumerate(ch0D):\n mf.addNote(track, 0, pitch, time, snote, volume)\n time += snote\nmf.addNote(track, 0, 76, 10 , qnote, volume)\n\n# Finally, write the file to a file object -----------\nwith open(\"tristesseV4.mid\", \"wb\") as output_file:\n mf.writeFile(output_file)\n#Args: (fileHandle)\n" } ]
2
jangley/qcoffin
https://github.com/jangley/qcoffin
189a53c136d9a4122694c49f495108219463cdba
08a80b5bd1c21dd53293899eb409e4da340f8f70
0f0f7fc8373cc3a4ad9f7f7ce22f5c6e877d05ca
refs/heads/master
2020-02-25T11:24:05.897536
2015-02-07T19:44:14
2015-02-07T19:44:14
30,466,063
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6461716890335083, "alphanum_fraction": 0.6473317742347717, "avg_line_length": 28.724138259887695, "blob_id": "04c710496a62e8c9ffec655bae70fc04aa97fefe", "content_id": "099c2cc5d1497f2c50040d7663e2a7f32e1de047", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 862, "license_type": "permissive", "max_line_length": 94, "num_lines": 29, "path": "/coffin/contrib/flatpages/context.py", "repo_name": "jangley/qcoffin", "src_encoding": "UTF-8", "text": "# coding=utf-8\nfrom django.conf import settings\nfrom django.contrib.flatpages.models import FlatPage\nfrom coffin.common import env\n\n\ndef get_flatpages(starts_with=None, user=None, site_id=None):\n \"\"\"\n Context-function similar to get_flatpages tag in Django templates.\n\n Usage:\n <ul>\n {% for page in get_flatpages(starts_with='/about/', user=user, site_id=site.pk) %}\n <li><a href=\"{{ page.url }}\">{{ page.title }}</a></li>\n {% endfor %}\n </ul>\n\n \"\"\"\n flatpages = FlatPage.objects.filter(sites__id=site_id or settings.SITE_ID)\n\n if starts_with:\n flatpages = flatpages.filter(url__startswith=starts_with)\n\n if not user or not user.is_authenticated():\n flatpages = flatpages.filter(registration_required=False)\n\n return flatpages\n\nenv.globals['get_flatpages'] = get_flatpages\n" }, { "alpha_fraction": 0.7027027010917664, "alphanum_fraction": 0.7297297120094299, "avg_line_length": 17.5, "blob_id": "4148ba20b51cfd17d34887a3db3c1c99cdaa2d9d", "content_id": "91f61c11d54bb5eacea14dbc18ae7bd45302ff36", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 37, "license_type": "permissive", "max_line_length": 21, "num_lines": 2, "path": "/coffin/contrib/flatpages/__init__.py", "repo_name": "jangley/qcoffin", "src_encoding": "UTF-8", "text": "# coding=utf-8\nfrom . import context\n" } ]
2
darcwader/sdcn_p4_advanced_lane_finding
https://github.com/darcwader/sdcn_p4_advanced_lane_finding
ec7c344ed1429acf3e6e152d2543ab4b080de48a
44a243df91e6eabe417ffd12754867f52f6dcc1f
39cbc9f80e51bacae4b9ed3df31becdccfccc07e
refs/heads/master
2021-01-17T08:37:14.494464
2017-03-09T21:52:21
2017-03-09T21:52:21
83,941,330
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5716311931610107, "alphanum_fraction": 0.6056737303733826, "avg_line_length": 23.310344696044922, "blob_id": "54968fa18a4f9781ddc7941dc13e6be192450a45", "content_id": "95faa9bc5e1465b9d472f281ef8b079738469002", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 705, "license_type": "no_license", "max_line_length": 52, "num_lines": 29, "path": "/lane.py", "repo_name": "darcwader/sdcn_p4_advanced_lane_finding", "src_encoding": "UTF-8", "text": "from methods import *\nfrom slidingwindow import *\n\nl = Lane()\n\ndef frame(img):\n binary_warped = l.sliding_window(img)\n\n warp = fast_warp_lane(binary_warped)\n\n out = cv2.addWeighted(img, 1.0, warp, 0.5, 0)\n return out\n\ndef frame_convolution(img):\n res = apply_thresholds(img)\n res_rgb = np.dstack((res*255, res*255, res*255))\n lane = fast_unwarp_lane(res_rgb)\n unwarp = convolution(lane[:,:,0])\n warp = fast_warp_lane(unwarp)\t\n\n out = cv2.addWeighted(img, 1.0, warp, 0.5, 0)\n\nif __name__ == \"__main__\":\n inp = \"project_small\"\n #inp = \"project_video\"\n\n process_video(infile=inp + \".mp4\", \n outfile=inp + \"_final.mp4\", \n method=frame_convolution)\n" }, { "alpha_fraction": 0.6860068440437317, "alphanum_fraction": 0.7064846158027649, "avg_line_length": 25.545454025268555, "blob_id": "5bca8114704669438f37d55045f0919885b379c1", "content_id": "06f7ed4210e3506ec5d78c26ebc143dce591ac2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 293, "license_type": "no_license", "max_line_length": 76, "num_lines": 11, "path": "/run_1b_undistort.py", "repo_name": "darcwader/sdcn_p4_advanced_lane_finding", "src_encoding": "UTF-8", "text": "from methods import *\nimport cv2\n\n#load calibration\nmtx, dist = load_calibration()\n\ntest_image = cv2.imread('test_images/test4.jpg')\ntest_image = test_image[..., ::-1]\nundist = cv2.undistort(test_image, mtx, dist)\n\nplot_images_save('output_images/1b_undistort.png', [ [test_image, undist] ])\n\n" }, { "alpha_fraction": 0.7106534838676453, "alphanum_fraction": 0.7299085855484009, "avg_line_length": 70.1693115234375, "blob_id": "4858bd45fc2db38a761a827965f5d0be34940555", "content_id": "5159fe147d4b3dab560cc586a6d333886f3e5ab5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 13451, "license_type": "no_license", "max_line_length": 577, "num_lines": 189, "path": "/writeup.html", "repo_name": "darcwader/sdcn_p4_advanced_lane_finding", "src_encoding": "UTF-8", "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n <meta http-equiv=\"Content-Style-Type\" content=\"text/css\" />\n <meta name=\"generator\" content=\"pandoc\" />\n <title></title>\n <style type=\"text/css\">code{white-space: pre;}</style>\n</head>\n<body>\n<p><strong>Advanced Lane Finding Project</strong></p>\n<p>The goals / steps of this project are the following:</p>\n<ul>\n<li>Compute the camera calibration matrix and distortion coefficients given a set of chessboard images.</li>\n<li>Apply a distortion correction to raw images.</li>\n<li>Use color transforms, gradients, etc., to create a thresholded binary image.</li>\n<li>Apply a perspective transform to rectify binary image (&quot;birds-eye view&quot;).</li>\n<li>Detect lane pixels and fit to find the lane boundary.</li>\n<li>Determine the curvature of the lane and vehicle position with respect to center.</li>\n<li>Warp the detected lane boundaries back onto the original image.</li>\n<li>Output visual display of the lane boundaries and numerical estimation of lane curvature and vehicle position.</li>\n</ul>\n<h2 id=\"rubric-points\"><a href=\"https://review.udacity.com/#!/rubrics/571/view\">Rubric</a> Points</h2>\n<h3 id=\"here-i-will-consider-the-rubric-points-individually-and-describe-how-i-addressed-each-point-in-my-implementation.\">Here I will consider the rubric points individually and describe how I addressed each point in my implementation.</h3>\n<h3 id=\"writeup-readme\">Writeup / README</h3>\n<h4 id=\"provide-a-writeup-readme-that-includes-all-the-rubric-points-and-how-you-addressed-each-one.-you-can-submit-your-writeup-as-markdown-or-pdf.-here-is-a-template-writeup-for-this-project-you-can-use-as-a-guide-and-a-starting-point.\">1. Provide a Writeup / README that includes all the rubric points and how you addressed each one. You can submit your writeup as markdown or pdf. <a href=\"https://github.com/udacity/CarND-Advanced-Lane-Lines/blob/master/writeup_template.md\">Here</a> is a template writeup for this project you can use as a guide and a starting point.</h4>\n<h3 id=\"camera-calibration\">Camera Calibration</h3>\n<h4 id=\"briefly-state-how-you-computed-the-camera-matrix-and-distortion-coefficients.-provide-an-example-of-a-distortion-corrected-calibration-image.\">1. Briefly state how you computed the camera matrix and distortion coefficients. Provide an example of a distortion corrected calibration image.</h4>\n<p>The code for this is in <code>calibrate.py</code>. this saves the calibration to a pickle file. method to load is in <code>methods.py</code> along with other helper routines.</p>\n<p>First all points are created using <code>np.mgrid</code> and <code>cv2.findChessboardCorners</code> is called on each image in <code>camera_cal/*.jpg</code> files.</p>\n<p>All points are then collected into <code>objpoints</code> and <code>imgpoints</code>. the images are also plotted to show make sure it finds everything properly.</p>\n<h3 id=\"pipeline-single-images\">Pipeline (single images)</h3>\n<h4 id=\"provide-an-example-of-a-distortion-corrected-image.\">1. Provide an example of a distortion-corrected image.</h4>\n<p>To test if this is fine run <code>run_1_undistort.py</code> is run which saves file into <code>output_images/1_undistor.py</code></p>\n<div class=\"figure\">\n<img src=\"./output_images/1_undistorted.png\" title=\"Undistorted\" alt=\"Undistorted\" />\n<p class=\"caption\">Undistorted</p>\n</div>\n<p>Apply to a lane image to undistort</p>\n<div class=\"figure\">\n<img src=\"./output_images/1b_undistort.png\" title=\"Sample Undistorted\" alt=\"Alt text\" />\n<p class=\"caption\">Alt text</p>\n</div>\n<h4 id=\"describe-how-and-identify-where-in-your-code-you-used-color-transforms-gradients-or-other-methods-to-create-a-thresholded-binary-image.-provide-an-example-of-a-binary-image-result.\">2. Describe how (and identify where in your code) you used color transforms, gradients or other methods to create a thresholded binary image. Provide an example of a binary image result.</h4>\n<p><em>Transform</em></p>\n<p><code>methods.py</code> contains function <code>load_transforms</code> which loads transform matrix. <code>fast_unwarp_lane</code> and <code>fast_warp_lane</code> then use the loaded matrix to perform the warp and unwarping.</p>\n<p><em>Thresholding</em></p>\n<p>This was the hardest part of the entire project, took weeks.</p>\n<p>Unsuccessful tries:</p>\n<ul>\n<li>I tried sobel x filter , sobel y filter, xy filter, dir filter on RGB image. Although it went well on image, further down the pipeline this failed badly.</li>\n<li>I used HSV color space and it produced nice results along with sobelx, xy, dir in RGB space. but realized it also failed in some cases.</li>\n</ul>\n<p>Successful</p>\n<ul>\n<li>I took some snapshots of track and applied filter on then instead of test images.</li>\n<li>I converted to HSV only, RGB was just not helpful</li>\n<li>on HSV filter out higher thresholds to isolate lane lines</li>\n<li>on HSV filter also apply weights to H, S, V to get some addional information</li>\n<li>threshold the above two to get a binary lane</li>\n</ul>\n<p>Code is in <code>methods.py</code></p>\n<p>I used a combination of color and gradient thresholds to generate a binary image (thresholding steps at lines # through # in <code>another_file.py</code>). Here's an example of my output for this step. (note: this is not actually from one of the test images)</p>\n<p>method that applies the threshold is <code>apply_thresholds</code> and returns a unwarped binary file.</p>\n<div class=\"figure\">\n<img src=\"./output_images/2_threshold.png\" title=\"Theshold\" alt=\"alt text\" />\n<p class=\"caption\">alt text</p>\n</div>\n<h4 id=\"describe-how-and-identify-where-in-your-code-you-performed-a-perspective-transform-and-provide-an-example-of-a-transformed-image.\">3. Describe how (and identify where in your code) you performed a perspective transform and provide an example of a transformed image.</h4>\n<p>The transform is performed by using the folowing</p>\n<pre><code>src = np.float32([[ 585.0-10, 460.0],\n [ 0.0, 720.0],\n [ 1280.0, 720.0],\n [ 695.0+10, 460.0]])\n\ndst = np.float32([[320, 0],\n [320, 720],\n [960, 720],\n [960, 0]])</code></pre>\n<p>This resulted in the following source and destination points:</p>\n<table>\n<thead>\n<tr class=\"header\">\n<th align=\"center\">Source</th>\n<th align=\"center\">Destination</th>\n</tr>\n</thead>\n<tbody>\n<tr class=\"odd\">\n<td align=\"center\">575.0, 460</td>\n<td align=\"center\">320, 0</td>\n</tr>\n<tr class=\"even\">\n<td align=\"center\">0, 720</td>\n<td align=\"center\">320, 720</td>\n</tr>\n<tr class=\"odd\">\n<td align=\"center\">1280, 720</td>\n<td align=\"center\">960, 720</td>\n</tr>\n<tr class=\"even\">\n<td align=\"center\">705.0, 460</td>\n<td align=\"center\">960, 0</td>\n</tr>\n</tbody>\n</table>\n<p>I verified that my perspective transform was working as expected. here is the warped lane drawing.</p>\n<div class=\"figure\">\n<img src=\"./output_images/3_warping.png\" title=\"Warping\" alt=\"alt text\" />\n<p class=\"caption\">alt text</p>\n</div>\n<h4 id=\"describe-how-and-identify-where-in-your-code-you-identified-lane-line-pixels-and-fit-their-positions-with-a-polynomial\">4. Describe how (and identify where in your code) you identified lane-line pixels and fit their positions with a polynomial?</h4>\n<p>the code for lane and all details are in <code>methods_sliding_window.py</code></p>\n<p>we have a <code>Lane</code> class.</p>\n<p>In this we find the lane lines by using histogram of thresolded image. We find the base by finding the max</p>\n<pre><code>leftx_base = np.argmax(histogram[:midpoint])\nrightx_base = np.argmax(histogram[midpoint:]) + midpoint</code></pre>\n<p>Then we divide into small strips and calculate the highest values in within a certain margin.</p>\n<p>resulting windows if plotted would show.</p>\n<div class=\"figure\">\n<img src=\"./output_images/4_process.png\" title=\"Sliding Window\" alt=\"alt text\" />\n<p class=\"caption\">alt text</p>\n</div>\n<p>This is only done for the first frame.</p>\n<p>Successive frames we use <code>sliding_next</code> methods in <code>Lane</code> class. Which uses the previous fits to calculate the next frames.</p>\n<pre><code>nonzero = binary_warped.nonzero()\nnonzeroy = np.array(nonzero[0])\nnonzerox = np.array(nonzero[1])\nmargin = 100\nself.left.lane_inds = ((nonzerox &gt; (self.left.current_fit[0]*(nonzeroy**2) + self.left.current_fit[1]*nonzeroy + self.left.current_fit[2] - margin)) &amp; (nonzerox &lt; (self.left.current_fit[0]*(nonzeroy**2) + self.left.current_fit[1]*nonzeroy + self.left.current_fit[2] + margin)))\nself.right.lane_inds = ((nonzerox &gt; (self.right.current_fit[0]*(nonzeroy**2) + self.right.current_fit[1]*nonzeroy + self.right.current_fit[2] - margin)) &amp; (nonzerox &lt; (self.right.current_fit[0]*(nonzeroy**2) + self.right.current_fit[1]*nonzeroy + self.right.current_fit[2] + margin))) \n\n# Again, extract left and right line pixel positions\nleftx = nonzerox[self.left.lane_inds]\nlefty = nonzeroy[self.left.lane_inds]\nrightx = nonzerox[self.right.lane_inds]\nrighty = nonzeroy[self.right.lane_inds]\n# Fit a second order polynomial to each\nself.left.current_fit = np.polyfit(lefty, leftx, 2)\nself.right.current_fit = np.polyfit(righty, rightx, 2)</code></pre>\n<h4 id=\"describe-how-and-identify-where-in-your-code-you-calculated-the-radius-of-curvature-of-the-lane-and-the-position-of-the-vehicle-with-respect-to-center.\">5. Describe how (and identify where in your code) you calculated the radius of curvature of the lane and the position of the vehicle with respect to center.</h4>\n<p>radius of curvature is calculated using <code>draw_curvature</code> methods in <code>Lane</code> class.</p>\n<pre><code>y_eval = np.max(img.shape[0]-1)\nleft_curverad = ((1 + (2*self.left.current_fit[0]*y_eval + self.left.current_fit[1])**2)**1.5) / np.absolute(2*self.left.current_fit[0])\nright_curverad = ((1 + (2*self.right.current_fit[0]*y_eval + self.right.current_fit[1])**2)**1.5) / np.absolute(2*self.right.current_fit[0])\n\nploty = np.linspace(0, img.shape[0]-1, img.shape[0] )\nleftx = self.left.current_fit[0]*ploty**2 + self.left.current_fit[1]*ploty + self.left.current_fit[2]\nrightx = self.right.current_fit[0]*ploty**2 + self.right.current_fit[1]*ploty + self.right.current_fit[2]\n\n# Define conversions in x and y from pixels space to meters\nym_per_pix = 30/720 # meters per pixel in y dimension\nxm_per_pix = 3.7/700 # meters per pixel in x dimension\n\n# Fit new polynomials to x,y in world space\nleft_fit_cr = np.polyfit(ploty*ym_per_pix, leftx*xm_per_pix, 2)\nright_fit_cr = np.polyfit(ploty*ym_per_pix, rightx*xm_per_pix, 2)\n\n# Calculate the new radii of curvature\nself.left.radius_of_curvature = ((1 + (2*left_fit_cr[0]*y_eval*ym_per_pix + left_fit_cr[1])**2)**1.5) / np.absolute(2*left_fit_cr[0])\nself.right.radius_of_curvature = ((1 + (2*right_fit_cr[0]*y_eval*ym_per_pix + right_fit_cr[1])**2)**1.5) / np.absolute(2*right_fit_cr[0])</code></pre>\n<h4 id=\"provide-an-example-image-of-your-result-plotted-back-down-onto-the-road-such-that-the-lane-area-is-identified-clearly.\">6. Provide an example image of your result plotted back down onto the road such that the lane area is identified clearly.</h4>\n<p>This is done in <code>draw_projection</code> in <code>Lane</code> class from <code>methods_sliding_window.py</code></p>\n<div class=\"figure\">\n<img src=\"./output_images/6_lane.png\" title=\"Projection\" alt=\"alt text\" />\n<p class=\"caption\">alt text</p>\n</div>\n<hr />\n<h3 id=\"pipeline-video\">Pipeline (video)</h3>\n<h4 id=\"provide-a-link-to-your-final-video-output.-your-pipeline-should-perform-reasonably-well-on-the-entire-project-video-wobbly-lines-are-ok-but-no-catastrophic-failures-that-would-cause-the-car-to-drive-off-the-road.\">1. Provide a link to your final video output. Your pipeline should perform reasonably well on the entire project video (wobbly lines are ok but no catastrophic failures that would cause the car to drive off the road!).</h4>\n<p>There are few measures taken to make the lane detection robust.</p>\n<ol style=\"list-style-type: decimal\">\n<li>The lane is smoothed over last_n = 5 good fits.</li>\n<li>New coefficients are calcualated based on current_fit and then we calculate root mean square error with previous_fit</li>\n<li>if the error is too high then we take up previous_fit and drop this current_fit</li>\n</ol>\n<p>Here's a <a href=\"./output_images/project_video_final.mp4\">link to my video result</a></p>\n<hr />\n<h3 id=\"discussion\">Discussion</h3>\n<h4 id=\"briefly-discuss-any-problems-issues-you-faced-in-your-implementation-of-this-project.-where-will-your-pipeline-likely-fail-what-could-you-do-to-make-it-more-robust\">1. Briefly discuss any problems / issues you faced in your implementation of this project. Where will your pipeline likely fail? What could you do to make it more robust?</h4>\n<ul>\n<li>the lane lines histogram can fail if the curvature is too high.</li>\n<li>brightness vairations are not recorded well</li>\n<li>the the surface of road is more brighter the thresholding can fail and not find the lanes</li>\n<li>average of lane lines might not be good enough fit.</li>\n<li>the left and right lane movement is not related in my algorithm. convolution was a better method, maybe that should be adopted for better performance.</li>\n</ul>\n</body>\n</html>\n" }, { "alpha_fraction": 0.7148289084434509, "alphanum_fraction": 0.73384028673172, "avg_line_length": 25.200000762939453, "blob_id": "2f60c5c8bf0e5b5a61c1e4242fa52eb76f2a2efb", "content_id": "2a09644840f95384786b140396dd27a4f1f1371a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 263, "license_type": "no_license", "max_line_length": 75, "num_lines": 10, "path": "/run_1_undistort.py", "repo_name": "darcwader/sdcn_p4_advanced_lane_finding", "src_encoding": "UTF-8", "text": "from methods import *\nimport cv2\n\n#load calibration\nmtx, dist = load_calibration()\n\ntest_image = cv2.imread('camera_cal/calibration1.jpg')\nundist = cv2.undistort(test_image, mtx, dist)\n\nplot_images_save('output_images/1_undistort.png', [ [test_image, undist] ])\n\n" }, { "alpha_fraction": 0.6979144215583801, "alphanum_fraction": 0.7217802405357361, "avg_line_length": 44.135921478271484, "blob_id": "aad2c3633039d89485182466a47e8fd105e78f6e", "content_id": "7241b15b0c9f91e03e4251b9201597ed6527ec2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9302, "license_type": "no_license", "max_line_length": 331, "num_lines": 206, "path": "/writeup_template.md", "repo_name": "darcwader/sdcn_p4_advanced_lane_finding", "src_encoding": "UTF-8", "text": "\n**Advanced Lane Finding Project**\n\nThe goals / steps of this project are the following:\n\n* Compute the camera calibration matrix and distortion coefficients given a set of chessboard images.\n* Apply a distortion correction to raw images.\n* Use color transforms, gradients, etc., to create a thresholded binary image.\n* Apply a perspective transform to rectify binary image (\"birds-eye view\").\n* Detect lane pixels and fit to find the lane boundary.\n* Determine the curvature of the lane and vehicle position with respect to center.\n* Warp the detected lane boundaries back onto the original image.\n* Output visual display of the lane boundaries and numerical estimation of lane curvature and vehicle position.\n\n[//]: # (Image References)\n\n[image1]: ./output_images/1_undistorted.png \"Undistorted\"\n[image2]: ./output_images/2_threshold.png \"Theshold\"\n[image3]: ./output_images/3_warping.png \"Warping\"\n[image4]: ./output_images/4_process.png \"Sliding Window\"\n[image6]: ./output_images/6_lane.png \"Projection\"\n\n## [Rubric](https://review.udacity.com/#!/rubrics/571/view) Points\n### Here I will consider the rubric points individually and describe how I addressed each point in my implementation. \n\n### Writeup / README\n\n#### 1. Provide a Writeup / README that includes all the rubric points and how you addressed each one. You can submit your writeup as markdown or pdf. [Here](https://github.com/udacity/CarND-Advanced-Lane-Lines/blob/master/writeup_template.md) is a template writeup for this project you can use as a guide and a starting point. \n\n### Camera Calibration\n\n#### 1. Briefly state how you computed the camera matrix and distortion coefficients. Provide an example of a distortion corrected calibration image.\n\nThe code for this is in `calibrate.py`. this saves the calibration to a pickle file.\nmethod to load is in `methods.py` along with other helper routines. \n\nFirst all points are created using `np.mgrid` and `cv2.findChessboardCorners` is called on each image in `camera_cal/*.jpg` files.\n\nAll points are then collected into `objpoints` and `imgpoints`. the images are also plotted to show make sure it finds everything properly.\n\n\n### Pipeline (single images)\n\n#### 1. Provide an example of a distortion-corrected image.\n\nTo test if this is fine run `run_1_undistort.py` is run which saves file into `output_images/1_undistor.py`\n\n![Undistorted][image1]\n\n#### 2. Describe how (and identify where in your code) you used color transforms, gradients or other methods to create a thresholded binary image. Provide an example of a binary image result.\n\n*Transform*\n\n`methods.py` contains function `load_transforms` which loads transform matrix. `fast_unwarp_lane` and `fast_warp_lane` then use the loaded matrix to perform the warp and unwarping.\n\n\n*Thresholding* \n\nThis was the hardest part of the entire project, took weeks. \n\nUnsuccessful tries: \n\n * I tried sobel x filter , sobel y filter, xy filter, dir filter on RGB image. Although it went well on image, further down the pipeline this failed badly.\n * I used HSV color space and it produced nice results along with sobelx, xy, dir in RGB space. but realized it also failed in some cases.\n\nSuccessful\n\n * I took some snapshots of track and applied filter on then instead of test images.\n * I converted to HSV only, RGB was just not helpful\n * on HSV filter out higher thresholds to isolate lane lines\n * on HSV filter also apply weights to H, S, V to get some addional information\n * threshold the above two to get a binary lane\n\nCode is in `methods.py`\n\n\nI used a combination of color and gradient thresholds to generate a binary image (thresholding steps at lines # through # in `another_file.py`). Here's an example of my output for this step. (note: this is not actually from one of the test images)\n\nmethod that applies the threshold is `apply_thresholds` and returns a unwarped binary file.\n\n![alt text][image2]\n\n#### 3. Describe how (and identify where in your code) you performed a perspective transform and provide an example of a transformed image.\n\nThe transform is performed by using the folowing\n\n```\nsrc = np.float32([[ 585.0-10, 460.0],\n [ 0.0, 720.0],\n [ 1280.0, 720.0],\n [ 695.0+10, 460.0]])\n\ndst = np.float32([[320, 0],\n [320, 720],\n [960, 720],\n [960, 0]])\n```\n\nThis resulted in the following source and destination points:\n\n| Source | Destination | \n|:-------------:|:-------------:| \n| 575.0, 460 | 320, 0 | \n| 0, 720 | 320, 720 |\n| 1280, 720 | 960, 720 |\n| 705.0, 460 | 960, 0 |\n\nI verified that my perspective transform was working as expected. here is the warped lane drawing.\n\n![alt text][image3]\n\n#### 4. Describe how (and identify where in your code) you identified lane-line pixels and fit their positions with a polynomial?\n\nthe code for lane and all details are in `methods_sliding_window.py`\n\nwe have a `Lane` class. \n\nIn this we find the lane lines by using histogram of thresolded image. We find the base by finding the max \n\n```\nleftx_base = np.argmax(histogram[:midpoint])\nrightx_base = np.argmax(histogram[midpoint:]) + midpoint\n```\n\nThen we divide into small strips and calculate the highest values in within a certain margin.\n\nresulting windows if plotted would show.\n\n![alt text][image4]\n\n\nThis is only done for the first frame.\n\nSuccessive frames we use `sliding_next` methods in `Lane` class. Which uses the previous fits to calculate the next frames.\n\n```\nnonzero = binary_warped.nonzero()\nnonzeroy = np.array(nonzero[0])\nnonzerox = np.array(nonzero[1])\nmargin = 100\nself.left.lane_inds = ((nonzerox > (self.left.current_fit[0]*(nonzeroy**2) + self.left.current_fit[1]*nonzeroy + self.left.current_fit[2] - margin)) & (nonzerox < (self.left.current_fit[0]*(nonzeroy**2) + self.left.current_fit[1]*nonzeroy + self.left.current_fit[2] + margin)))\nself.right.lane_inds = ((nonzerox > (self.right.current_fit[0]*(nonzeroy**2) + self.right.current_fit[1]*nonzeroy + self.right.current_fit[2] - margin)) & (nonzerox < (self.right.current_fit[0]*(nonzeroy**2) + self.right.current_fit[1]*nonzeroy + self.right.current_fit[2] + margin))) \n\n# Again, extract left and right line pixel positions\nleftx = nonzerox[self.left.lane_inds]\nlefty = nonzeroy[self.left.lane_inds] \nrightx = nonzerox[self.right.lane_inds]\nrighty = nonzeroy[self.right.lane_inds]\n# Fit a second order polynomial to each\nself.left.current_fit = np.polyfit(lefty, leftx, 2)\nself.right.current_fit = np.polyfit(righty, rightx, 2)\n```\n\n####5. Describe how (and identify where in your code) you calculated the radius of curvature of the lane and the position of the vehicle with respect to center.\n\nradius of curvature is calculated using `draw_curvature` methods in `Lane` class.\n\n```\ny_eval = np.max(img.shape[0]-1)\nleft_curverad = ((1 + (2*self.left.current_fit[0]*y_eval + self.left.current_fit[1])**2)**1.5) / np.absolute(2*self.left.current_fit[0])\nright_curverad = ((1 + (2*self.right.current_fit[0]*y_eval + self.right.current_fit[1])**2)**1.5) / np.absolute(2*self.right.current_fit[0])\n\nploty = np.linspace(0, img.shape[0]-1, img.shape[0] )\nleftx = self.left.current_fit[0]*ploty**2 + self.left.current_fit[1]*ploty + self.left.current_fit[2]\nrightx = self.right.current_fit[0]*ploty**2 + self.right.current_fit[1]*ploty + self.right.current_fit[2]\n\n# Define conversions in x and y from pixels space to meters\nym_per_pix = 30/720 # meters per pixel in y dimension\nxm_per_pix = 3.7/700 # meters per pixel in x dimension\n\n# Fit new polynomials to x,y in world space\nleft_fit_cr = np.polyfit(ploty*ym_per_pix, leftx*xm_per_pix, 2)\nright_fit_cr = np.polyfit(ploty*ym_per_pix, rightx*xm_per_pix, 2)\n\n# Calculate the new radii of curvature\nself.left.radius_of_curvature = ((1 + (2*left_fit_cr[0]*y_eval*ym_per_pix + left_fit_cr[1])**2)**1.5) / np.absolute(2*left_fit_cr[0])\nself.right.radius_of_curvature = ((1 + (2*right_fit_cr[0]*y_eval*ym_per_pix + right_fit_cr[1])**2)**1.5) / np.absolute(2*right_fit_cr[0])\n```\n\n####6. Provide an example image of your result plotted back down onto the road such that the lane area is identified clearly.\n\nThis is done in `draw_projection` in `Lane` class from `methods_sliding_window.py`\n\n![alt text][image6]\n\n---\n\n###Pipeline (video)\n\n####1. Provide a link to your final video output. Your pipeline should perform reasonably well on the entire project video (wobbly lines are ok but no catastrophic failures that would cause the car to drive off the road!).\n\n\nThe lane line is smoothed over 5 best fit's to remove jitters.\n\nHere's a [link to my video result](./output_images/project_video_final.mp4)\n\n---\n\n###Discussion\n\n####1. Briefly discuss any problems / issues you faced in your implementation of this project. Where will your pipeline likely fail? What could you do to make it more robust?\n\n* the lane lines histogram can fail if the curvature is too high. \n* brightness vairations are not recorded well\n* the the surface of road is more brighter the thresholding can fail and not find the lanes\n* average of lane lines might not be good enough fit. \n* the left and right lane movement is not related in my algorithm. convolution was a better method, maybe that should be adopted for better performance.\n\n\n\n" }, { "alpha_fraction": 0.5953437089920044, "alphanum_fraction": 0.6075388193130493, "avg_line_length": 21.9743595123291, "blob_id": "9f1e32a3431592a373e050b83a9af69544e92766", "content_id": "9daf47ab9a33be7b8db08412a30f31f5e0ca010a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 902, "license_type": "no_license", "max_line_length": 56, "num_lines": 39, "path": "/run_6_image.py", "repo_name": "darcwader/sdcn_p4_advanced_lane_finding", "src_encoding": "UTF-8", "text": "from methods import *\nfrom methods_sliding_window import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom moviepy.editor import VideoFileClip\nimport glob\nimport cv2\nimport matplotlib.image as mpimg\n\nlane = Lane()\n\ndef process(img):\n out = lane.sliding_window(img)\n out = fast_warp_lane(out)\n out = cv2.addWeighted(img, 1.0, out, 0.5, 0)\n lane.draw_curvature(out)\n return out\n\n \nif __name__ == \"__main__\":\n \"\"\"\n #inp = \"project_small\"\n inp = \"project_video\"\n\n process_video(infile=inp + \".mp4\", \n outfile=inp + \"_threshold.mp4\", \n method=thresh)\n \"\"\"\n files = glob.glob(\"test_images/test2.jpg\")\n\n print(files)\n images = []\n for ix, fname in enumerate(files):\n img = mpimg.imread(fname)\n \n t = process(img)\n images.append([img, t])\n\n plot_images_save(\"output_images/6_lane.png\", images)\n\n \n" }, { "alpha_fraction": 0.5928338766098022, "alphanum_fraction": 0.6080347299575806, "avg_line_length": 23.078947067260742, "blob_id": "a6496a999bbd1e5da47def02434805e34bb36d0f", "content_id": "6875735767ea6e741936a76a13beb361da7092ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 921, "license_type": "no_license", "max_line_length": 61, "num_lines": 38, "path": "/run_3_warping.py", "repo_name": "darcwader/sdcn_p4_advanced_lane_finding", "src_encoding": "UTF-8", "text": "from methods import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom moviepy.editor import VideoFileClip\nimport glob\nimport cv2\nimport matplotlib.image as mpimg\n\ndef thresh(img, warp=False):\n res = apply_thresholds(img)\n\n binary = np.dstack((res*255, res*255, res*255))\n binary_warped = binary\n if warp == True:\n binary_warped = fast_unwarp_lane(binary)\n return binary_warped\n\n \nif __name__ == \"__main__\":\n \"\"\"\n #inp = \"project_small\"\n inp = \"project_video\"\n\n process_video(infile=inp + \".mp4\", \n outfile=inp + \"_threshold.mp4\", \n method=thresh)\n \"\"\"\n files = glob.glob(\"test_images/test2.jpg\")\n\n print(files)\n images = []\n for ix, fname in enumerate(files):\n img = mpimg.imread(fname)\n \n t = thresh(img, False)\n images.append([img, t])\n\n plot_images_save(\"output_images/2_threshold.png\", images)\n\n \n" }, { "alpha_fraction": 0.6736508011817932, "alphanum_fraction": 0.6939682364463806, "avg_line_length": 30.5, "blob_id": "ef879a7d69dc8bcedacfb2cb78913e1f3f044ad6", "content_id": "b12e75f203ba148460f1c3a32401d0214a3be51f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1575, "license_type": "no_license", "max_line_length": 104, "num_lines": 50, "path": "/calibrate.py", "repo_name": "darcwader/sdcn_p4_advanced_lane_finding", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nimport glob\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport pickle\nimport matplotlib.image as mpimg\nfrom moviepy.editor import VideoFileClip\n\nnx = 9\nny = 6\n\n# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(nx,ny,0)\nobjp = np.zeros((nx*ny,3), np.float32)\nobjp[:,:2] = np.mgrid[0:nx, 0:ny].T.reshape(-1,2)\n\n# Arrays to store object points and image points from all the images.\nobjpoints = [] # 3d points in real world space\nimgpoints = [] # 2d points in image plane.\n\n# Make a list of calibration images\nimages = glob.glob('camera_cal/calibration*.jpg')\n\n# Step through the list and search for chessboard corners\nfor idx, fname in enumerate(images):\n img = cv2.imread(fname)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Find the chessboard corners\n ret, corners = cv2.findChessboardCorners(gray, (nx,ny), None)\n\n # If found, add object points, image points\n if ret == True:\n objpoints.append(objp)\n imgpoints.append(corners)\n\n #draw the chessboard corners and plot to show\n cv2.drawChessboardCorners(img, (nx,ny), corners, ret)\n plt.imshow(img)\n plt.show()\n \n \ndef save_calibration(objpoints, imgpoints):\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img.shape[0:2], None, None)\n calib = [mtx, dist]\n pickle.dump(calib, open(\"calibration.pkl\", \"wb\"))\n\n# save the calibration to load in successive runs, as this calibration is slow.\nsave_calibration(objpoints, imgpoints)\nprint(\"Calibration Saved\")\n" }, { "alpha_fraction": 0.5703807473182678, "alphanum_fraction": 0.6142158508300781, "avg_line_length": 31.90804672241211, "blob_id": "b4ff2e6a5ffd9ae547d3b7cbd923d5871082d1ba", "content_id": "eb9e61ebe7b2b69b956b6988ebed4e1ed5b7c955", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5726, "license_type": "no_license", "max_line_length": 132, "num_lines": 174, "path": "/methods.py", "repo_name": "darcwader/sdcn_p4_advanced_lane_finding", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nimport glob\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport pickle\nfrom moviepy.editor import VideoFileClip\nfrom tqdm import tqdm\n\ndef load_calibration():\n calib = pickle.load(open(\"calibration.pkl\", \"rb\"))\n print(\"Calibration Loaded\")\n return calib[0], calib[1]\n\n#load calibration\nmtx, dist = load_calibration()\n\nimg_size = (1280, 720)\n\ndef load_transforms():\n #load perspective vars\n src = np.float32([[ 585.0-10, 460.0],\n [ 0.0, 720.0],\n [ 1280.0, 720.0],\n [ 695.0+10, 460.0]])\n\n dst = np.float32([[320, 0],\n [320, 720],\n [960, 720],\n [960, 0]])\n\n M = cv2.getPerspectiveTransform(src, dst)\n Minv = cv2.getPerspectiveTransform(dst, src)\n return M, Minv\n\nM, Minv = load_transforms()\n\ndef undistort(img):\n undist = cv2.undistort(img, mtx, dist)\n return undist\n\ndef fast_unwarp_lane(img):\n global dist, mtx, img_size\n undist = cv2.undistort(img, mtx, dist)\n out = cv2.warpPerspective(undist, M, img_size, flags=cv2.INTER_LINEAR)\n return out\n\ndef fast_warp_lane(lane):\n global Minv, img_size\n unwarped = cv2.warpPerspective(lane, Minv, img_size, flags=cv2.INTER_LINEAR)\n return unwarped\n\ndef process_video(infile, outfile, method):\n \"\"\"method has to accept rgb image and return rgb image. method is called on every frame of infile.\"\"\"\n clip1 = VideoFileClip(infile)\n white_clip = clip1.fl_image(method) #NOTE: this function expects color images!!\n white_clip.write_videofile(outfile, audio=False)\n\ndef plot_images(images):\n \"\"\" Helper routine which plots all images passed as array in a single row \"\"\"\n m = len(images)\n n = len(images[0])\n\n fig, axes = plt.subplots(m, n, figsize=(10*n, 10*m))\n fig.tight_layout()\n for ix in range(m):\n for iy in range(n):\n axes[ix][iy].imshow(images[ix][iy], cmap='gray')\n axes[ix][iy].axis('off')\n plt.show()\n\ndef plot_images_save(fname, images):\n \"\"\" Helper routine which plots all images passed as array in a single row \"\"\"\n print(len(images))\n m = len(images)\n n = len(images[0])\n\n fig, axes = plt.subplots(m, n, figsize=(10*n, 10*m))\n if m == 1:\n axes = [axes]\n fig.tight_layout()\n for ix in range(m):\n for iy in range(n):\n axes[ix][iy].imshow(images[ix][iy], cmap='gray')\n axes[ix][iy].axis('off')\n fig.savefig(fname)\n\ndef abs_sobel_thresh(img_gray, orient='x', ksize=3, thresh=(20,100)):\n sobel = None\n if orient=='x':\n sobel = cv2.Sobel(img_gray, cv2.CV_64F, 1, 0, ksize=ksize)\n else:\n sobel = cv2.Sobel(img_gray, cv2.CV_64F, 0, 1, ksize=ksize)\n abs_sobel = np.absolute(sobel)\n scaled = np.uint8(255*abs_sobel/np.max(abs_sobel))\n\n binary_output = np.zeros_like(scaled)\n binary_output[(scaled >= thresh[0]) & (scaled <= thresh[1])] = 1\n\n return binary_output\n\ndef mag_thresh(gray, ksize=9, thresh=(20,80)):\n sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=ksize)\n sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=ksize)\n abssolxy = np.sqrt(sobelx ** 2 + sobely ** 2)\n scaledxy = (abssolxy*255/np.max(abssolxy)).astype(np.uint8)\n binary_output = np.zeros_like(scaledxy)\n binary_output[(scaledxy >= thresh[0]) & (scaledxy <= thresh[1])] = 1\n return binary_output\n\ndef dir_thresh(gray, ksize=15, thresh=(0.0, np.pi/2)):\n sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=ksize)\n abssobelx = np.absolute(sobelx)\n sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=ksize)\n abssobely = np.absolute(sobely)\n\n abssobelxy = np.arctan2(abssobely,abssobelx)\n\n binary_output = np.zeros(abssobelxy.shape, dtype=np.uint8)\n binary_output[(abssobelxy >= thresh[0]) & (abssobelxy <= thresh[1])] = 1\n return binary_output\n\ndef hsv_select(image_hsv):\n i_h = image_hsv[:,:,0]\n i_s = image_hsv[:,:,1]\n i_v = image_hsv[:,:,2]\n\n i_h = cv2.equalizeHist(i_h)\n i_s = cv2.equalizeHist(i_s)\n i_v = cv2.equalizeHist(i_v)\n\n res = np.zeros_like(i_h).astype(np.uint8)\n res[(i_s > 200) & (i_v > 150) ] = 1 #yellow only\n res[(i_s<80) & (i_v > 240)] = 1 #white only\n\n return res\n\ndef hsv_debug(img):\n img_hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n i_h = img_hsv[:,:,0]\n i_s = img_hsv[:,:,1]\n i_v = img_hsv[:,:,2]\n\n i_h_e = cv2.equalizeHist(i_h)\n i_s_e = cv2.equalizeHist(i_s)\n i_v_e = cv2.equalizeHist(i_v)\n\n return i_h_e, i_s_e, i_v_e\n\ndef apply_stage_1(img_gray):\n x_image = abs_sobel_thresh(img_gray, orient='x', ksize=3, thresh=(20,200))\n y_image = abs_sobel_thresh(img_gray, orient='y', ksize=3, thresh=(20,200))\n xy_image = mag_thresh(img_gray, ksize=9, thresh=(20,100))\n dir_image = dir_thresh(img_gray, ksize=9, thresh=(0.7, 1.3))\n\n img_stage_1 = np.zeros_like(x_image)\n img_stage_1[(x_image == 1) | ((xy_image == 1) & (dir_image == 1))] = 1 #dir_image is not working after lot of trials and error.\n #img_stage_1[((x_image == 1) | (y_image == 1))] = 1\n return img_stage_1\n\ndef apply_thresholds(img):\n img = cv2.undistort(img, mtx, dist, None, mtx)\n img_hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n img_hsv_s = cv2.equalizeHist(img_hsv[:,:,2])\n\n stage_1 = apply_stage_1(img_hsv_s) #sending S channel as gray for sobel thresholding\n stage_2 = hsv_select(img_hsv)\n\n # hsv is generally better overall. x/y only on certain occasions.\n #res = (stage_1 * 72) + (stage_2 * 182) # lot of trials, got this. hsv is prominent, but xy sobel is when hsv is not working.\n res = stage_1 + stage_2\n binary_out = np.zeros_like(res)\n binary_out[res > 100] = 1\n return res, stage_1, stage_2\n" }, { "alpha_fraction": 0.584263265132904, "alphanum_fraction": 0.6266795992851257, "avg_line_length": 49.18000030517578, "blob_id": "f8b501d0180793299d42a28316f5f31c666dd422", "content_id": "47041eeed43a1387c36111bac575a144efe38116", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17564, "license_type": "no_license", "max_line_length": 292, "num_lines": 350, "path": "/methods_sliding_window.py", "repo_name": "darcwader/sdcn_p4_advanced_lane_finding", "src_encoding": "UTF-8", "text": "\nimport numpy as np\nimport cv2\nimport glob\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport pickle\nfrom moviepy.editor import VideoFileClip\nfrom tqdm import tqdm\nfrom methods import *\n\n\nclass Line:\n def __init__(self):\n self.lane_inds = []\n #polynomial coefficients averaged over the last n iterations\n self.best_fit = None\n #polynomial coefficients for the most recent fit\n self.current_fit = np.array([False])\n self.previous_fit = []\n #radius of curvature of the line in some units\n self.radius_of_curvature = 0\n #error between current_fit and previous_fit\n self.curr_err = 0.0\n\nclass Lane:\n\n\n def __init__(self):\n self.left = Line()\n self.right = Line()\n self.debug_image = np.zeros((1080, 1920, 3), dtype=np.uint8)\n\n def binary_warped(self, img):\n res, st1, st2 = apply_thresholds(img)\n res_rgb = np.dstack((res, res, res))*255\n st1_rgb = np.dstack((st1, st1, st1))*255\n st2_rgb = np.dstack((st2, st2, st2))*255\n lane = fast_unwarp_lane(res_rgb)\n st1_uw = fast_unwarp_lane(st1_rgb)\n st2_uw = fast_unwarp_lane(st2_rgb)\n\n binary_warped = lane[:,:,2]\n\n\n #following only used for debugging pipeline\n self.debug_image[840:1080, 0:320] = cv2.resize(st1_uw, (320, 240), interpolation=cv2.INTER_AREA)\n self.debug_image[840:1080, 320:640] = cv2.resize(st2_uw, (320, 240), interpolation=cv2.INTER_AREA)\n self.debug_image[840:1080, 640:960] = cv2.resize(lane, (320, 240), interpolation=cv2.INTER_AREA)\n\n\n cv2.rectangle(self.debug_image,(0,840),(320,1080),(0,255,255), 2)\n cv2.rectangle(self.debug_image,(320,840),(640,1080),(0,255,255), 2)\n cv2.rectangle(self.debug_image,(640,840),(960,1080),(0,255,255), 2)\n\n a,b,c = hsv_debug(img)\n a = fast_unwarp_lane(np.dstack((a,a,a))*255)\n b = fast_unwarp_lane(np.dstack((b,b,b))*255)\n c = fast_unwarp_lane(np.dstack((c,c,c))*255)\n self.debug_image[0:240, 1600:1920] = cv2.resize(a, (320, 240), interpolation=cv2.INTER_AREA)\n self.debug_image[240:480, 1600:1920] = cv2.resize(b, (320, 240), interpolation=cv2.INTER_AREA)\n self.debug_image[480:720, 1600:1920] = cv2.resize(c, (320, 240), interpolation=cv2.INTER_AREA)\n\n return binary_warped\n\n def sliding_window(self, img):\n binary_warped = self.binary_warped(img)\n\n if self.left.current_fit.size > 0:\n out = self.sliding_first(binary_warped)\n else:\n out = self.sliding_next(binary_warped)\n\n self.draw_search_window_area(binary_warped, d1=960, d2=1280) #plot before dropping fit\n self.process_fits()\n out = self.draw_projection(binary_warped)\n self.draw_search_window_area(binary_warped)\n\n return out\n\n\n def sliding_first(self, binary_warped):\n # Takins in binary warped, and returns sliding window drawn image with\n # left right inds colored\n\n # Take a histogram of the bottom half of the image\n histogram = np.sum(binary_warped[binary_warped.shape[0]/2:,:], axis=0)\n # Create an output image to draw on and visualize the result\n out_img = np.dstack((binary_warped, binary_warped, binary_warped))*255\n # Find the peak of the left and right halves of the histogram\n # These will be the starting point for the left and right lines\n midpoint = np.int(histogram.shape[0]/2)\n leftx_base = np.argmax(histogram[:midpoint])\n rightx_base = np.argmax(histogram[midpoint:]) + midpoint\n\n # Choose the number of sliding windows\n nwindows = 9\n # Set height of windows\n window_height = np.int(binary_warped.shape[0]/nwindows)\n # Identify the x and y positions of all nonzero pixels in the image\n nonzero = binary_warped.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n # Current positions to be updated for each window\n leftx_current = leftx_base\n rightx_current = rightx_base\n # Set the width of the windows +/- margin\n margin = 100\n # Set minimum number of pixels found to recenter window\n minpix = 50\n # Create empty lists to receive left and right lane pixel indices\n self.left.lane_inds = []\n self.right.lane_inds = []\n\n # Step through the windows one by one\n for window in range(nwindows):\n # Identify window boundaries in x and y (and right and left)\n win_y_low = binary_warped.shape[0] - (window+1)*window_height\n win_y_high = binary_warped.shape[0] - window*window_height\n win_xleft_low = leftx_current - margin\n win_xleft_high = leftx_current + margin\n win_xright_low = rightx_current - margin\n win_xright_high = rightx_current + margin\n # Draw the windows on the visualization image\n cv2.rectangle(out_img,(win_xleft_low,win_y_low),(win_xleft_high,win_y_high),(0,255,0), 2)\n cv2.rectangle(out_img,(win_xright_low,win_y_low),(win_xright_high,win_y_high),(0,255,0), 2)\n # Identify the nonzero pixels in x and y within the window\n good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]\n good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]\n # Append these indices to the lists\n self.left.lane_inds.append(good_left_inds)\n self.right.lane_inds.append(good_right_inds)\n # If you found > minpix pixels, recenter next window on their mean position\n if len(good_left_inds) > minpix:\n leftx_current = np.int(np.mean(nonzerox[good_left_inds]))\n if len(good_right_inds) > minpix:\n rightx_current = np.int(np.mean(nonzerox[good_right_inds]))\n\n # Concatenate the arrays of indices\n self.left.lane_inds = np.concatenate(self.left.lane_inds)\n self.right.lane_inds = np.concatenate(self.right.lane_inds)\n\n # Extract left and right line pixel positions\n leftx = nonzerox[self.left.lane_inds]\n lefty = nonzeroy[self.left.lane_inds]\n rightx = nonzerox[self.right.lane_inds]\n righty = nonzeroy[self.right.lane_inds]\n\n # Fit a second order polynomial to each\n self.left.current_fit = np.polyfit(lefty, leftx, 2)\n self.right.current_fit = np.polyfit(righty, rightx, 2)\n\n # Generate x and y values for plotting\n ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0] )\n left_fitx = self.left.current_fit[0]*ploty**2 + self.left.current_fit[1]*ploty + self.left.current_fit[2]\n right_fitx = self.right.current_fit[0]*ploty**2 + self.right.current_fit[1]*ploty + self.right.current_fit[2]\n\n out_img[nonzeroy[self.left.lane_inds], nonzerox[self.left.lane_inds]] = [255, 0, 0]\n out_img[nonzeroy[self.right.lane_inds], nonzerox[self.right.lane_inds]] = [0, 0, 255]\n\n return out_img\n\n def sliding_next(self,binary_warped):\n # We now have a new warped binary image\n # It's now much easier to find line pixels!\n nonzero = binary_warped.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n margin = 100\n self.left.lane_inds = ((nonzerox > (self.left.current_fit[0]*(nonzeroy**2) + self.left.current_fit[1]*nonzeroy + self.left.current_fit[2] - margin)) & (nonzerox < (self.left.current_fit[0]*(nonzeroy**2) + self.left.current_fit[1]*nonzeroy + self.left.current_fit[2] + margin)))\n self.right.lane_inds = ((nonzerox > (self.right.current_fit[0]*(nonzeroy**2) + self.right.current_fit[1]*nonzeroy + self.right.current_fit[2] - margin)) & (nonzerox < (self.right.current_fit[0]*(nonzeroy**2) + self.right.current_fit[1]*nonzeroy + self.right.current_fit[2] + margin)))\n\n # Again, extract left and right line pixel positions\n leftx = nonzerox[self.left.lane_inds]\n lefty = nonzeroy[self.left.lane_inds]\n rightx = nonzerox[self.right.lane_inds]\n righty = nonzeroy[self.right.lane_inds]\n # Fit a second order polynomial to each\n self.left.current_fit = np.polyfit(lefty, leftx, 2)\n self.right.current_fit = np.polyfit(righty, rightx, 2)\n\n return binary_warped\n\n\n def draw_search_window_area(self, binary_warped, d1=1280, d2=1600):\n # Create an image to draw on and an image to show the selection window\n out_img = np.dstack((binary_warped, binary_warped, binary_warped))*255\n window_img = np.zeros_like(out_img)\n nonzero = binary_warped.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n # Color in left and right line pixels\n out_img[nonzeroy[self.left.lane_inds], nonzerox[self.left.lane_inds]] = [255, 0, 0]\n out_img[nonzeroy[self.right.lane_inds], nonzerox[self.right.lane_inds]] = [0, 0, 255]\n\n # Generate x and y values for plotting\n ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0] )\n left_fitx = self.left.current_fit[0]*ploty**2 + self.left.current_fit[1]*ploty + self.left.current_fit[2]\n right_fitx = self.right.current_fit[0]*ploty**2 + self.right.current_fit[1]*ploty + self.right.current_fit[2]\n # Generate a polygon to illustrate the search window area\n # And recast the x and y points into usable format for cv2.fillPoly()\n margin = 100\n left_line_window1 = np.array([np.transpose(np.vstack([left_fitx-margin, ploty]))])\n left_line_window2 = np.array([np.flipud(np.transpose(np.vstack([left_fitx+margin, ploty])))])\n left_line_pts = np.hstack((left_line_window1, left_line_window2))\n right_line_window1 = np.array([np.transpose(np.vstack([right_fitx-margin, ploty]))])\n right_line_window2 = np.array([np.flipud(np.transpose(np.vstack([right_fitx+margin, ploty])))])\n right_line_pts = np.hstack((right_line_window1, right_line_window2))\n\n # Draw the lane onto the warped blank image\n cv2.fillPoly(window_img, np.int_([left_line_pts]), (0,255, 0))\n cv2.fillPoly(window_img, np.int_([right_line_pts]), (0,255, 0))\n result = cv2.addWeighted(out_img, 1, window_img, 0.3, 0)\n\n self.debug_image[840:1080, d1:d2] = cv2.resize(result, (320, 240), interpolation=cv2.INTER_AREA)\n cv2.rectangle(self.debug_image,(960,840),(1280,1080),(0,255,255), 2)\n\n return result\n\n def process_fits(self):\n last_n = 5\n\n #measure the error between fits and store into curr_err.\n if self.left is not None and self.left.current_fit is not None and len(self.left.previous_fit)>0:\n #ploty = np.linspace(0, 720-1, 720)\n\n #left_fitx = self.left.current_fit[0]*ploty**2 + self.left.current_fit[1]*ploty + self.left.current_fit[2]\n #left_prev_fitx = self.left.previous_fit[-1][0]*ploty**2 + self.left.previous_fit[-1][1]*ploty + self.left.previous_fit[-1][2]\n #err_p = np.mean((left_fitx - left_prev_fitx)**2) #/np.sum(right_fit_prev[0]**2)\n err_p = np.mean((self.left.current_fit - self.left.previous_fit[-1])**2) #/np.sum(right_fit_prev[0]**2)\n err_p = np.sqrt(err_p)\n self.left.curr_err = err_p\n\n #right_fitx = self.right.current_fit[0]*ploty**2 + self.right.current_fit[1]*ploty + self.right.current_fit[2]\n #right_prev_fitx = self.right.previous_fit[-1][0]*ploty**2 + self.right.previous_fit[-1][1]*ploty + self.right.previous_fit[-1][2]\n #err_p = np.mean((right_fitx - right_prev_fitx)**2) #/np.sum(right_fit_prev[0]**2)\n err_p = np.mean((self.right.current_fit - self.right.previous_fit[-1])**2) #/np.sum(right_fit_prev[0]**2)\n err_p = np.sqrt(err_p)\n self.right.curr_err = err_p\n else:\n self.left.curr_err = 0.0\n self.right.curr_err = 0.0\n\n #if error is too high, drop the current_fit and use previous_fit\n if self.left.curr_err > 50.0:\n self.left.current_fit = self.left.best_fit\n\n if self.right.curr_err > 50.0:\n self.right.current_fit = self.right.best_fit\n\n #average the fit over last_n iterations\n self.left.previous_fit.append(self.left.current_fit)\n if len(self.left.previous_fit) > last_n:\n self.left.previous_fit = self.left.previous_fit[1:]\n self.left.best_fit = np.average(self.left.previous_fit, axis=0)\n\n\n self.right.previous_fit.append(self.right.current_fit)\n if len(self.right.previous_fit) > last_n:\n self.right.previous_fit = self.right.previous_fit[1:]\n self.right.best_fit = np.average(self.right.previous_fit, axis=0)\n\n #assign the best_fit / averate to current_fit for next steps\n self.left.current_fit = self.left.best_fit\n self.right.current_fit = self.right.best_fit\n\n\n def draw_curvature(self, img):\n #draws curvature metrics onto the img\n y_eval = np.max(img.shape[0]-1)\n left_curverad = ((1 + (2*self.left.current_fit[0]*y_eval + self.left.current_fit[1])**2)**1.5) / np.absolute(2*self.left.current_fit[0])\n right_curverad = ((1 + (2*self.right.current_fit[0]*y_eval + self.right.current_fit[1])**2)**1.5) / np.absolute(2*self.right.current_fit[0])\n #cv2.putText(img, \"left:{0:.2f}\".format(left_curverad), (100,100), cv2.FONT_HERSHEY_PLAIN,2, 255)\n #cv2.putText(img, \"right:{0:.2f}\".format(right_curverad), (100,150), cv2.FONT_HERSHEY_PLAIN,2, 255)\n #print(left_curverad, right_curverad)\n\n\n ploty = np.linspace(0, img.shape[0]-1, img.shape[0] )\n leftx = self.left.current_fit[0]*ploty**2 + self.left.current_fit[1]*ploty + self.left.current_fit[2]\n rightx = self.right.current_fit[0]*ploty**2 + self.right.current_fit[1]*ploty + self.right.current_fit[2]\n\n # Define conversions in x and y from pixels space to meters\n ym_per_pix = 30/720 # meters per pixel in y dimension\n xm_per_pix = 3.7/700 # meters per pixel in x dimension\n\n # Fit new polynomials to x,y in world space\n left_fit_cr = np.polyfit(ploty*ym_per_pix, leftx*xm_per_pix, 2)\n right_fit_cr = np.polyfit(ploty*ym_per_pix, rightx*xm_per_pix, 2)\n # Calculate the new radii of curvature\n self.left.radius_of_curvature = ((1 + (2*left_fit_cr[0]*y_eval*ym_per_pix + left_fit_cr[1])**2)**1.5) / np.absolute(2*left_fit_cr[0])\n self.right.radius_of_curvature = ((1 + (2*right_fit_cr[0]*y_eval*ym_per_pix + right_fit_cr[1])**2)**1.5) / np.absolute(2*right_fit_cr[0])\n # Now our radius of curvature is in meters\n #print(left_curverad, 'm', right_curverad, 'm')\n\n cv2.putText(img, \"Radius Left:{0:.2f}m\".format(self.left.radius_of_curvature), (10,50), cv2.FONT_HERSHEY_PLAIN, 2, 255)\n cv2.putText(img, \"Radius Right:{0:.2f}m\".format(self.right.radius_of_curvature), (10,100), cv2.FONT_HERSHEY_PLAIN, 2, 255)\n # Example values: 632.1 m 626.2 m\n\n self.draw_lane_deviation(img)\n\n\n str_err = 'Error: Left = ' + str(np.round(self.left.curr_err,2)) + ', Right = ' + str(np.round(self.right.curr_err,2))\n\n font = cv2.FONT_HERSHEY_PLAIN\n middlepanel = np.zeros((120, 1280, 3), dtype=np.uint8)\n cv2.putText(middlepanel, str_err, (30, 60), font, 2, (255,0,0), 2)\n #cv2.putText(middlepanel, str_offset, (30, 90), font, 1, (255,0,0), 2)\n self.debug_image[720:840, 0:1280] = middlepanel\n\n\n\n return img\n\n\n def draw_projection(self, binary_warped):\n #draws the projection and returns color image\n\n # Create an image to draw the lines on\n warp_zero = np.zeros_like(binary_warped).astype(np.uint8)\n color_warp = np.dstack((warp_zero, warp_zero, warp_zero))\n\n # Recast the x and y points into usable format for cv2.fillPoly()\n ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0] )\n left_fitx = self.left.current_fit[0]*ploty**2 + self.left.current_fit[1]*ploty + self.left.current_fit[2]\n right_fitx = self.right.current_fit[0]*ploty**2 + self.right.current_fit[1]*ploty + self.right.current_fit[2]\n\n pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])\n pts = np.hstack((pts_left, pts_right))\n\n cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0))\n\n self.debug_image[480:720, 1280:1600] = cv2.resize(color_warp, (320, 240), interpolation=cv2.INTER_AREA)\n\n return color_warp\n\n def draw_lane_deviation(self, img):\n ## Compute intercepts\n img_size = img.shape[0:2]\n left_bot = img_size[0] * self.left.current_fit[0]**2 + img_size[0]*self.left.current_fit[1] + self.left.current_fit[2]\n right_bot = img_size[0] * self.right.current_fit[0]**2 + img_size[0]*self.right.current_fit[1] + self.right.current_fit[2]\n\n ## Compute center location\n val_center = (left_bot+right_bot)/2.0\n\n ## Compute lane offset\n dist_offset = val_center - img_size[1]/2\n dist_offset = np.round(dist_offset/2.81362,2)\n str_offset = 'Lane deviation: ' + str(dist_offset) + ' cm.'\n\n cv2.putText(img, str_offset, (10,150), cv2.FONT_HERSHEY_PLAIN, 2, 255)\n" }, { "alpha_fraction": 0.6064981818199158, "alphanum_fraction": 0.6510228514671326, "avg_line_length": 24.96875, "blob_id": "9d0d748951892a9d3f8252dd4003d9f133c34087", "content_id": "b59184830d49c6a463b1fe17327ef61adb795af4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 831, "license_type": "no_license", "max_line_length": 68, "num_lines": 32, "path": "/run_7_video.py", "repo_name": "darcwader/sdcn_p4_advanced_lane_finding", "src_encoding": "UTF-8", "text": "from methods import *\nfrom methods_sliding_window import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom moviepy.editor import VideoFileClip\nimport glob\nimport cv2\nimport matplotlib.image as mpimg\n\nlane = Lane()\n\ndef process(img):\n undist = undistort(img)\n out = lane.sliding_window(img)\n out = fast_warp_lane(out)\n out = cv2.addWeighted(undist, 1.0, out, 0.5, 0)\n lane.draw_curvature(out)\n #lane.draw_search_window_area(out)\n lane.debug_image[0:720, 0:1280] = out\n cv2.rectangle(lane.debug_image,(0,0),(1280,1080),(0,255,255), 2)\n return lane.debug_image\n return out\n\n\nif __name__ == \"__main__\":\n #inp = \"project_small\"\n #inp = \"project_video\"\n inp = \"challenge_video\"\n\n process_video(infile=inp + \".mp4\",\n outfile=inp + \"_final.mp4\",\n method=process)\n" }, { "alpha_fraction": 0.5776805281639099, "alphanum_fraction": 0.5951859951019287, "avg_line_length": 20.761905670166016, "blob_id": "a66078769fc8c520bec333eb69640cb114b3375a", "content_id": "25764e4df93de843e84f4b61dd43aa7c18cd2750", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 457, "license_type": "no_license", "max_line_length": 49, "num_lines": 21, "path": "/curvature.py", "repo_name": "darcwader/sdcn_p4_advanced_lane_finding", "src_encoding": "UTF-8", "text": "from methods import *\nfrom methods_sliding_window import *\n\nl = Lane()\n\ndef frame(img):\n binary_warped = l.sliding_window(img)\n warp = fast_warp_lane(binary_warped)\n\n out = cv2.addWeighted(img, 1.0, warp, 0.5, 0)\n l.draw_curvature(out)\n return out\n\n\nif __name__ == \"__main__\":\n inp = \"project_small\"\n #inp = \"project_video\"\n\n process_video(infile=inp + \".mp4\", \n outfile=inp + \"_curvature.mp4\", \n method=frame)\n" } ]
12
shubhamguptasr/EyeBraille
https://github.com/shubhamguptasr/EyeBraille
7e0275bb57a183e8052ef712e17ac2bef0098ce5
2997dd677bdaa946099a341d1eead667f5cfe74f
eb8df6587e18accda995a988ee39d60aef9003e4
refs/heads/main
2023-09-04T03:13:32.574722
2021-10-16T17:41:25
2021-10-16T17:41:25
416,938,455
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8225806355476379, "alphanum_fraction": 0.8306451439857483, "avg_line_length": 61, "blob_id": "fa1bf6743440b93489d43813f92ee2b6ef10919c", "content_id": "730c4d8e4a6ae22496e0914cee1d662e28cece6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 124, "license_type": "no_license", "max_line_length": 110, "num_lines": 2, "path": "/README.md", "repo_name": "shubhamguptasr/EyeBraille", "src_encoding": "UTF-8", "text": "# EyeBraille\nA portable Braille reading device to help visually impaired read digital text through 3D printed braille pins.\n" }, { "alpha_fraction": 0.5096153616905212, "alphanum_fraction": 0.5188746452331543, "avg_line_length": 34.099998474121094, "blob_id": "97f7c2803a1a13659de847828727964ce4b895b4", "content_id": "94d5495165908ff20d787fdcd6de7e7632a358a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2808, "license_type": "no_license", "max_line_length": 106, "num_lines": 80, "path": "/Programs/GUI/Code V2/textbox.py", "repo_name": "shubhamguptasr/EyeBraille", "src_encoding": "UTF-8", "text": "import pygame\nimport os\n#from convertOutput import convOut\nimport threading\n\n#Output to EyeBraille\n\n\npygame.init()\n##screen = pygame.display.set_mode((640, 480))\nCOLOR_INACTIVE = pygame.Color('lightskyblue3')\nCOLOR_ACTIVE = pygame.Color('dodgerblue2')\nFONT = pygame.font.Font('freesansbold.ttf', 20)\n\n\nclass InputBox:\n\n def __init__(self, screen, x, y, w, h, text=''):\n self.screen = screen\n self.rect = pygame.Rect(x, y, w, h)\n self.color = COLOR_INACTIVE\n self.text = text\n self.txt_surface = FONT.render(text, True, self.color)\n self.active = False\n self.txt_start = 0\n self.txt_display_length = 16\n \n\n def handle_event(self, event):\n if event.type == pygame.MOUSEBUTTONDOWN:\n # If the user clicked on the input_box rect.\n if self.rect.collidepoint(event.pos):\n # Toggle the active variable.\n self.active = not self.active\n else:\n self.active = False\n # Change the current color of the input box.\n self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE\n if event.type == pygame.KEYDOWN:\n if self.active:\n if event.key == pygame.K_RETURN:\n print(self.text)\n\n # Write text to file\n f = open (\"Text_File.txt\", \"w+\")\n f.write(self.text)\n f.close()\n \n #convOut(self.screen)\n \n #convOut(self.screen)\n #os.system('sudo chmod +x ./convertOutput.py')\n #subprocess.Popen(['./GUI.py'])\n #subprocess.Popen(['./convertOutput.py'])\n os.system(\"lxterminal -e python2 convertOutput.py\")\n \n \n self.text = ''\n elif event.key == pygame.K_BACKSPACE:\n self.text = self.text[:-1]\n else:\n self.text += event.unicode\n\n # Adjust for text out of bounds\n if len(self.text) >= self.txt_display_length:\n self.txt_start = len(self.text) - self.txt_display_length\n\n # Re-render the text.\n self.txt_surface = FONT.render(self.text[self.txt_start:len(self.text)], True, self.color)\n \n def update(self):\n # Resize the box if the text is too long.\n width = max(200, 100) #self.txt_surface.get_width()+10\n self.rect.w = width\n\n def draw(self):\n # Blit the text.\n self.screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5))\n # Blit the rect.\n pygame.draw.rect(self.screen, self.color, self.rect, 2)\n" }, { "alpha_fraction": 0.6016917824745178, "alphanum_fraction": 0.6318499445915222, "avg_line_length": 25.738916397094727, "blob_id": "262ee02d77e6510616014d403135c82189587c4d", "content_id": "cf6b2c119db598fe0d2b374bbad40fffe53819df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5438, "license_type": "no_license", "max_line_length": 126, "num_lines": 203, "path": "/Programs/GUI/Code V2/GUI.py", "repo_name": "shubhamguptasr/EyeBraille", "src_encoding": "UTF-8", "text": "from textbox import *\n#Output to EyeBraille\n#from convertOutput import *\nimport subprocess\nimport threading\n\nimport pygame\nimport time\n#File Dialog\nimport Tkinter\nfrom Tkinter import *\nfrom tkFileDialog import askopenfilename\n#PDF\nfrom cStringIO import StringIO\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\nfrom pdfminer.converter import TextConverter\nfrom pdfminer.layout import LAParams\nfrom pdfminer.pdfpage import PDFPage\nimport os\nimport sys, getopt\n#import os\n#import pdfminer\n\npygame.init()\n\ndisplay_width = 800\ndisplay_height = 600\n\n#Defined Colours\nwhite = (255,255,255)\ngrey = (200,200,200)\nlight_grey = (125,125,125)\ngold = (255,223,20)\n\n\nGUI_Display = pygame.display.set_mode((display_width,display_height))\npygame.display.set_caption('Eye Braille')\nclock = pygame.time.Clock()\nexit_Condition = False\n\n\n\npygame.display.update()\n\n##\ndef text_objects(text, font):\n textSurface = font.render(text, True, (0,0,0))\n return textSurface, textSurface.get_rect()\n##\n\n##\ndef message_display(text, font, font_size, rect):\n Text_Font = pygame.font.Font(font,font_size)\n TextSurf, TextRect = text_objects(text, Text_Font)\n TextRect.center = (rect[0]+rect[2]/2,rect[1]+rect[3]/2)\n GUI_Display.blit(TextSurf, TextRect)\n\n #time.sleep(2) #Display for 2 second\n##\n\n##Button\ndef button(msg, font, font_size, rect, ic, ac, action=None):\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n\n # Mouse Hover\n if rect[0]+rect[2] > mouse[0] > rect[0] and rect[1]+rect[3] > mouse[1] > rect[1]:\n pygame.draw.rect(GUI_Display,ac,rect)\n if click[0] == 1 and action != None:\n action()\n action = None\n else:\n pygame.draw.rect(GUI_Display,ic,rect)\n\n message_display(msg,font,font_size,rect)\n##\n\n##Upload File\ndef upload_file():\n tk_root = Tk()\n tk_root.withdraw()\n\n result = askopenfilename(\n initialdir=tk_root,\n title=\"Select File\",\n filetypes=[(\"PDF Documents\", \"*.pdf\")],\n )\n\n if len(result)>0:\n print (\"You chose %s\" % result)\n #string = 'pdf2txt.py -o Text_File.txt -t tag %s' % result\n #os.system(string)\n text = convert(result,)\n textFile = open(\"Text_File.txt\", \"w\") #make text file\n textFile.write(text) #write text to text file\n##\n\n##Convert PDF to Txt\ndef convert(fname, pages=None):\n if not pages:\n pagenums = set()\n else:\n pagenums = set(pages)\n\n output = StringIO()\n manager = PDFResourceManager()\n converter = TextConverter(manager, output, laparams=LAParams())\n interpreter = PDFPageInterpreter(manager, converter)\n\n infile = file(fname, 'rb')\n for page in PDFPage.get_pages(infile, pagenums):\n interpreter.process_page(page)\n infile.close()\n converter.close()\n text = output.getvalue()\n output.close\n return text \n##\n\n##Main Menu\ndef main_menu():\n \n global exit_Condition\n \n while not exit_Condition:\n pygame.display.update()\n clock.tick(15)\n GUI_Display.fill(gold)\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit_Condition = True\n\n #message_display(\"Eye Braille\",'freesansbold.ttf',115,(0,0,display_width,display_height))\n logo = pygame.image.load('Eye_Braille.png')\n GUI_Display.blit(logo, (display_width/2-logo.get_width()/2,0))\n\n #Buttons/Menu Options\n button(\"Upload Content\",'freesansbold.ttf',20,(display_width/2-85,400,170,50),grey,light_grey, upload_content)\n button(\"Enter Text\",'freesansbold.ttf',20,(display_width/2-85,500,170,50),grey,light_grey, enter_text)\n##\n\n##Upload Content Menu\ndef upload_content():\n \n global exit_Condition\n \n while not exit_Condition:\n pygame.display.update()\n clock.tick(15)\n GUI_Display.fill(gold)\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit_Condition = True\n\n #Instruction\n message_display(\"Select and upload a PDF File:\",'freesansbold.ttf',20,(0,0,display_width,display_height/8))\n\n button(\"Upload PDF\",'freesansbold.ttf',20,(display_width/2-75,100,150,50),grey,light_grey, upload_file)\n button(\"Back\",'freesansbold.ttf',20,(50,500,100,50),grey,light_grey, main_menu)\n##\n\n##Enter Text Menu\ndef enter_text():\n input_box = InputBox(GUI_Display, display_width/2-100, 100, 100, 32)\n input_boxes = [input_box]\n global exit_Condition\n \n \n \n while not exit_Condition:\n pygame.display.update()\n clock.tick(15)\n GUI_Display.fill(gold)\n \n for event in pygame.event.get():\n \n if event.type == pygame.QUIT: \n exit_Condition = True\n for box in input_boxes:\n box.handle_event(event)\n\n for box in input_boxes:\n box.update()\n \n for box in input_boxes:\n box.draw()\n \n \n #os.system(\"python2 convertOutput.py &\")\n #subprocess.Popen(['./convertOutput.py'])\n #Instruction\n message_display(\"Enter text to be displayed on EyeBraille\",'freesansbold.ttf',20,(0,0,display_width,display_height/8))\n\n button(\"Back\",'freesansbold.ttf',20,(50,500,100,50),grey,light_grey, main_menu)\n\n #NOTE: Exclude some special characters\n##\n \nmain_menu()\npygame.quit()\nquit()\n\n \n" }, { "alpha_fraction": 0.7733333110809326, "alphanum_fraction": 0.7733333110809326, "avg_line_length": 29, "blob_id": "cdfb90538167c99b66f3148e11451bb09d83771d", "content_id": "41f8edb16154b033b228b4c8533d11c8a4d046f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 150, "license_type": "no_license", "max_line_length": 52, "num_lines": 5, "path": "/Programs/GUI/Code V2/fileCheck.py", "repo_name": "shubhamguptasr/EyeBraille", "src_encoding": "UTF-8", "text": "import pyinotify\nwm = pyinotify.WatchManager()\nnotifier = pyinotify.Notifier(wm)\nwm.add_watch('./Text_File.txt',pyinotify.ALL_EVENTS)\nnotifier.loop()\n" }, { "alpha_fraction": 0.6109022498130798, "alphanum_fraction": 0.6184210777282715, "avg_line_length": 25.350000381469727, "blob_id": "f71540899ff8ef0c1a99c64cd3d2c33607f068da", "content_id": "4ceb954551c2dce561639651b69f3ee908bb1a03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 532, "license_type": "no_license", "max_line_length": 67, "num_lines": 20, "path": "/Programs/Reading Text with Scrolling/read_text.py", "repo_name": "shubhamguptasr/EyeBraille", "src_encoding": "UTF-8", "text": "#opening target file\ntextFile = open('textFile.txt', 'r')\n\n#read all lines into stringFile array\nstringFile = textFile.read().split('\\n')\n\n#determine number of lines in the file\nnumLines = len(stringFile)\n\n#initialize array that will store each element in file\ntextFileArray = []\n\nfor i in range(numLines):\n for j in range (len(stringFile[i])):\n if (stringFile[i][j] == \" \" or stringFile[i][j] == \"\\x0c\"):\n j=j+1\n else:\n textFileArray.append(stringFile[i][j])\n j=j+1\n i=i+1\n \n" }, { "alpha_fraction": 0.6794871687889099, "alphanum_fraction": 0.7051281929016113, "avg_line_length": 18.5, "blob_id": "16ef751ca23ed4fbdff4a02e8643cc64905b35a7", "content_id": "9c8eac1ac60b1e165f6d364cc136a44b9c3965c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 78, "license_type": "no_license", "max_line_length": 36, "num_lines": 4, "path": "/Programs/GUI/Code V2/run2.py", "repo_name": "shubhamguptasr/EyeBraille", "src_encoding": "UTF-8", "text": "import os\n\nos.system('python2 ./GUI.py')\nos.system('python2 ./runProgram.py')\n" }, { "alpha_fraction": 0.2943877577781677, "alphanum_fraction": 0.38163265585899353, "avg_line_length": 24.08974266052246, "blob_id": "0651c576f7cc9792a0349ce1cc72d6cfe941c691", "content_id": "495879ee9881452600a21615e68e376ab19f0f3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1960, "license_type": "no_license", "max_line_length": 68, "num_lines": 78, "path": "/Programs/First Dictionary Test/braille_Sentence.py", "repo_name": "shubhamguptasr/EyeBraille", "src_encoding": "UTF-8", "text": "dict = {}\ndict[str('A')] = [1,0,0,0,0,0]\ndict[str('B')] = [1,1,0,0,0,0]\ndict[str('C')] = [1,0,0,1,0,0]\ndict[str('D')] = [1,0,0,1,1,0]\ndict[str('E')] = [1,0,0,0,1,0]\ndict[str('F')] = [1,1,0,1,0,0]\ndict[str('G')] = [1,1,0,1,1,0]\ndict[str('H')] = [1,1,0,0,1,0]\ndict[str('I')] = [0,1,0,1,0,0]\ndict[str('J')] = [0,1,0,1,1,0]\ndict[str('K')] = [1,0,1,0,0,0]\ndict[str('L')] = [1,1,1,0,0,0]\ndict[str('M')] = [1,0,1,1,0,0]\ndict[str('N')] = [1,0,1,1,1,0]\ndict[str('O')] = [1,0,1,0,1,0]\ndict[str('P')] = [1,1,1,1,0,0]\ndict[str('Q')] = [1,1,1,1,1,0]\ndict[str('R')] = [1,1,1,0,1,0]\ndict[str('S')] = [0,1,1,1,0,0]\ndict[str('T')] = [0,1,1,1,1,0]\ndict[str('U')] = [1,0,1,0,0,1]\ndict[str('V')] = [1,1,1,0,0,1]\ndict[str('W')] = [0,1,0,1,1,1]\ndict[str('X')] = [1,0,1,1,0,1]\ndict[str('Y')] = [1,1,1,1,1,1]\ndict[str('Z')] = [1,0,1,0,1,1]\n\ntl = 'o'\nml = 'o'\nbl = 'o'\ntr = 'o'\nmr = 'o'\nbr = 'o'\n\noutputStr = []\n\nwhile(1):\n ltr = raw_input(\"Enter word: \")\n inputSize = len(ltr)\n \n for i in range(inputSize):\n searchLtr = ltr[i]\n if ltr[i] in dict:\n if dict[searchLtr][0] == 1:\n tl = 'x'\n else:\n tl = 'o'\n if dict[searchLtr][1] == 1:\n ml = 'x'\n else:\n ml = 'o'\n if dict[searchLtr][2] == 1:\n bl = 'x'\n else:\n bl = 'o'\n if dict[searchLtr][3] == 1:\n tr = 'x'\n else:\n tr = 'o'\n if dict[searchLtr][4] == 1:\n mr = 'x'\n else:\n mr = 'o'\n if dict[searchLtr][5] == 1:\n br = 'x'\n else:\n br = 'o'\n \n #print(tl+\"\\t\"+tr+\"\\n\"+ml+\"\\t\"+mr+\"\\n\"+bl+\"\\t\"+br)\n outputStr.append(tl+\"\\t\"+tr+\"\\n\"+ml+\"\\t\"+mr+\"\\n\"+bl+\"\\t\"+br)\n \n i=i+1\n\n print(\"\\n\")\n for i in range(len(outputStr)):\n print(outputStr[i]+'\\t')\n i=i+1\n\n\n\n" }, { "alpha_fraction": 0.5512396693229675, "alphanum_fraction": 0.571074366569519, "avg_line_length": 23.040000915527344, "blob_id": "1dfcaf9b664dcdd66f6b54c310811f38e79d7e36", "content_id": "e8d21b4fd951b965856f16f6d6ce6e068b6a6755", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1210, "license_type": "no_license", "max_line_length": 67, "num_lines": 50, "path": "/Programs/Reading Text with Scrolling/read_text_with_scroll.py", "repo_name": "shubhamguptasr/EyeBraille", "src_encoding": "UTF-8", "text": "import pygame\nimport time\n\n\n#opening target file\ntextFile = open('textFile.txt', 'r')\n\n#read all lines into stringFile array\nstringFile = textFile.read().split('\\n')\n\n#determine number of lines in the file\nnumLines = len(stringFile)\n\n#initialize array that will store each element in file\ntextFileArray = []\nscrollDir = 0\ntextPos = -1\n\nfor i in range(numLines):\n for j in range (len(stringFile[i])):\n if (stringFile[i][j] == \" \" or stringFile[i][j] == \"\\x0c\"):\n j=j+1\n else:\n textFileArray.append(stringFile[i][j])\n j=j+1\ni=i+1\n \n\nscreen = pygame.display.set_mode((320,240))\n\nwhile True:\n for e in pygame.event.get():\n if e.type == pygame.QUIT:\n pygame.quit()\n\n if e.type == pygame.MOUSEBUTTONDOWN:\n if((textPos==0 or textPos==-1) and e.button == 5):\n print(\"You are at the beginning of the document!\")\n elif e.button == 4:\n print(textFileArray[textPos+1])\n textPos = textPos + 1\n elif e.button == 5:\n print(textFileArray[textPos-1])\n textPos = textPos - 1\n\n \n\n\n time.sleep(0.05)\n pygame.display.update()\n\n\n \n\n" }, { "alpha_fraction": 0.49826058745384216, "alphanum_fraction": 0.519133448600769, "avg_line_length": 29.550724029541016, "blob_id": "2aac7925d3e6a6658a914b8605d5c0ba4ce028fe", "content_id": "b61ae04a6683eadd709121e7d14240eedc93ea6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6324, "license_type": "no_license", "max_line_length": 77, "num_lines": 207, "path": "/Programs/GUI/Code V2/TextBox_Test.py", "repo_name": "shubhamguptasr/EyeBraille", "src_encoding": "UTF-8", "text": "##import pygame as pg\n##\n##\n##def main():\n## screen = pg.display.set_mode((640, 480))\n## font = pg.font.Font(None, 32)\n## clock = pg.time.Clock()\n## input_box = pg.Rect(100, 100, 140, 32)\n## color_inactive = pg.Color('lightskyblue3')\n## color_active = pg.Color('dodgerblue2')\n## color = color_inactive\n## active = False\n## text = ''\n## done = False\n##\n## while not done:\n## for event in pg.event.get():\n## if event.type == pg.QUIT:\n## done = True\n## if event.type == pg.MOUSEBUTTONDOWN:\n## # If the user clicked on the input_box rect.\n## if input_box.collidepoint(event.pos):\n## # Toggle the active variable.\n## active = not active\n## else:\n## active = False\n## # Change the current color of the input box.\n## color = color_active if active else color_inactive\n## if event.type == pg.KEYDOWN:\n## if active:\n## if event.key == pg.K_RETURN:\n## print(text)\n## text = ''\n## elif event.key == pg.K_BACKSPACE:\n## text = text[:-1]\n## else:\n## text += event.unicode\n##\n## screen.fill((30, 30, 30))\n## # Render the current text.\n## txt_surface = font.render(text, True, color)\n## # Resize the box if the text is too long.\n## width = max(200, txt_surface.get_width()+10)\n## input_box.w = width\n## # Blit the text.\n## screen.blit(txt_surface, (input_box.x+5, input_box.y+5))\n## # Blit the input_box rect.\n## pg.draw.rect(screen, color, input_box, 2)\n##\n## pg.display.flip()\n## clock.tick(30)\n##\n##\n##if __name__ == '__main__':\n## pg.init()\n## main()\n## pg.quit()\n\n\n\n\n##import pygame as pg\n##\n##\n##pg.init()\n##screen = pg.display.set_mode((640, 480))\n##COLOR_INACTIVE = pg.Color('lightskyblue3')\n##COLOR_ACTIVE = pg.Color('dodgerblue2')\n##FONT = pg.font.Font(None, 32)\n##\n##\n##class InputBox:\n##\n## def __init__(self, x, y, w, h, text=''):\n## self.rect = pg.Rect(x, y, w, h)\n## self.color = COLOR_INACTIVE\n## self.text = text\n## self.txt_surface = FONT.render(text, True, self.color)\n## self.active = False\n##\n## def handle_event(self, event):\n## if event.type == pg.MOUSEBUTTONDOWN:\n## # If the user clicked on the input_box rect.\n## if self.rect.collidepoint(event.pos):\n## # Toggle the active variable.\n## self.active = not self.active\n## else:\n## self.active = False\n## # Change the current color of the input box.\n## self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE\n## if event.type == pg.KEYDOWN:\n## if self.active:\n## if event.key == pg.K_RETURN:\n## print(self.text)\n## self.text = ''\n## elif event.key == pg.K_BACKSPACE:\n## self.text = self.text[:-1]\n## else:\n## self.text += event.unicode\n## # Re-render the text.\n## self.txt_surface = FONT.render(self.text, True, self.color)\n##\n## def update(self):\n## # Resize the box if the text is too long.\n## width = max(200, self.txt_surface.get_width()+10)\n## self.rect.w = width\n##\n## def draw(self, screen):\n## # Blit the text.\n## screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5))\n## # Blit the rect.\n## pg.draw.rect(screen, self.color, self.rect, 2)\n##\n##\n##\n##def main():\n## clock = pg.time.Clock()\n## input_box1 = InputBox(100, 100, 140, 32)\n## input_box2 = InputBox(100, 300, 140, 32)\n## input_boxes = [input_box1, input_box2]\n## done = False\n##\n## while not done:\n## for event in pg.event.get():\n## if event.type == pg.QUIT:\n## done = True\n## for box in input_boxes:\n## box.handle_event(event)\n##\n## for box in input_boxes:\n## box.update()\n##\n## screen.fill((30, 30, 30))\n## for box in input_boxes:\n## box.draw(screen)\n##\n## pg.display.flip()\n## clock.tick(30)\n##\n##\n##if __name__ == '__main__':\n## main()\n## pg.quit()\n\n\n\n\n\nimport pygame\npygame.init()\nvalidChars = \"`1234567890-=qwertyuiop[]\\\\asdfghjkl;'zxcvbnm,./\"\nshiftChars = '~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:\"ZXCVBNM<>?'\n\nclass TextBox(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.text = \"\"\n self.font = pygame.font.Font(None, 50)\n self.image = self.font.render(\"Enter your name\", False, [0, 0, 0])\n self.rect = self.image.get_rect()\n\n def add_chr(self, char):\n global shiftDown\n if char in validChars and not shiftDown:\n self.text += char\n elif char in validChars and shiftDown:\n self.text += shiftChars[validChars.index(char)]\n self.update()\n\n def update(self):\n old_rect_pos = self.rect.center\n self.image = self.font.render(self.text, False, [0, 0, 0])\n self.rect = self.image.get_rect()\n self.rect.center = old_rect_pos\n\n\nscreen = pygame.display.set_mode([640, 480])\ntextBox = TextBox()\nshiftDown = False\ntextBox.rect.center = [320, 240]\n\nrunning = True\nwhile running:\n screen.fill([255, 255, 255])\n screen.blit(textBox.image, textBox.rect)\n pygame.display.flip()\n for e in pygame.event.get():\n if e.type == pygame.QUIT:\n running = False\n if e.type == pygame.KEYUP:\n if e.key in [pygame.K_RSHIFT, pygame.K_LSHIFT]:\n shiftDown = False\n if e.type == pygame.KEYDOWN:\n textBox.add_chr(pygame.key.name(e.key))\n if e.key == pygame.K_SPACE:\n textBox.text += \" \"\n textBox.update()\n if e.key in [pygame.K_RSHIFT, pygame.K_LSHIFT]:\n shiftDown = True\n if e.key == pygame.K_BACKSPACE:\n textBox.text = textBox.text[:-1]\n textBox.update()\n if e.key == pygame.K_RETURN:\n if len(textBox.text) > 0:\n print (textBox.text)\n running = False\npygame.quit()\n" }, { "alpha_fraction": 0.6441241502761841, "alphanum_fraction": 0.6496673822402954, "avg_line_length": 19.477272033691406, "blob_id": "d14c6c6bcb620a8691469f05bc3f2727c22ce7d2", "content_id": "0186e235b37fa05e2244a8d11901ee217e80cb60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 902, "license_type": "no_license", "max_line_length": 100, "num_lines": 44, "path": "/Programs/GUI/Code V2/File_Test.py", "repo_name": "shubhamguptasr/EyeBraille", "src_encoding": "UTF-8", "text": "####1####\n##import tkinter\n##from tkinter.filedialog import askopenfilename\n##tk_root = tkinter.Tk()\n##tk_root.withdraw()\n##\n##result = askopenfilename(\n## filetypes=[(\"PDF Documents\", \"*.pdf\")],\n##)\n\n\n####2####\n##import tkinter\n##import tkinter.filedialog\n##import os\n##\n##tk_root = tkinter.Tk()\n##tk_root.withdraw()\n##\n##result = tkinter.filedialog.askopenfilename(\n## filetypes=[(\"PDF Documents\", \"*.pdf\")],\n##)\n##\n##currdir = os.getcwd()\n##tempdir = tkinter.filedialog.askdirectory(parent=tk_root, initialdir=currdir, title='Select File')\n##if len(tempdir)>0:\n## print (\"You chose %s\" % tempdir)\n\n\n####3####\nimport tkinter\nimport tkinter.filedialog\n\ntk_root = tkinter.Tk()\ntk_root.withdraw()\n\nresult = tkinter.filedialog.askopenfilename(\n initialdir=tk_root,\n title=\"Select File\",\n filetypes=[(\"PDF Documents\", \"*.pdf\")],\n)\n\nif len(result)>0:\n print (\"You chose %s\" % result)\n\n" }, { "alpha_fraction": 0.42518186569213867, "alphanum_fraction": 0.48550644516944885, "avg_line_length": 33.90234375, "blob_id": "3e77ff628628abfc1643028e4236b92fcafc3d49", "content_id": "82c1e1d8765d694ded01d0ad6692a9f5716f0cc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8935, "license_type": "no_license", "max_line_length": 253, "num_lines": 256, "path": "/Programs/GUI/Code V2/convertOutput.py", "repo_name": "shubhamguptasr/EyeBraille", "src_encoding": "UTF-8", "text": "#import libraries\nimport RPi.GPIO as GPIO\nimport pygame\nimport time\n\n#set up GPIO. This programm will use the BCM numbering\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\n#def convert():\n #set up library for alphabet\ndict = {}\ndict[str('A')] = [1,0,0,0,0,0]#start of upper case letters\ndict[str('B')] = [1,1,0,0,0,0]\ndict[str('C')] = [1,0,0,1,0,0]\ndict[str('D')] = [1,0,0,1,1,0]\ndict[str('E')] = [1,0,0,0,1,0]\ndict[str('F')] = [1,1,0,1,0,0]\ndict[str('G')] = [1,1,0,1,1,0]\ndict[str('H')] = [1,1,0,0,1,0]\ndict[str('I')] = [0,1,0,1,0,0]\ndict[str('J')] = [0,1,0,1,1,0]\ndict[str('K')] = [1,0,1,0,0,0]\ndict[str('L')] = [1,1,1,0,0,0]\ndict[str('M')] = [1,0,1,1,0,0]\ndict[str('N')] = [1,0,1,1,1,0]\ndict[str('O')] = [1,0,1,0,1,0]\ndict[str('P')] = [1,1,1,1,0,0]\ndict[str('Q')] = [1,1,1,1,1,0]\ndict[str('R')] = [1,1,1,0,1,0]\ndict[str('S')] = [0,1,1,1,0,0]\ndict[str('T')] = [0,1,1,1,1,0]\ndict[str('U')] = [1,0,1,0,0,1]\ndict[str('V')] = [1,1,1,0,0,1]\ndict[str('W')] = [0,1,0,1,1,1]\ndict[str('X')] = [1,0,1,1,0,1]\ndict[str('Y')] = [1,0,1,1,1,1]\ndict[str('Z')] = [1,0,1,0,1,1]\ndict[str('a')] = [1,0,0,0,0,0]#start of lower case letters\ndict[str('b')] = [1,1,0,0,0,0]\ndict[str('c')] = [1,0,0,1,0,0]\ndict[str('d')] = [1,0,0,1,1,0]\ndict[str('e')] = [1,0,0,0,1,0]\ndict[str('f')] = [1,1,0,1,0,0]\ndict[str('g')] = [1,1,0,1,1,0]\ndict[str('h')] = [1,1,0,0,1,0]\ndict[str('i')] = [0,1,0,1,0,0]\ndict[str('j')] = [0,1,0,1,1,0]\ndict[str('k')] = [1,0,1,0,0,0]\ndict[str('l')] = [1,1,1,0,0,0]\ndict[str('m')] = [1,0,1,1,0,0]\ndict[str('n')] = [1,0,1,1,1,0]\ndict[str('o')] = [1,0,1,0,1,0]\ndict[str('p')] = [1,1,1,1,0,0]\ndict[str('q')] = [1,1,1,1,1,0]\ndict[str('r')] = [1,1,1,0,1,0]\ndict[str('s')] = [0,1,1,1,0,0]\ndict[str('t')] = [0,1,1,1,1,0]\ndict[str('u')] = [1,0,1,0,0,1]\ndict[str('v')] = [1,1,1,0,0,1]\ndict[str('w')] = [0,1,0,1,1,1]\ndict[str('x')] = [1,0,1,1,0,1]\ndict[str('y')] = [1,0,1,1,1,1]\ndict[str('z')] = [1,0,1,0,1,1]\ndict[str('numInd')] = [0,0,1,1,1,1] #this is used as the indicator when going from letter to numbers\ndict[str('1')] = [1,0,0,0,0,0]#start of numbers\ndict[str('2')] = [1,1,0,0,0,0]\ndict[str('3')] = [1,0,0,1,0,0]\ndict[str('4')] = [1,0,0,1,1,0]\ndict[str('5')] = [1,0,0,0,1,0]\ndict[str('6')] = [1,1,0,1,0,0]\ndict[str('7')] = [1,1,0,1,1,0]\ndict[str('8')] = [1,1,0,0,1,0]\ndict[str('9')] = [0,1,0,1,0,0]\ndict[str('0')] = [0,1,0,1,1,0]\ndict[str('puncInd')] = [0,0,0,1,1,1] #this is used as the indicator for punctuations\ndict[str(',')] = [0,0,1,0,0,0]#start of punctuation\ndict[str(':')] = [0,1,0,0,1,0]\ndict[str('!')] = [0,1,1,0,1,0]\ndict[str('.')] = [0,1,0,0,1,1]\ndict[str('?')] = [0,1,1,0,0,1]\ndict[str(';')] = [0,1,1,0,0,0]\n\n\n#set up the output pins\ntl = 2\nml = 3\nbl = 4\ntr = 17\nmr = 27\nbr = 22\n\nGPIO.setup(tl, GPIO.OUT)\nGPIO.setup(ml, GPIO.OUT)\nGPIO.setup(bl, GPIO.OUT)\nGPIO.setup(tr, GPIO.OUT)\nGPIO.setup(mr, GPIO.OUT)\nGPIO.setup(br, GPIO.OUT)\n\n#GPIO Test\nprint(\"Confirming GPIO Setup...\")\nGPIO.output(tl, GPIO.HIGH)\nGPIO.output(ml, GPIO.HIGH)\nGPIO.output(bl, GPIO.HIGH)\nGPIO.output(tr, GPIO.HIGH)\nGPIO.output(mr, GPIO.HIGH)\nGPIO.output(br, GPIO.HIGH)\ntime.sleep(1)\nprint(\"Confirming GPIO Setup......\")\nGPIO.output(tl, GPIO.LOW)\nGPIO.output(ml, GPIO.LOW)\nGPIO.output(bl, GPIO.LOW)\nGPIO.output(tr, GPIO.LOW)\nGPIO.output(mr, GPIO.LOW)\nGPIO.output(br, GPIO.LOW)\ntime.sleep(1)\nprint(\"Confirming GPIO Setup..........\")\nprint(\"GPIO Setup Complete!\")\n\n#opening target file\ntextFile = open('Text_File.txt', 'r')\n\n#read all lines into stringFile array\nstringFile = textFile.read().split('\\n')\n\n#determine number of lines in the file\nnumLines = len(stringFile)\n\n#initialize array that will store each element in file\ntextFileArray = []\nscrollDir = 0\ntextPos = -1\nletterToPrint = \"\"\n\nfor i in range(numLines):\n for j in range (len(stringFile[i])):\n if (stringFile[i][j] == \" \" or stringFile[i][j] == \"\\x0c\"):\n j=j+1\n else:\n textFileArray.append(stringFile[i][j])\n j=j+1\ni=i+1\n \n#initialize screen size for pygame\nscreen = pygame.display.set_mode((320,240))\n\nwhile True:\n for e in pygame.event.get():\n if e.type == pygame.QUIT:\n pygame.quit()\n\n if e.type == pygame.MOUSEBUTTONDOWN:\n if((textPos==0 or textPos==-1) and e.button == 5):\n print(\"You are at the beginning of the document!\")\n textPos = 0\n #PLAY AUDIO HERE\n if(textPos >= (len(textFileArray)-1) and e.button == 4):\n print(\"Reached end of document!\")\n textPos = len(textFileArray) -1\n \n elif e.button == 4: #positive direction sequence\n if((ord(textFileArray[textPos])>=65 and ord(textFileArray[textPos])<=122) and (ord(textFileArray[textPos+1])>=48 and ord(textFileArray[textPos+1])<=58)):\n print(\"numInd\")\n print('o'+\"\\t\"+'x'+\"\\n\"+'o'+\"\\t\"+'x'+\"\\n\"+'x'+\"\\t\"+'x')\n #GPIO.output(tl, GPIO.LOW)\n #GPIO.output(ml, GPIO.LOW)\n #GPIO.output(bl, GPIO.HIGH)\n #GPIO.output(tr, GPIO.HIGH)\n #GPIO.output(mr, GPIO.HIGH)\n #GPIO.output(br, GPIO.HIGH)\n \n elif((ord(textFileArray[textPos+1])==44) or (ord(textFileArray[textPos+1])==58) or (ord(textFileArray[textPos+1])==33) or (ord(textFileArray[textPos+1])==46) or (ord(textFileArray[textPos+1])==63) or (ord(textFileArray[textPos+1])==59)):\n print(\"puncInd\")\n print('o'+\"\\t\"+'x'+\"\\n\"+'o'+\"\\t\"+'x'+\"\\n\"+'o'+\"\\t\"+'x')\n #GPIO.output(tl, GPIO.LOW)\n #GPIO.output(ml, GPIO.LOW)\n #GPIO.output(bl, GPIO.LOW)\n #GPIO.output(tr, GPIO.HIGH)\n #GPIO.output(mr, GPIO.HIGH)\n #GPIO.output(br, GPIO.HIGH)\n\n \n \n \n letterToPrint = textFileArray[textPos+1]\n textPos = textPos + 1\n elif e.button == 5: #negative direction sequence\n if((ord(textFileArray[textPos])>=65 and ord(textFileArray[textPos])<=122) and (ord(textFileArray[textPos-1])>=48 and ord(textFileArray[textPos-1])<=58)):\n print(\"numInd\")\n print('o'+\"\\t\"+'x'+\"\\n\"+'o'+\"\\t\"+'x'+\"\\n\"+'x'+\"\\t\"+'x')\n #GPIO.output(tl, GPIO.LOW)\n #GPIO.output(ml, GPIO.LOW)\n #GPIO.output(bl, GPIO.HIGH)\n #GPIO.output(tr, GPIO.HIGH)\n #GPIO.output(mr, GPIO.HIGH)\n #GPIO.output(br, GPIO.HIGH)\n\n elif((ord(textFileArray[textPos-1])==44) or (ord(textFileArray[textPos-1])==58) or (ord(textFileArray[textPos-1])==33) or (ord(textFileArray[textPos-1])==46) or (ord(textFileArray[textPos-1])==63) or (ord(textFileArray[textPos-1])==59)):\n print(\"puncInd\")\n print('o'+\"\\t\"+'x'+\"\\n\"+'o'+\"\\t\"+'x'+\"\\n\"+'o'+\"\\t\"+'x')\n #GPIO.output(tl, GPIO.LOW)\n #GPIO.output(ml, GPIO.LOW)\n #GPIO.output(bl, GPIO.LOW)\n #GPIO.output(tr, GPIO.HIGH)\n #GPIO.output(mr, GPIO.HIGH)\n #GPIO.output(br, GPIO.HIGH)\n \n letterToPrint = textFileArray[textPos-1]\n textPos = textPos - 1\n\n \n if letterToPrint in dict:\n if dict[letterToPrint][0] == 1:\n #tl = 'x'\n GPIO.output(tl, GPIO.HIGH)\n else:\n #tl = 'o'\n GPIO.output(tl, GPIO.LOW)\n if dict[letterToPrint][1] == 1:\n #ml = 'x'\n GPIO.output(ml, GPIO.HIGH)\n else:\n #ml = 'o'\n GPIO.output(ml, GPIO.LOW)\n if dict[letterToPrint][2] == 1:\n #bl = 'x'\n GPIO.output(bl, GPIO.HIGH)\n else:\n #bl = 'o'\n GPIO.output(bl, GPIO.LOW)\n if dict[letterToPrint][3] == 1:\n #tr = 'x'\n GPIO.output(tr, GPIO.HIGH)\n else:\n #tr = 'o'\n GPIO.output(tr, GPIO.LOW)\n if dict[letterToPrint][4] == 1:\n #mr = 'x'\n GPIO.output(mr, GPIO.HIGH)\n else:\n #mr = 'o'\n GPIO.output(mr, GPIO.LOW)\n if dict[letterToPrint][5] == 1:\n #br = 'x'\n GPIO.output(br, GPIO.HIGH)\n else:\n #br = 'o'\n GPIO.output(br, GPIO.LOW)\n #print(tl+\"\\t\"+tr+\"\\n\"+ml+\"\\t\"+mr+\"\\n\"+bl+\"\\t\"+br)\n print(textPos)\n \n\n\n\n time.sleep(0.05)\n pygame.display.update()\n" }, { "alpha_fraction": 0.7257142663002014, "alphanum_fraction": 0.7257142663002014, "avg_line_length": 13.416666984558105, "blob_id": "732c5e4117a50681867346ea7733612dba34ce7b", "content_id": "ae3c60b9454226d59e67c43c68c7350c9efe6614", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 175, "license_type": "no_license", "max_line_length": 30, "num_lines": 12, "path": "/Programs/GUI/Code V2/runProgram.py", "repo_name": "shubhamguptasr/EyeBraille", "src_encoding": "UTF-8", "text": "from threading import Thread\nimport os\n\ndef runGUI():\n import GUI\n\ndef runConv():\n import convertOutput\n\n\nThread(target=runGUI).start()\nThread(target=runConv).start()\n\n\n" }, { "alpha_fraction": 0.6487603187561035, "alphanum_fraction": 0.6694214940071106, "avg_line_length": 14.0625, "blob_id": "168db680dbf7e53a0e9ec66ed674c0623e12d06d", "content_id": "e89af968f3363f54dc880920e18d538dc1b07097", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 242, "license_type": "no_license", "max_line_length": 30, "num_lines": 16, "path": "/Programs/GUI/Code V2/gpioTest.py", "repo_name": "shubhamguptasr/EyeBraille", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\npin=3\n\nGPIO.setup(pin,GPIO.OUT)\n\nwhile(True):\n \n GPIO.output(pin,GPIO.HIGH)\n time.sleep(0.5)\n GPIO.output(pin,GPIO.LOW)\n time.sleep(0.5)\n\n" } ]
13
avbezdolny/game2048_kivy
https://github.com/avbezdolny/game2048_kivy
0fb2322a59f9f81e98db5b677792b8bd020e0c05
856b2411a9b06bb98fc898e3bfe29fddfd21031c
0b425f4844aedd36c1654c03b2e8574e0b0809b5
refs/heads/master
2021-07-05T12:19:50.636924
2021-02-07T09:10:43
2021-02-07T09:10:43
226,525,702
3
1
null
null
null
null
null
[ { "alpha_fraction": 0.47338247299194336, "alphanum_fraction": 0.49467650055885315, "avg_line_length": 36.15625, "blob_id": "4d3618fc949277345ea384b87f729d1e3ba683f6", "content_id": "498187be86558adb793b5928273ea6e59f28b5ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1221, "license_type": "no_license", "max_line_length": 171, "num_lines": 32, "path": "/game2048.spec", "repo_name": "avbezdolny/game2048_kivy", "src_encoding": "UTF-8", "text": "# -*- mode: python -*-\r\nfrom kivy_deps import sdl2, glew, gstreamer\r\nblock_cipher = None\r\n\r\n\r\na = Analysis(['main.py'],\r\n pathex=['C:\\\\Users\\\\avbez\\\\Desktop\\\\2048_kivy'],\r\n binaries=[],\r\n datas=[('game2048.kv', '.'), ('Rubik.ttf', '.'), ('click.wav', '.'), ('move.wav', '.'), ('popup.wav', '.'), ('data/*.png', 'data'), ('data/*.atlas', 'data')],\r\n hiddenimports=[],\r\n hookspath=[],\r\n runtime_hooks=[],\r\n excludes=[],\r\n win_no_prefer_redirects=False,\r\n win_private_assemblies=False,\r\n cipher=block_cipher,\r\n noarchive=False)\r\npyz = PYZ(a.pure, a.zipped_data,\r\n cipher=block_cipher)\r\nexe = EXE(pyz, Tree('C:\\\\Users\\\\avbez\\\\Desktop\\\\2048_kivy'),\r\n a.scripts,\r\n a.binaries,\r\n a.zipfiles,\r\n a.datas,\r\n *[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins + gstreamer.dep_bins)],\r\n name='game2048',\r\n debug=False,\r\n bootloader_ignore_signals=False,\r\n strip=False,\r\n upx=True,\r\n runtime_tmpdir=None,\r\n console=False, icon='C:\\\\Users\\\\avbez\\\\Desktop\\\\2048_kivy\\\\game2048.ico' )\r\n" }, { "alpha_fraction": 0.5363723635673523, "alphanum_fraction": 0.5560098886489868, "avg_line_length": 39.35490417480469, "blob_id": "32ea6ab6b166eb3a10f16c1a61967ea5c9ebac27", "content_id": "d7d7c3bab5c9f0de1a1d9d92c47080ac3129d079", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19836, "license_type": "no_license", "max_line_length": 529, "num_lines": 479, "path": "/main.py", "repo_name": "avbezdolny/game2048_kivy", "src_encoding": "UTF-8", "text": "#!python3\r\n# -*- coding: utf-8 -*-\r\n\r\nimport kivy\r\nfrom kivy.app import App\r\nfrom kivy.clock import Clock\r\nfrom kivy.core.window import Window\r\nfrom kivy.core.window import Keyboard\r\nfrom kivy.core.audio import SoundLoader\r\nfrom kivy.utils import get_color_from_hex, platform\r\nfrom kivy.uix.widget import Widget\r\nfrom kivy.animation import Animation\r\nfrom kivy.uix.behaviors import ButtonBehavior\r\nfrom kivy.uix.image import Image\r\nfrom kivy.properties import ObjectProperty, DictProperty, ListProperty, NumericProperty, StringProperty, BooleanProperty\r\nfrom kivy.uix.modalview import ModalView\r\nfrom kivy.storage.dictstore import DictStore\r\nfrom os.path import join, dirname\r\nimport random\r\nimport math\r\nimport sys\r\n\r\n\r\n# Returns path containing content - either locally or in pyinstaller tmp file\r\ndef resourcePath():\r\n if hasattr(sys, '_MEIPASS'):\r\n return join(sys._MEIPASS)\r\n return join(dirname(__file__))\r\n\r\n\r\nclass Board(Widget):\r\n trace = BooleanProperty(False)\r\n\r\n def on_touch_down(self, touch):\r\n if not App.get_running_app().block:\r\n self.trace = True\r\n\r\n def on_touch_move(self, touch):\r\n if self.trace and not App.get_running_app().block:\r\n touch_path = min(Window.width, Window.height) / 24\r\n if math.fabs(touch.dpos[0]) >= touch_path or math.fabs(touch.dpos[1]) >= touch_path:\r\n if math.fabs(touch.dpos[0]) > math.fabs(touch.dpos[1]):\r\n if touch.dpos[0] < 0 and touch.pos[0] < Window.width * 0.75:\r\n self.trace = False\r\n App.get_running_app().move(-1, 0)\r\n elif touch.dpos[0] > 0 and touch.pos[0] > Window.width * 0.25:\r\n self.trace = False\r\n App.get_running_app().move(1, 0)\r\n elif math.fabs(touch.dpos[1]) > math.fabs(touch.dpos[0]):\r\n if touch.dpos[1] < 0 and touch.pos[1] < Window.height * 0.75:\r\n self.trace = False\r\n App.get_running_app().move(0, -1)\r\n elif touch.dpos[1] > 0 and touch.pos[1] > Window.height * 0.25:\r\n self.trace = False\r\n App.get_running_app().move(0, 1)\r\n\r\n def on_touch_up(self, touch):\r\n self.trace = False\r\n\r\n\r\nclass Cell(Widget):\r\n pass\r\n\r\n\r\nclass Tile(Widget):\r\n number = NumericProperty(2)\r\n number_new = NumericProperty(2)\r\n check = BooleanProperty(False)\r\n\r\n colors = {\r\n 2: '#e53935',\r\n 4: '#1e88e5',\r\n 8: '#43a047',\r\n 16: '#fdd835',\r\n 32: '#d81b60',\r\n 64: '#039be5',\r\n 128: '#66bb6a',\r\n 256: '#ffb300',\r\n 512: '#e53935',\r\n 1024: '#1e88e5',\r\n 2048: '#43a047',\r\n 4096: '#fdd835',\r\n 8192: '#d81b60',\r\n 16384: '#039be5',\r\n 32768: '#66bb6a',\r\n 65536: '#ffb300',\r\n 131072: '#8d6e63'\r\n }\r\n\r\n\r\nclass Btn(ButtonBehavior, Widget):\r\n text = StringProperty('btn')\r\n color = ListProperty(get_color_from_hex('#26a69a40'))\r\n text_color = ListProperty(get_color_from_hex('#26a69a'))\r\n\r\n def __init__(self, **kwargs):\r\n super(Btn, self).__init__(**kwargs)\r\n\r\n\r\nclass SoundBtn(ButtonBehavior, Image):\r\n def __init__(self, **kwargs):\r\n super(SoundBtn, self).__init__(**kwargs)\r\n\r\n\r\nclass ViewChoice(Widget):\r\n text = StringProperty('...')\r\n\r\n\r\nclass ViewInfo(Widget):\r\n text = StringProperty('...')\r\n\r\n\r\nclass Game2048App(App):\r\n Window.clearcolor = get_color_from_hex('#000000')\r\n if platform in ['win', 'linux', 'mac']:\r\n icon = 'data/icon.png'\r\n title = '2048'\r\n Window.size = (480, 800)\r\n Window.left = 100\r\n Window.top = 100\r\n\r\n board = ObjectProperty()\r\n cell_size = ListProperty([100, 100])\r\n score = NumericProperty(0)\r\n best = NumericProperty(0)\r\n step = NumericProperty(0)\r\n savepoint = NumericProperty(0)\r\n savepoint_score = NumericProperty(0)\r\n savepoint_step = NumericProperty(0)\r\n check_savepoint = BooleanProperty(False)\r\n block = BooleanProperty(True)\r\n moving = BooleanProperty(False)\r\n game_over = BooleanProperty(False)\r\n key_vectors = DictProperty()\r\n tiles = None\r\n remove_tiles = None\r\n savepoint_tiles = None\r\n store = None\r\n view_exit = None\r\n view_info = None\r\n view_new = None\r\n view_gameover = None\r\n view_update = None\r\n view_savepoint = None\r\n\r\n is_sound = BooleanProperty(True)\r\n sound_click = None\r\n sound_popup = None\r\n\r\n def on_start(self):\r\n self.board = self.root.ids.board\r\n\r\n self.key_vectors = {\r\n Keyboard.keycodes['up']: (0, 1),\r\n Keyboard.keycodes['right']: (1, 0),\r\n Keyboard.keycodes['down']: (0, -1),\r\n Keyboard.keycodes['left']: (-1, 0),\r\n }\r\n\r\n # tiles\r\n self.cell_size = [(self.board.width - 3 * self.board.width / 40) / 4] * 2\r\n self.tiles = [[None for i in range(4)] for j in range(4)]\r\n self.remove_tiles = [[None for i in range(4)] for j in range(4)]\r\n\r\n # sounds\r\n self.sound_click = SoundLoader.load('click.wav')\r\n self.sound_popup = SoundLoader.load('popup.wav')\r\n\r\n # exit dialog\r\n self.view_exit = ModalView(size_hint=(None, None), size=[self.board.width, self.board.width * 0.75], auto_dismiss=False, background = 'data/background.png')\r\n self.view_exit.add_widget(ViewChoice(text='Exit the game?'))\r\n self.view_exit.children[0].ids.yes_btn.bind(on_release=self.stop)\r\n\r\n # info dialog\r\n self.view_info = ModalView(size_hint=(None, None), size=[self.board.width, self.board.width * 0.75], auto_dismiss=False, background = 'data/background.png')\r\n self.view_info.add_widget(ViewInfo(text='[size=' + str(int(min(self.view_info.width, self.view_info.height) / 14)) + ']GAME 2048[/size][size=' + str(int(min(self.view_info.width, self.view_info.height) / 20)) + ']\\n\\nSwipe to move the tiles. When two tiles with the same number touch, they merge into one. Get to the 2048 tile and reach a high score!\\nBased by Gabriele Cirulli original game :)[/size][size=' + str(int(min(self.view_info.width, self.view_info.height) / 30)) + ']\\n\\n* * *\\n(c) Anton Bezdolny, 2021 / ver. 2.2.1 /[/size]'))\r\n\r\n # new game dialog\r\n self.view_new = ModalView(size_hint=(None, None), size=[self.board.width, self.board.width * 0.75], auto_dismiss=False, background = 'data/background.png')\r\n self.view_new.add_widget(ViewChoice(text='Start new game?'))\r\n self.view_new.children[0].ids.yes_btn.bind(on_release=self.new_game)\r\n\r\n # game over dialog\r\n self.view_gameover = ModalView(size_hint=(None, None), size=[self.board.width, self.board.width * 0.75], auto_dismiss=False, background = 'data/background.png')\r\n self.view_gameover.add_widget(ViewInfo(text='* GAME OVER *'))\r\n\r\n # update savepoint dialog\r\n self.view_update = ModalView(size_hint=(None, None), size=[self.board.width, self.board.width * 0.75], auto_dismiss=False, background = 'data/background.png')\r\n self.view_update.add_widget(ViewInfo())\r\n\r\n # load savepoint dialog\r\n self.view_savepoint = ModalView(size_hint=(None, None), size=[self.board.width, self.board.width * 0.75], auto_dismiss=False, background = 'data/background.png')\r\n self.view_savepoint.add_widget(ViewChoice())\r\n self.view_savepoint.children[0].ids.yes_btn.bind(on_release=self.load_savepoint)\r\n self.view_savepoint.children[0].ids.no_btn.bind(on_release=self.pass_savepoint)\r\n\r\n # bind's\r\n Window.bind(on_key_down=self.on_key_down)\r\n if platform in ['win', 'linux', 'mac']: Window.bind(on_request_close=self.on_request_close)\r\n self.board.bind(pos=Clock.schedule_once(self.resize, 0.150))\r\n\r\n # game start\r\n # load data settings\r\n if platform in ['win', 'linux', 'mac']: # desktop\r\n self.store = DictStore(join(self.user_data_dir, 'store.dat'))\r\n else: # if platform in ['android', 'ios']\r\n self.store = DictStore('store.dat') # android API 26+ без запроса разрешений доступа\r\n if self.store.exists('matrix'):\r\n self.load_data()\r\n else:\r\n self.new_game()\r\n\r\n def sound_move_play(self):\r\n sound_move = SoundLoader.load('move.wav')\r\n if sound_move: sound_move.play()\r\n\r\n def cell_pos(self, row, col):\r\n return (self.board.x + self.cell_size[0] * row + row * self.board.width / 40, self.board.y + self.cell_size[0] * col + col * self.board.width / 40)\r\n\r\n def all_cells(self, flip_row=False, flip_col=False):\r\n for row in (reversed(range(4)) if flip_row else range(4)):\r\n for col in (reversed(range(4)) if flip_col else range(4)):\r\n yield (row, col)\r\n\r\n def valid_cell(self, row, col):\r\n return (row >= 0 and col >= 0 and row <= 3 and col <= 3)\r\n\r\n def can_move(self, row, col):\r\n return (self.valid_cell(row, col) and self.tiles[row][col] is None)\r\n\r\n def can_combine(self, row, col, number, check):\r\n return (self.valid_cell(row, col) and\r\n self.tiles[row][col] is not None and\r\n self.tiles[row][col].number_new == number and\r\n not self.tiles[row][col].check and\r\n not check)\r\n\r\n def count_value(self, value): # counter same tiles\r\n i = 0\r\n for row, col in self.all_cells():\r\n if self.tiles[row][col] and self.tiles[row][col].number_new == value:\r\n i += 1\r\n return i\r\n\r\n def is_deadlocked(self):\r\n for row, col in self.all_cells():\r\n if self.tiles[row][col] is None:\r\n return False\r\n if self.can_combine(row + 1, col, self.tiles[row][col].number, self.tiles[row][col].check) or self.can_combine(row, col + 1, self.tiles[row][col].number, self.tiles[row][col].check):\r\n return False\r\n return True\r\n\r\n def on_key_down(self, window, key, *args):\r\n if key in self.key_vectors and not self.block:\r\n self.move(*self.key_vectors[key])\r\n elif key in [27, 4]: # ESC and BACK_BUTTON\r\n if self.is_sound and self.sound_popup: self.sound_popup.play()\r\n self.view_exit.open()\r\n return True\r\n\r\n def on_request_close(self, *args):\r\n if self.is_sound and self.sound_popup: self.sound_popup.play()\r\n self.view_exit.open()\r\n return True\r\n\r\n def save_data(self):\r\n matrix = [[None for i in range(4)] for j in range(4)]\r\n for row, col in self.all_cells():\r\n if self.tiles[row][col]:\r\n matrix[row][col] = self.tiles[row][col].number\r\n self.store.put('matrix', value=matrix)\r\n self.store.put('score', value=self.score)\r\n self.store.put('best', value=self.best)\r\n self.store.put('step', value=self.step)\r\n self.store.put('game_over', value=self.game_over)\r\n self.store.put('savepoint', value=self.savepoint)\r\n self.store.put('savepoint_score', value=self.savepoint_score)\r\n self.store.put('savepoint_step', value=self.savepoint_step)\r\n self.store.put('savepoint_matrix', value=self.savepoint_tiles)\r\n self.store.put('is_sound', value=self.is_sound)\r\n\r\n def load_data(self):\r\n self.score = self.store.get('score')['value']\r\n self.best = self.store.get('best')['value']\r\n self.step = self.store.get('step')['value']\r\n self.game_over = self.store.get('game_over')['value']\r\n self.savepoint = self.store.get('savepoint')['value']\r\n self.savepoint_score = self.store.get('savepoint_score')['value']\r\n self.savepoint_step = self.store.get('savepoint_step')['value']\r\n\r\n matrix = self.store.get('matrix')['value']\r\n for row, col in self.all_cells():\r\n if matrix[row][col]:\r\n tile = Tile(number=matrix[row][col], number_new=matrix[row][col], pos=self.cell_pos(row, col))\r\n self.tiles[row][col] = tile\r\n self.board.add_widget(tile)\r\n\r\n self.savepoint_tiles = self.store.get('savepoint_matrix')['value']\r\n self.is_sound = self.store.get('is_sound')['value']\r\n self.block = True if self.game_over else False\r\n\r\n def load_savepoint(self, *args):\r\n self.score = self.savepoint_score\r\n self.step = self.savepoint_step\r\n self.game_over = False\r\n\r\n for row, col in self.all_cells():\r\n if self.savepoint_tiles[row][col]:\r\n tile = Tile(number=self.savepoint_tiles[row][col], number_new=self.savepoint_tiles[row][col], pos=self.cell_pos(row, col))\r\n self.tiles[row][col] = tile\r\n self.board.add_widget(tile)\r\n\r\n self.block = False\r\n\r\n def pass_savepoint(self, *args):\r\n self.new_tile()\r\n self.new_tile()\r\n\r\n def new_game(self, *args):\r\n self.score = 0\r\n self.step = 0\r\n self.game_over = False\r\n self.moving = False\r\n self.check_savepoint = False\r\n self.block = True\r\n\r\n # clear old widget\r\n if self.tiles:\r\n for row, col in self.all_cells():\r\n remove_tile = self.tiles[row][col]\r\n if remove_tile:\r\n self.board.remove_widget(remove_tile)\r\n self.tiles[row][col] = None\r\n\r\n if self.savepoint > 0:\r\n self.view_savepoint.children[0].text = 'Load savepoint\\n' + str(self.savepoint) + '?'\r\n self.view_savepoint.open()\r\n else:\r\n self.new_tile()\r\n self.new_tile()\r\n '''rnumb = 2\r\n for row, col in self.all_cells(): # TEST ALL TILE'S NUMBER !!!\r\n rnumb *= 2\r\n tile = Tile(number=rnumb, number_new=rnumb, pos=self.cell_pos(row, col))\r\n self.tiles[row][col] = tile\r\n self.board.add_widget(tile)'''\r\n\r\n def new_tile(self):\r\n empty_cells = [(row, col) for row, col in self.all_cells() if self.tiles[row][col] is None]\r\n row, col = random.choice(empty_cells)\r\n rnumb = (2 if random.randint(1, 100) <= 90 else 4)\r\n\r\n tile = Tile(number=rnumb, number_new=rnumb, pos=self.cell_pos(row, col))\r\n self.tiles[row][col] = tile\r\n self.board.add_widget(tile)\r\n\r\n # game analyze\r\n if len(empty_cells) == 1 and self.is_deadlocked():\r\n self.game_over = True\r\n Clock.schedule_once(self.after_game_over, 0.5)\r\n else:\r\n if self.check_savepoint:\r\n self.check_savepoint = False\r\n self.savepoint_score = self.score\r\n self.savepoint_step = self.step\r\n self.savepoint_tiles = [[None for i in range(4)] for j in range(4)]\r\n for r, c in self.all_cells():\r\n if self.tiles[r][c]:\r\n self.savepoint_tiles[r][c] = self.tiles[r][c].number\r\n self.view_update.children[0].text = 'New savepoint\\n' + str(self.savepoint) + '!'\r\n Clock.schedule_once(self.after_update_savepoint, 0.5)\r\n\r\n self.block = False\r\n\r\n def after_game_over(self, *args):\r\n if self.is_sound and self.sound_popup: self.sound_popup.play()\r\n self.view_gameover.open()\r\n\r\n def after_update_savepoint(self, *args):\r\n if self.is_sound and self.sound_popup: self.sound_popup.play()\r\n self.view_update.open()\r\n\r\n def move(self, dir_x, dir_y):\r\n if not self.block:\r\n self.block = True\r\n\r\n for row, col in self.all_cells(dir_x > 0, dir_y > 0):\r\n tile = self.tiles[row][col]\r\n if not tile:\r\n continue\r\n else:\r\n x, y = row, col\r\n while self.can_move(x + dir_x, y + dir_y):\r\n self.tiles[x][y] = None\r\n x += dir_x\r\n y += dir_y\r\n self.tiles[x][y] = tile\r\n\r\n if self.can_combine(x + dir_x, y + dir_y, tile.number, tile.check):\r\n self.tiles[x][y] = None\r\n x += dir_x\r\n y += dir_y\r\n self.remove_tiles[x][y] = self.tiles[x][y] # remove widget\r\n self.tiles[x][y] = tile\r\n tile.number_new *= 2\r\n tile.check = True # check this join numbers\r\n self.score += tile.number_new\r\n\r\n if self.score > self.best: # best score\r\n self.best = self.score\r\n\r\n # savepoint\r\n if tile.number_new >= 1024 and tile.number_new >= self.savepoint and self.count_value(tile.number_new) == 1:\r\n self.check_savepoint = True\r\n self.savepoint = tile.number_new\r\n\r\n if x == row and y == col:\r\n continue # nothing has happened\r\n\r\n anim = Animation(pos=self.cell_pos(x, y), duration=0.25, transition='linear')\r\n anim.start(tile)\r\n if not self.moving:\r\n self.moving = True\r\n anim.bind(on_complete=self.after_move)\r\n if self.is_sound: self.sound_move_play()\r\n # if no moves\r\n if not self.moving:\r\n self.block = False\r\n\r\n def after_move(self, *args):\r\n self.moving = False\r\n self.step += 1\r\n\r\n for row, col in self.all_cells():\r\n remove_tile = self.remove_tiles[row][col]\r\n if remove_tile:\r\n self.board.remove_widget(remove_tile)\r\n self.remove_tiles[row][col] = None\r\n\r\n tile = self.tiles[row][col]\r\n if tile:\r\n tile.number = tile.number_new\r\n tile.check = False\r\n\r\n self.new_tile()\r\n\r\n def resize(self, *args):\r\n self.cell_size = [(self.board.width - 3 * self.board.width / 40) / 4] * 2\r\n for row, col in self.all_cells():\r\n tile = self.tiles[row][col]\r\n if tile:\r\n anim = Animation(pos=self.cell_pos(row, col), duration=0.25, transition='linear')\r\n anim.start(tile)\r\n\r\n # dialog's\r\n self.view_exit.size = [self.board.width, self.board.width * 0.75]\r\n self.view_info.size = [self.board.width, self.board.width * 0.75]\r\n self.view_info.children[0].text = '[size=' + str(int(min(self.view_info.width, self.view_info.height) / 14)) + ']GAME 2048[/size][size=' + str(int(min(self.view_info.width, self.view_info.height) / 20)) + ']\\n\\nSwipe to move the tiles. When two tiles with the same number touch, they merge into one. Get to the 2048 tile and reach a high score!\\nBased by Gabriele Cirulli original game :)[/size][size=' + str(int(min(self.view_info.width, self.view_info.height) / 30)) + ']\\n\\n* * *\\n(c) Anton Bezdolny, 2021 / ver. 2.2.1 /[/size]'\r\n self.view_new.size = [self.board.width, self.board.width * 0.75]\r\n self.view_gameover.size = [self.board.width, self.board.width * 0.75]\r\n self.view_update.size = [self.board.width, self.board.width * 0.75]\r\n self.view_savepoint.size = [self.board.width, self.board.width * 0.75]\r\n\r\n def on_pause(self):\r\n self.save_data()\r\n return True\r\n\r\n def on_resume(self):\r\n pass\r\n\r\n def on_stop(self):\r\n self.save_data()\r\n sys.exit(0) # for Android and other OS\r\n\r\n\r\nif __name__ == '__main__':\r\n if platform in ['win', 'linux', 'mac']: # desktop\r\n kivy.resources.resource_add_path(resourcePath())\r\n Game2048App().run()\r\n" }, { "alpha_fraction": 0.7275693416595459, "alphanum_fraction": 0.7601957321166992, "avg_line_length": 28.190475463867188, "blob_id": "a098676b856e93b8ce7e768b259894254bbc87f4", "content_id": "ffe5e6e1350cf36cddc4344fefcde1b19d8ca359", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 889, "license_type": "no_license", "max_line_length": 85, "num_lines": 21, "path": "/README.md", "repo_name": "avbezdolny/game2048_kivy", "src_encoding": "UTF-8", "text": "![icon](/data/icon.png)\n\n# GAME 2048 🎮\n\n*Join the numbers and get to the 2048 tile or more :)*\n\nSwipe to move the tiles.\nWhen two tiles with the same number touch, they merge into one.\nGet to the 2048 tile and reach a high score!\nBased by Gabriele Cirulli original game :)\n\n---\n\n# ИГРА 2048 🎮\n\n*Объедините числа и получите плитку 2048 или еще большую :)*\n\nСмахивайте плитки жестами по экрану для их движения.\nКогда две плитки с одинаковыми номерами касаются друг друга, они складываются в одну.\nНаберите максимальное количество очков и получите плитку с наибольшим числом!\nОсновано на оригинальной игре Габриэле Чирулли :)\n" } ]
3
wazari972/goto-file
https://github.com/wazari972/goto-file
d689e7633cca041712b25374baf16730d163df73
fcc7f9307be7826e89d2cc56350b9ca7a071cdeb
81e5747d815187e79fed89df936dba262d254a43
refs/heads/master
2021-01-10T02:14:47.980284
2015-11-22T17:41:35
2015-11-22T17:41:35
46,668,313
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6301369667053223, "alphanum_fraction": 0.6575342416763306, "avg_line_length": 23.66666603088379, "blob_id": "0be0edaa759a2c4b85d86a150b1b21230fa65829", "content_id": "22903f7c90901b9fbba18a5cb8bbcab18500e25c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 73, "license_type": "no_license", "max_line_length": 59, "num_lines": 3, "path": "/bin/goto-emacs", "repo_name": "wazari972/goto-file", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\necho emacsclient --eval \"goto-auto-and-highlight '$1' '$2'\"" }, { "alpha_fraction": 0.5950334072113037, "alphanum_fraction": 0.5955109596252441, "avg_line_length": 25.846153259277344, "blob_id": "69a7b722a4c74e144fb4bab829c38c64790dea2a", "content_id": "cb86232f4c5fadac03d9e2bdf32bbdfe02c40e6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2094, "license_type": "no_license", "max_line_length": 96, "num_lines": 78, "path": "/gdb-goto.py", "repo_name": "wazari972/goto-file", "src_encoding": "UTF-8", "text": "import gdb\n\nprev_position = \"\"\ndef send_position(filename, line):\n global prev_position\n current_position = \"{}:{}\".format(filename, line)\n if prev_position == current_position: return\n prev_position = current_position\n print(\"We're in {}.\".format(current_position))\n\ndef current_position():\n try:\n frame = gdb.selected_frame()\n except gdb.error:\n return # no frame available\n \n sal = frame.find_sal()\n if not sal: return\n\n line = sal.line\n if line == 0: return\n \n filename = sal.symtab.fullname()\n \n return filename, line\n \n# install prompt hook\ndef goto_prompt(current_prompt):\n try:\n if not auto_goto.self.value: return\n \n position = current_position()\n if not position: return\n \n send_position(*position)\n finally:\n return current_prompt\n\n# set auto-goto-emacs on|off\nclass auto_goto(gdb.Parameter):\n self = None\n \n def __init__(self):\n gdb.Parameter.__init__ (self, \"auto-goto-emacs\", gdb.COMMAND_OBSCURE, gdb.PARAM_BOOLEAN)\n auto_goto.self = self\n self.value = True\n \n def get_set_string(self):\n return \"Auto goto emacs is {}.\".format(\"enabled\" if self.value else \"disabled\")\n\n def get_show_string(self, svalue):\n return self.get_set_string()\n\n\nclass goto_emacs(gdb.Command):\n \"\"\"\\\nOpen file with emacs. If no argument is provided, try to send the current location. \\\nOtherwise, send directly the arguments.\"\"\"\n \n def __init__(self):\n gdb.Command.__init__ (self, \"goto-emacs\", gdb.COMMAND_OBSCURE)\n\n def invoke(self, args, from_tty):\n if not args:\n position = current_position()\n if position is None:\n print(\"Cannot get the current position.\")\n else:\n filename, line = position\n print(\"Goto {}:{}\".format(filename, line))\n send_position(filename, line)\n else:\n send_position(args)\n\ndef enable_goto_emacs():\n auto_goto()\n gdb.prompt_hook = goto_prompt\n goto_emacs()\n" } ]
2
gasgas4/all_your_browsers_belong_to_us
https://github.com/gasgas4/all_your_browsers_belong_to_us
5d74f860d44e85a908fd378ae7b43314973ceef9
1b7eb834ce57e24080142713e56da7fbbafbd1ba
4c8e20a5499f3ecedf5cc391db48b361b1e7368e
refs/heads/master
2018-01-16T08:32:15.782958
2016-04-08T19:58:51
2016-04-08T19:58:51
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7955800890922546, "alphanum_fraction": 0.7955800890922546, "avg_line_length": 179.5, "blob_id": "c853b71e1636c7ae9b14ed02978b1333c067a6eb", "content_id": "783fa85249ec2afdee2b1f95e4c920926a51efbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 362, "license_type": "no_license", "max_line_length": 326, "num_lines": 2, "path": "/exploits/mercury-browser/README.md", "repo_name": "gasgas4/all_your_browsers_belong_to_us", "src_encoding": "UTF-8", "text": "# Mercury Browser for Android RCE\nThis repository contains two different files. The first is ```libvplayer.so```, which is a custom native library that will execute ncat and start a bind shell through busybox when loaded. The second file is the python script, which is used to exploit the path traversal vulnerability in the WiFiManager's custom web service.\n\n" }, { "alpha_fraction": 0.5093023180961609, "alphanum_fraction": 0.5755813717842102, "avg_line_length": 30.851852416992188, "blob_id": "1dae8e1cee20a98c964e07b0a955900b05b75148", "content_id": "2f1a0ee2008fc62cc0701e7264134c4dc927b431", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 860, "license_type": "no_license", "max_line_length": 113, "num_lines": 27, "path": "/exploits/mercury-browser/upload_rce.py", "repo_name": "gasgas4/all_your_browsers_belong_to_us", "src_encoding": "UTF-8", "text": "import requests\nimport sys\n\ndef do_exploit():\n \n # Update IP address as needed\n url = \"http://192.168.3.128:8888/doupload?dir=\"\n path_traversl = \"../../../../data/data/com.ilegendsoft.mercury/libs/&id=15c516f6-cc7d-4c5b-8e40-6a1200e7b963\"\n headers = {\"Referer\": \"http://192.168.225.207:8888/\"}\n files = {\"libvplayer.0.so\": open(\"libvplayer.so\", \"rb\")}\n\n try:\n print(\"[*] Uploading shared library : libvplayer.so\")\n r = requests.post(\"\".join([url, path_traversl]), files=files, headers=headers)\n if r.status_code == 200:\n print(\"[*] Successfully uploaded\")\n print(\"[*] {0}\".format(r.text))\n else:\n print(\"[*] Could not upload\")\n except Exception as e:\n raise e\n\nif __name__ == \"__main__\":\n try:\n do_exploit()\n except KeyboardInterrupt:\n sys.exit(0)\n" }, { "alpha_fraction": 0.7780487537384033, "alphanum_fraction": 0.787804901599884, "avg_line_length": 57.57143020629883, "blob_id": "ef46ec8c4d139a3fb362c1065c03724bf0c47ab2", "content_id": "ee3b0253b2ff4626fd1ecc7424e3dc9e08eb961d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 410, "license_type": "no_license", "max_line_length": 145, "num_lines": 7, "path": "/README.md", "repo_name": "gasgas4/all_your_browsers_belong_to_us", "src_encoding": "UTF-8", "text": "# All Your Browsers Belong To Us\n\nThe **Infiltrate 2016** presentation materials include: \n\n- [The Dolphin Browser for Android exploit](https://github.com/LifeForm-Labs/all_your_browsers_belong_to_us/tree/master/exploits/dolphin-browser)\n- [The Mercury Browser for Android exploit](https://github.com/LifeForm-Labs/all_your_browsers_belong_to_us/tree/master/exploits/mercury-browser)\n- Presentation Deck (PDF)\n" } ]
3
mafrasiabi/Bayesian-GLM-for-Classification
https://github.com/mafrasiabi/Bayesian-GLM-for-Classification
b39f7d771ef5b4b721ea7c9dfdae04ebf20d9d4a
78def76c8a829f6bdcfe1990612482263191cf7b
7b64c15c3b960c8a35cb4cb6c437be45f1eb179f
refs/heads/master
2022-03-05T02:08:21.020468
2019-11-10T18:50:44
2019-11-10T18:50:44
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5325882434844971, "alphanum_fraction": 0.5463095903396606, "avg_line_length": 35.1728401184082, "blob_id": "0939cf1f2972bc6f7187acc6df268bbc4ef74b3a", "content_id": "431cfd1807496b0c0c9e2350d662182ddde3b206", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9037, "license_type": "no_license", "max_line_length": 127, "num_lines": 243, "path": "/pp3.py", "repo_name": "mafrasiabi/Bayesian-GLM-for-Classification", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python3\r\nimport sys\r\nimport numpy as np \r\nimport pandas as pd\r\nimport random\r\nimport math \r\nimport matplotlib.pyplot as plt \r\nimport pprint\r\nimport timeit\r\n\r\n#Function to read dataset based on name and randomly split into training and testing set\r\ndef read_csv(dataset_name):\r\n features = pd.read_csv(\"pp3data/\"+dataset_name+\".csv\", header = None).values\r\n labels = pd.read_csv(\"pp3data/labels-\"+dataset_name+\".csv\", header = None).values\r\n #irlstest is sample dataset to test w, we do not split it\r\n if dataset_name == \"irlstest\":\r\n return features, labels, features, labels\r\n else:\r\n dataset = np.column_stack((features,labels))\r\n #np.random.shuffle(dataset)\r\n #training set is 2/3rd of dataset and test set is remaining\r\n train_l = int(2/3*len(dataset))\r\n train, trainL, test, testL = dataset[:train_l,:-1], dataset[:train_l,-1:], dataset[train_l:,:-1], dataset[train_l:,-1:]\r\n return train, trainL, test, testL\r\n\r\n#Function to compute 1st and 2nd derivative for Logistic Regression\r\ndef compute_R_d_Logistic(a, t): \r\n y = sigmoid(-a) \r\n r = y * (1 - y)\r\n #First Derivative term\r\n d = t-y\r\n #Second Derivative term R is diagonal matrix of y(1-y)\r\n R = np.diag(r.ravel())\r\n return R, d\r\n\r\n#Function to compute 1st and 2nd derivative for Poisson Regression\r\ndef compute_R_d_Poisson(a, t): \r\n y = np.array([[math.exp(ai)] for ai in a]) \r\n r = y\r\n #First Derivative term\r\n d = t-y\r\n #Second Derivative term R is diagonal matrix of y\r\n R = np.diag(r.ravel())\r\n return R, d\r\n\r\n#Function to compute 1st and 2nd derivative for Ordinal Regression\r\ndef compute_R_d_Ordinal(a, t): \r\n phiJ = [-math.inf,-2,-1,0,1,math.inf]\r\n s = 1\r\n d = []\r\n r = []\r\n for i,ai in enumerate(a):\r\n ti = int(t[i][0])\r\n yiti = yij(ai,phiJ[ti],s)\r\n yiti_1 = yij(ai,phiJ[ti-1],s)\r\n d.append(yiti + yiti_1 - 1)\r\n r.append(s*s*(yiti*(1-yiti)+yiti_1*(yiti_1)))\r\n #print(d)\r\n #print(r)\r\n ri = np.array(r)\r\n R = np.diag(ri.ravel())\r\n return R, d\r\n\r\n#Prediction function for Logistic regression\r\ndef prediction_Logistic(a):\r\n y = sigmoid(-a) \r\n #Predict True label for values >=0.5\r\n y = [int(val>=0.5) for val in y] \r\n return y \r\n\r\n#Prediction function for Poisson regression\r\ndef prediction_Poisson(a):\r\n y = [math.exp(ai) for ai in a]\r\n #Use floor function to predict \r\n t = [math.floor(yi) for yi in y]\r\n return t \r\n\r\n#Prediction function for Ordinal regression\r\ndef prediction_Ordinal(a):\r\n s = 1\r\n phiJ = [-math.inf,-2,-1,0,1,math.inf]\r\n t = []\r\n #Compute values for all ordinals J = 1,2,3,4,5 and choose max\r\n for ai in a:\r\n pj = []\r\n for j in range(1,6):\r\n yj = yij(ai,phiJ[j],s)\r\n yj_1 = yij(ai,phiJ[j-1],s)\r\n pj.append(yj - yj_1)\r\n t.append(pj.index(max(pj))+1)\r\n return t \r\n\r\n#Function to plot the error rate as a function of training set sizes\r\ndef plot_summary(data,sizes,model,dataset_name,alpha):\r\n errors = [d.get(\"Mean\") for d in data]\r\n font = {'family' : 'normal',\r\n 'weight' : 'bold',\r\n 'size' : 22}\r\n\r\n plt.rc('font', **font)\r\n std = [d.get(\"STD\") for d in data]\r\n plt.gcf().clear()\r\n plt.figure(figsize=(25,25),dpi=90)\r\n plt.errorbar(sizes,errors,yerr=std,ecolor='r', color = 'b', capsize=25, label = \"GLM Model : \"+model)\r\n plt.xlabel(\"Training Sizes\")\r\n plt.ylabel(\"Error Rate\")\r\n plt.grid(\"on\")\r\n plt.title(\"Dataset: \" +dataset_name+\" | Alpha: \"+str(alpha))\r\n plt.legend(loc=\"best\")\r\n plt.savefig(dataset_name + \"_\"+ model + '.png')\r\n plt.show()\r\n\r\n#Function implement the common GLM function\r\ndef GLM_variant(model, dataset_name):\r\n #Read dataset and split to Train and Test sets\r\n train, trainL, test, testL = read_csv(dataset_name)\r\n #Set training set sizes as 0.1, 0.2, 0.3... 1 \r\n training_set_sizes = [1] if dataset_name == \"irlstest\" else [int(i/10*len(train)) for i in range(1, 11, 1)]\r\n summary = []\r\n for size in training_set_sizes:\r\n trials = 30 if dataset_name != \"irlstest\" else 1\r\n #trials =1\r\n error_predictions = []\r\n iterations = []\r\n time = []\r\n #Repeat for 30 trials\r\n for trial in range(0,trials):\r\n if dataset_name == \"irlstest\":\r\n train_sub, trainL_sub = train, trainL\r\n else: \r\n #Shuffle training data\r\n #train_sub, trainL_sub = zip(*random.sample(list(zip(train, trainL)),size))\r\n train_sub, trainL_sub = train[:size], train[:size]\r\n t = trainL_sub\r\n N = len(train_sub)\r\n w0 = np.array([[1]] * N)\r\n #Append data matrix with ones\r\n phi = np.concatenate((w0, train_sub), axis=1)\r\n\r\n M = len(phi[0])\r\n \r\n #Set parameter value\r\n alpha = 10\r\n\r\n I = np.eye(M)\r\n #Newton Raphson starts with w0 = vector of zeroes\r\n w = np.array([[0]] * M)\r\n convergence_test = 1\r\n itr = 1\r\n start = timeit.default_timer()\r\n #Repeat Newton Raphson update formula until convergence or 100 iterations\r\n while itr < 100 and convergence_test > 10 ** -3:\r\n w_old = w\r\n a = np.matmul(phi,w_old)\r\n #Compute first and second Derivatives based on Model\r\n if model == \"logistic\": \r\n R, d = compute_R_d_Logistic(a, t)\r\n elif model == \"poisson\":\r\n R, d = compute_R_d_Poisson(a, t)\r\n elif model == \"ordinal\":\r\n R, d = compute_R_d_Ordinal(a, t)\r\n\r\n #First derivative\r\n g = np.matmul(np.transpose(phi),d) - (alpha * w)\r\n #Hessian matrix of second derivatives\r\n H = -(alpha * I) - np.matmul(np.transpose(phi),np.matmul(R,phi))\r\n #Newton Raphson update formula for GLM \r\n #W_old = W_new - inverse(H)*g\r\n if np.linalg.det(H) != 0:\r\n w_new = w_old - np.matmul(np.linalg.inv(H),g)\r\n #Test convergence\r\n if np.linalg.norm(w_old) != 0:\r\n convergence_test = np.linalg.norm(w_new - w_old) / np.linalg.norm(w_old)\r\n \r\n w = w_new\r\n itr += 1\r\n #print(w) \r\n stop = timeit.default_timer() \r\n iterations.append(itr)\r\n time.append(stop-start)\r\n #prediction\r\n Ntest = len(test)\r\n w0 = np.array([[1]] * Ntest)\r\n #Use test set for prediction\r\n phi = np.concatenate((w0, test), axis=1)\r\n #We predict using WMap calculated earlier using Newton Raphson\r\n a = np.matmul(phi,w)\r\n if model == \"logistic\": \r\n y = prediction_Logistic(a)\r\n error_predictions.append(((y-testL.flatten()) != 0).sum())\r\n if model == \"poisson\":\r\n y = prediction_Poisson(a)\r\n error_predictions.append((abs(y-testL.flatten()) != 0).sum())\r\n if model == \"ordinal\":\r\n y = prediction_Ordinal(a)\r\n error_predictions.append((abs(y-testL.flatten()) != 0).sum())\r\n \r\n print(size,\"Done\")\r\n summary_data = {}\r\n summary_data['Model'] = model\r\n summary_data['Run Time'] = np.mean(time)\r\n summary_data['Dataset Size'] = size\r\n summary_data['Mean'] = np.mean(np.array(error_predictions)/Ntest)\r\n summary_data['STD'] = np.std(np.array(error_predictions)/Ntest)\r\n summary_data['Iterations'] = np.mean(iterations)\r\n summary.append(summary_data)\r\n pprint.pprint(summary)\r\n filename = 'Output Summary '+model+ ' ' + dataset_name + '.txt'\r\n #Write Summary to file\r\n with open(filename, 'wt') as out:\r\n pprint.pprint(summary, stream=out)\r\n #Plot graph\r\n plot_summary(summary,training_set_sizes,model, dataset_name, alpha)\r\n\r\n#Utility function to calculate Sigmoid\r\ndef sigmoid(x):\r\n return 1 / (1 + np.exp(x))\r\n\r\n\r\n#Utility function to calculate sigmoid based on S and Phi parameters for Ordinal\r\ndef yij(a,phij,s):\r\n x = np.array(s*(phij-a))\r\n if x >= 0:\r\n z = np.exp(-1*x)\r\n return 1 / (1 + z)\r\n else:\r\n z = np.exp(x)\r\n return z / (1 + z)\r\n\r\n#Code Execution starts here!\r\nif __name__ == \"__main__\":\r\n #Sample dataset names = [\"A\",\"usps\",\"AO\",\"AP\"]\r\n #Sample model names = [\"logistic\",\"poisson\",\"ordinal\"]\r\n if(len(sys.argv) != 3):\r\n raise Exception('Error: expected 2 command line arguments!')\r\n\r\n #Code expects dataset name and model name as command line argument \r\n dataset_name = sys.argv[1]\r\n model = sys.argv[2]\r\n #Common function to generate GLM model, predict and evaluate\r\n GLM_variant(model, dataset_name)\r\n\r\n print(\"\\n\\n..Done!\")\r\n\r\n\r\n" }, { "alpha_fraction": 0.5702906250953674, "alphanum_fraction": 0.5866523385047913, "avg_line_length": 36.67499923706055, "blob_id": "a0222657ea98346c07d4891646d2910f739533f9", "content_id": "8cf673cd6f6211492d0621dd6559bea7cf7af294", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4645, "license_type": "no_license", "max_line_length": 101, "num_lines": 120, "path": "/model_selection.py", "repo_name": "mafrasiabi/Bayesian-GLM-for-Classification", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python3\r\nimport sys\r\nimport numpy as np \r\nimport pandas as pd\r\nimport random\r\nimport math \r\nimport matplotlib.pyplot as plt \r\nimport pprint\r\nimport timeit\r\nfrom numpy import linalg as LA\r\nimport pp3\r\n\r\n#Function to perform cross validation for model selection. Based on my code in Assignment 2\r\ndef model_selection_using_cross_validation(train, trainR, test, testR, dataset_name, model):\r\n len_train = np.shape(train)[0]\r\n step = len_train//10 \r\n error_for_params = [] \r\n #Running cross validation with below values of parameters\r\n test_params = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9] + [i for i in range(1,101)] \r\n for l in test_params:\r\n error_predictions = []\r\n #Steps = 10 to perform 10 fold cross validation\r\n for i in range(0,len_train, step):\r\n #Training set will be all portions except i-th portion\r\n current_train = np.delete(train,slice(i,i+step),0)\r\n current_trainR = np.delete(trainR,slice(i,i+step),0)\r\n w = calculate_w(l,current_train,current_trainR, model)\r\n \r\n test = train[i:i+step]\r\n testL = trainR[i:i+step]\r\n Ntest = len(test)\r\n w0 = np.array([[1]] * Ntest)\r\n #Use remaining part of data set for prediction\r\n phi = np.concatenate((w0, test), axis=1)\r\n a = np.matmul(phi,w)\r\n #We predict using WMap calculated earlier using Newton Raphson\r\n if model == \"logistic\": \r\n y = pp3.prediction_Logistic(a)\r\n error_predictions.append(((y-testL.flatten()) != 0).sum())\r\n if model == \"poisson\":\r\n y = pp3.prediction_Poisson(a)\r\n error_predictions.append((abs(y-testL.flatten()) != 0).sum())\r\n if model == \"ordinal\":\r\n y = pp3.prediction_Ordinal(a)\r\n error_predictions.append((abs(y-testL.flatten()) != 0).sum())\r\n error_for_params.append(avg(error_predictions))\r\n \r\n print(\"Dataset: \", dataset_name)\r\n print(\"--MODEL SELECTION USING CROSS VALIDATION--\")\r\n print(\"Parameter: \", str(test_params[error_for_params.index(min(error_for_params))]))\r\n\r\n\r\n#Using Same function to calculate w\r\n#Didn't get enough time to generalize function wriiten in pp3 to return only w for cross validation. \r\n#But I am calling functions written in pp3 file\r\ndef calculate_w(l, train_sub, trainL_sub, model):\r\n t = trainL_sub\r\n N = len(train_sub)\r\n w0 = np.array([[1]] * N)\r\n #Append data matrix with ones\r\n phi = np.concatenate((w0, train_sub), axis=1)\r\n\r\n M = len(phi[0])\r\n \r\n #Set parameter value\r\n alpha = l\r\n\r\n I = np.eye(M)\r\n #Newton Raphson starts with w0 = vector of zeroes\r\n w = np.array([[0]] * M)\r\n convergence_test = 1\r\n itr = 1\r\n #Repeat Newton Raphson update formula until convergence or 100 iterations\r\n while itr < 100 and convergence_test > 10 ** -3:\r\n w_old = w\r\n a = np.matmul(phi,w_old)\r\n #Compute first and second Derivatives based on Model\r\n if model == \"logistic\": \r\n R, d = pp3.compute_R_d_Logistic(a, t)\r\n elif model == \"poisson\":\r\n R, d = pp3.compute_R_d_Poisson(a, t)\r\n elif model == \"ordinal\":\r\n R, d = pp3.compute_R_d_Ordinal(a, t)\r\n\r\n #First derivative\r\n g = np.matmul(np.transpose(phi),d) - (alpha * w)\r\n #Hessian matrix of second derivatives\r\n H = -(alpha * I) - np.matmul(np.transpose(phi),np.matmul(R,phi))\r\n #Newton Raphson update formula for GLM \r\n #W_old = W_new - inverse(H)*g\r\n if np.linalg.det(H) != 0:\r\n w_new = w_old - np.matmul(np.linalg.inv(H),g)\r\n #Test convergence\r\n if np.linalg.norm(w_old) != 0:\r\n convergence_test = np.linalg.norm(w_new - w_old) / np.linalg.norm(w_old)\r\n \r\n w = w_new\r\n itr += 1\r\n return w\r\n\r\n#Find average of list\r\ndef avg(lst):\r\n return sum(lst)/len(lst)\r\n\r\n\r\n#Code Execution starts here!\r\nif __name__ == \"__main__\":\r\n #Sample dataset names = [\"A\",\"usps\",\"AO\",\"AP\"]\r\n #Sample model names = [\"logistic\",\"poisson\",\"ordinal\"]\r\n if(len(sys.argv) != 3):\r\n raise Exception('Error: expected 2 command line arguments!')\r\n\r\n #Code expects dataset name and model name as command line argument \r\n dataset_name = sys.argv[1]\r\n model = sys.argv[2]\r\n #Common function to generate GLM model, predict and evaluate\r\n\r\n train, trainL, test, testL = pp3.read_csv(dataset_name)\r\n model_selection_using_cross_validation(train, trainL, test, testL, dataset_name, model)\r\n print(\"..Done!\")\r\n\r\n\r\n" }, { "alpha_fraction": 0.8674699068069458, "alphanum_fraction": 0.8674699068069458, "avg_line_length": 82, "blob_id": "017e69737c6c037b45728d1036d8e47ba8efce4e", "content_id": "2f6a943f88d2cbe2da9d1a8e446e1aec183d81e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 166, "license_type": "no_license", "max_line_length": 131, "num_lines": 2, "path": "/README.md", "repo_name": "mafrasiabi/Bayesian-GLM-for-Classification", "src_encoding": "UTF-8", "text": "# Bayesian-GLM-for-Classification\nGeneric implementation for Generalized Linear Models including Logistic, Poisson and Ordinal Regression for Classification purposes\n" } ]
3
SaeedTaghavi/ModelingNeuralDynamics
https://github.com/SaeedTaghavi/ModelingNeuralDynamics
4fc98bd949be1410045c4a6906b7a4e2ee1b7b90
49e9bb14636b1481b1b78cba304168ded94c8e64
47b8a193081b14f4acec1d3fdfef6642f0f08515
refs/heads/master
2020-12-06T03:19:54.280681
2020-01-09T18:41:15
2020-01-09T18:41:15
232,325,626
1
0
null
2020-01-07T13:01:49
2020-01-07T11:50:36
2020-01-07T10:02:56
null
[ { "alpha_fraction": 0.4081170856952667, "alphanum_fraction": 0.47420036792755127, "avg_line_length": 25.939023971557617, "blob_id": "33785c0373441076ccf0a2ac10e5848c6c350fe4", "content_id": "aee6e0831d7db615acf4d48aeeaba502c065ede4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6628, "license_type": "no_license", "max_line_length": 79, "num_lines": 246, "path": "/python/30_The_PING_Model_of_Gamma_Rhythms/2_CELL_PING_CONDITION_NUMBERS/main.py", "repo_name": "SaeedTaghavi/ModelingNeuralDynamics", "src_encoding": "UTF-8", "text": "from scipy.integrate import odeint\nfrom numpy import exp\nimport numpy as np\nimport pylab as pl\n\n\ndef h_e_inf(v):\n alpha_h = 0.128 * exp(-(v + 50) / 18)\n beta_h = 4.0 / (1.0 + exp(-(v + 27.0) / 5.0))\n return (alpha_h / (alpha_h + beta_h))\n\n\ndef h_i_inf(v):\n alpha_h = 0.07 * exp(-(v + 58.0) / 20.0)\n beta_h = 1.0 / (exp(-0.1 * (v + 28.0)) + 1.0)\n return (alpha_h / (alpha_h + beta_h))\n\n\ndef m_e_inf(v):\n alpha_m = 0.32 * (v + 54.0) / (1.0 - exp(-(v + 54.0) / 4.0))\n beta_m = 0.28 * (v + 27.0) / (exp((v + 27.0) / 5.0) - 1.0)\n return (alpha_m / (alpha_m + beta_m))\n\n\ndef m_i_inf(v):\n alpha_m = 0.1 * (v + 35.0) / (1.0 - exp(-(v + 35.0) / 10.0))\n beta_m = 4.0 * exp(-(v + 60.0) / 18.0)\n return (alpha_m / (alpha_m + beta_m))\n\n\ndef n_e_inf(v):\n alpha_n = 0.032 * (v + 52.0) / (1.0 - exp(-(v + 52.0) / 5.0))\n beta_n = 0.5 * exp(-(v + 57.0) / 40.0)\n return (alpha_n / (alpha_n + beta_n))\n\n\ndef n_i_inf(v):\n alpha_n = -0.01 * (v + 34.0) / (exp(-0.1 * (v + 34.0)) - 1.0)\n beta_n = 0.125 * exp(-(v + 44.0) / 80.0)\n return (alpha_n / (alpha_n + beta_n))\n\n\ndef tau_h_e(v):\n alpha_h = 0.128 * exp(-(v + 50.0) / 18.0)\n beta_h = 4.0 / (1.0 + exp(-(v + 27.0) / 5.0))\n return (1.0 / (alpha_h + beta_h))\n\n\ndef tau_h_i(v):\n alpha_h = 0.07 * exp(-(v + 58.0) / 20.0)\n beta_h = 1.0 / (exp(-0.1 * (v + 28.0)) + 1.0)\n tau_h = 1.0 / (alpha_h + beta_h)\n phi = 5.0\n return (tau_h / phi)\n\n\ndef tau_n_e(v):\n alpha_n = 0.032 * (v + 52.0) / (1.0 - exp(-(v + 52.0) / 5.0))\n beta_n = 0.5 * exp(-(v + 57.0) / 40.0)\n return (1.0 / (alpha_n + beta_n))\n\n\ndef tau_n_i(v):\n alpha_n = -0.01 * (v + 34.0) / (exp(-0.1 * (v + 34.0)) - 1.0)\n beta_n = 0.125 * exp(-(v + 44.0) / 80.0)\n tau_n = 1.0 / (alpha_n + beta_n)\n phi = 5.0\n return (tau_n / phi)\n\n\ndef tau_peak_function(tau_d, tau_r, tau_d_q):\n\n dt05 = 0.5 * dt\n\n s = 0\n t = 0\n s_inc = exp(-t / tau_d_q) * (1.0 - s) / tau_r - s * tau_d\n while s_inc > 0:\n t_old = t\n s_inc_old = s_inc\n s_tmp = s + dt05 * s_inc\n s_inc_tmp = exp(-(t + dt05) / tau_d_q) * \\\n (1.0 - s_tmp) / tau_r - s_tmp / tau_d\n s = s + dt * s_inc_tmp\n t = t + dt\n s_inc = exp(-t / tau_d_q) * (1.0 - s) / tau_r - s / tau_d\n\n return (t_old * (-s_inc) + t * s_inc_old) / (s_inc_old - s_inc)\n\n\ndef tau_d_q_function(tau_d, tau_r, tau_hat):\n\n # set an interval for tau_d_q\n tau_d_q_left = 1.0\n while tau_peak_function(tau_d, tau_r, tau_d_q_left) > tau_hat:\n tau_d_q_left *= 0.5\n\n tau_d_q_right = tau_r\n while tau_peak_function(tau_d, tau_r, tau_d_q_right) < tau_hat:\n tau_d_q_right *= 2.0\n\n # bisection method\n while tau_d_q_right - tau_d_q_left > 1e-12:\n tau_d_q_mid = 0.5 * (tau_d_q_left + tau_d_q_right)\n if (tau_peak_function(tau_d, tau_r, tau_d_q_mid) <= tau_hat):\n tau_d_q_left = tau_d_q_mid\n else:\n tau_d_q_right = tau_d_q_mid\n\n return 0.5 * (tau_d_q_left + tau_d_q_right)\n\n\ndef derivative(x0, t):\n\n v_e, h_e, n_e, q_e, s_e, v_i, h_i, n_i, q_i, s_i = x0\n\n I_L_e = 0.1 * (v_e + 67.0)\n I_K_e = 80 * n_e ** 4 * (v_e + 100.0)\n I_Na_e = 100 * h_e * m_e_inf(v_e) ** 3 * (v_e - 50.0)\n I_syn_e = g_ie * s_i * (v_rev_i - v_e)\n\n dv_e = i_ext_e - I_L_e - I_K_e - I_Na_e + I_syn_e\n dh_e = (h_e_inf(v_e) - h_e) / tau_h_e(v_e)\n dn_e = (n_e_inf(v_e) - n_e) / tau_n_e(v_e)\n dq_e = 0.5 * (1 + np.tanh(0.1 * v_e)) * (1.0 - q_e) * 10.0 - q_e / tau_dq_e\n ds_e = q_e * (1.0 - s_e) / tau_r_e - s_e / tau_d_e\n\n I_L_i = 0.1 * (v_i + 65.0)\n I_K_i = 9.0 * n_i ** 4 * (v_i + 90.0)\n I_Na_i = 35.0 * m_i_inf(v_i) ** 3 * h_i * (v_i - 55.0)\n I_syn_i = g_ei * s_e * (v_rev_e - v_i)\n\n dv_i = i_ext_i - I_Na_i - I_K_i - I_L_i + I_syn_i\n dh_i = (h_i_inf(v_i) - h_i) / tau_h_i(v_i)\n dn_i = (n_i_inf(v_i) - n_i) / tau_n_i(v_i)\n dq_i = 0.5 * (1.0 + np.tanh(0.1 * v_i)) * (1.0 - q_i) * 10 - q_i / tau_dq_i\n ds_i = q_i * (1.0 - s_i) / tau_r_i - s_i / tau_d_i\n\n return np.array([dv_e, dh_e, dn_e, dq_e, ds_e,\n dv_i, dh_i, dn_i, dq_i, ds_i])\n\n\ndef spikeDetection(t, V, spikeThreshold):\n tSpikes = []\n v = np.asarray(V)\n nSteps = len(V)\n\n for i in range(1, nSteps):\n if (V[i - 1] <= spikeThreshold) & (V[i] > spikeThreshold):\n\n ts = ((i - 1) * dt * (V[i - 1] - spikeThreshold) +\n i * dt * (spikeThreshold - V[i])) / (V[i - 1] - V[i])\n tSpikes.append(ts)\n return tSpikes\n\n\ni_ext_e = 1.4\ni_ext_i = 0.0\ng_ei = 0.25\ng_ie = 0.25\nv_rev_e = 0.0\nv_rev_i = -75.0\ntau_r_e = 0.5\ntau_peak_e = 0.5\ntau_d_e = 3.0\ntau_r_i = 0.5\ntau_peak_i = 0.5\ntau_d_i = 9.0\nt_final = 200.0\ndt = 0.001\ntau_dq_e = tau_d_q_function(tau_d_e, tau_r_e, tau_peak_e)\ntau_dq_i = tau_d_q_function(tau_d_i, tau_r_i, tau_peak_i)\n\n# initialize dynamic variables\nv_e = -75.0\nh_e = 0.1\nn_e = 0.1\nq_e = 0\ns_e = 0\nv_i = -75.0\nh_i = 0.1\nn_i = 0.1\nq_i = 0\ns_i = 0\n\ninitialConditions = [v_e, h_e, n_e, q_e, s_e,\n v_i, h_i, n_i, q_i, s_i]\n\n\nt = np.arange(0, t_final, dt)\nsol = odeint(derivative,\n initialConditions,\n t)\n\nv_e = sol[:, 0]\nv_i = sol[:, 5]\n\neSpikes = spikeDetection(t, v_e, -20.0)\nbase_period = eSpikes[-1] - eSpikes[-2]\nprint \"Period of E neuron %10.3f ms\" % base_period\n\n# ------------------------------------------------------------------#\n\ni_ext_e = i_ext_e * 0.99\nsol = odeint(derivative,\n initialConditions,\n t)\n\nv_e = sol[:, 0]\nv_i = sol[:, 5]\neSpikes = spikeDetection(t, v_e, -20.0)\nperiod = eSpikes[-1] - eSpikes[-2]\npercentage_change = (base_period-period)/base_period*100\nprint \"Percentage change of reduce in I_E %10.3f\" % percentage_change\n\n# ------------------------------------------------------------------#\n\ni_ext_e = 1.4\ng_ie = g_ie * 1.01\nsol = odeint(derivative,\n initialConditions,\n t)\n\nv_e = sol[:, 0]\nv_i = sol[:, 5]\neSpikes = spikeDetection(t, v_e, -20.0)\nperiod = eSpikes[-1] - eSpikes[-2]\npercentage_change = (base_period-period)/base_period*100\nprint \"Percentage change of increse in g_IE %10.3f\" % percentage_change\n\n# ------------------------------------------------------------------#\n\ng_ie = 0.25\ni_ext_e = 1.4\ntau_d_i = tau_d_i * 1.01\ntau_dq_i = tau_d_q_function(tau_d_i, tau_r_i, tau_peak_i)\nsol = odeint(derivative,\n initialConditions,\n t)\n\nv_e = sol[:, 0]\nv_i = sol[:, 5]\neSpikes = spikeDetection(t, v_e, -20.0)\nperiod = eSpikes[-1] - eSpikes[-2]\npercentage_change = (base_period-period)/base_period*100\nprint \"Percentage change of increse in tau_I %10.3f\" % percentage_change\n\n" }, { "alpha_fraction": 0.5869837403297424, "alphanum_fraction": 0.6201502084732056, "avg_line_length": 22.5, "blob_id": "ec69f710db943ab8934e1bfe19674ca7f2e3e095", "content_id": "9b27bfd706f9af5efc460faa40740ca39c1133ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1598, "license_type": "no_license", "max_line_length": 69, "num_lines": 68, "path": "/python/17_Frequency_Current_Curves/RTM_F_I_CURVE_AT_ONSET/fff.py", "repo_name": "SaeedTaghavi/ModelingNeuralDynamics", "src_encoding": "UTF-8", "text": "from scipy.integrate import odeint\nimport numpy as np\nfrom numpy import exp\nimport pylab as pl\nfrom copy import copy\nfrom time import time\n\n\ni_ext_high = 0.1194\ni_ext_low = 0.1193\ni_ext_vec = np.linspace(i_ext_low, i_ext_high, 11)\n\n\nf_forward = np.loadtxt(\"forward.txt\")\nI = f_forward[:, 0]\nf = f_forward[:, 1]\n\npl.plot(I, f, \"ko\", label=\"forward\")\n\n\n# plot the solid red line\nind = np.where(f > 0)[0]\nI0 = I[ind]\nf0 = f[ind]\nalpha_vec = np.linspace(0, 1, 101)\n\nI_c_low = i_ext_vec[min(ind)-1]\nI_c_high = i_ext_vec[min(ind)]\n\nC_vec = np.zeros(len(alpha_vec))\nerr_vec = np.zeros(len(alpha_vec))\n\nfor ijk in range(len(alpha_vec)):\n\n alpha = alpha_vec[ijk]\n I_c = I_c_low * alpha + I_c_high * (1 - alpha)\n y = f0 / np.sqrt(I0 - I_c)\n print y\n exit(0)\n # measure how constant f/sqrt(I-I_c) is, with\n # the I_c defined above.\n err_vec[ijk] = (max(y) - min(y)) / np.mean(y)\n C_vec[ijk] = np.mean(y)\n\n# pick the I_c that makes f/sqrt(I-I_c) as constant\nind = np.argmin(err_vec)\nalpha = alpha_vec[ind]\n\nI_c = I_c_low * alpha + I_c_high * (1 - alpha)\nC = C_vec[ind]\nI = I_c + np.linspace(0, 1.0, 1001) * (i_ext_high - I_c)\nprint C * np.sqrt(I - I_c)\npl.plot(I, C * np.sqrt(I - I_c), 'r', lw=2)\n\n\nf_backward = np.loadtxt(\"backward.txt\")\nI = f_backward[:, 0][::-1]\nf = f_backward[:, 1][::-1]\n\npl.plot(I, f, \"ro\", fillstyle=\"none\", markersize=8, label=\"backward\")\n\n# pl.xlim(min(i_ext_vec), max(i_ext_vec))\npl.xlabel(\"I\", fontsize=16)\npl.ylabel(\"frequency\", fontsize=16)\npl.legend(fontsize=14, frameon=False)\npl.tight_layout()\npl.tick_params(labelsize=14)\npl.savefig(\"fig_17_5.png\")\n" }, { "alpha_fraction": 0.429299533367157, "alphanum_fraction": 0.46027183532714844, "avg_line_length": 26.525178909301758, "blob_id": "b7357ed5499eec106e5b5a52f20950f708ab84e5", "content_id": "b52e03799b173b74739fba38c2a2b9a1f1fa3422", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7652, "license_type": "no_license", "max_line_length": 75, "num_lines": 278, "path": "/python/31_ING_Rhythms/ING_1/lib.py", "repo_name": "SaeedTaghavi/ModelingNeuralDynamics", "src_encoding": "UTF-8", "text": "from numpy import exp, matmul\nfrom copy import copy\nimport numpy as np\nfrom main import *\n\n\ndef tau_n_i(v):\n alpha_n = -0.01 * (v + 34) / (exp(-0.1 * (v + 34)) - 1)\n beta_n = 0.125 * exp(-(v + 44) / 80)\n tau_n = 1. / (alpha_n + beta_n)\n phi = 5.0\n tau_n /= phi\n return tau_n\n\n\ndef tau_h_i(v):\n alpha_h = 0.07 * exp(-(v + 58) / 20)\n beta_h = 1. / (exp(-0.1 * (v + 28)) + 1)\n tau_h = 1. / (alpha_h + beta_h)\n phi = 5.0\n tau_h = tau_h / phi\n return tau_h\n\n\ndef n_i_inf(v):\n alpha_n = -0.01 * (v + 34) / (exp(-0.1 * (v + 34)) - 1)\n beta_n = 0.125 * exp(-(v + 44) / 80)\n return alpha_n / (alpha_n + beta_n)\n\n\ndef m_i_inf(v):\n alpha_m = 0.1 * (v + 35) / (1 - exp(-(v + 35) / 10))\n beta_m = 4 * exp(-(v + 60) / 18)\n return alpha_m / (alpha_m + beta_m)\n\n\ndef h_i_inf(v):\n alpha_h = 0.07 * exp(-(v + 58) / 20)\n beta_h = 1 / (exp(-0.1 * (v + 28)) + 1)\n return alpha_h / (alpha_h + beta_h)\n\n\ndef derivative(x0, t):\n\n v = x0[:num_i]\n h = x0[num_i: 2 * num_i]\n n = x0[2 * num_i: 3 * num_i]\n q = x0[3 * num_i: 4 * num_i]\n s = x0[4 * num_i: 5 * num_i]\n\n I_Na = g_Na * m_i_inf(v) ** 3 * h * (v - v_na)\n I_L = g_l * (v - v_l)\n I_K = g_k * n ** 4 * (v - v_k)\n I_syn = matmul(g_ii, s) * (v_rev_i - v) # + G_gap * v - c * v\n\n dv = -I_Na - I_K - I_L + i_ext + I_syn\n dh = (h_i_inf(v) - h) / tau_h_i(v)\n dn = (n_i_inf(v) - n) / tau_n_i(v)\n dq = 0.5 * (1.0 + np.tanh(0.1 * v)) * 10.0 * (1 - q) - q / tau_dq_i\n ds = q * (1.0 - s) / tau_r_i - s / tau_d_i\n\n return np.hstack((dv, dh, dn, dq, ds))\n\n\ndef derivativeSingle(x0, t=0):\n\n n0 = len(x0) / 3\n v, h, n = x0[:n0], x0[n0: (2 * n0)], x0[(2 * n0): (3 * n0)]\n\n I_Na = g_Na * m_i_inf(v) ** 3 * h * (v - v_na)\n I_L = g_l * (v - v_l)\n I_K = g_k * n ** 4 * (v - v_k)\n\n dv = -I_Na - I_K - I_L + i_ext\n dh = (h_i_inf(v) - h) / tau_h_i(v)\n dn = (n_i_inf(v) - n) / tau_n_i(v)\n\n return np.hstack((dv, dh, dn))\n\n# -------------------------------------------------------------------#\n\n\ndef eulerIntegrator(x, dt, f): \n\n x += f(x) * dt\n return x\n# -------------------------------------------------------------------#\n\n\ndef splayState(i_ext, phiVec, f):\n \"\"\"\n input: i_ext=column vector of external drives \n phi_vec = column vector of phases at which \n neurons are to be initialized\n The length, num, of i_ext is the total number \n of neurons.\n output: a num-by-3 array called rtm_init. The columns\n contain values of v, h, and n. If i_ext(i) is below\n the firing threshold, then the i-th row of the\n matrix rtm_init contains the stable equilibrium point.\n If i_ext(i) is above the firing threshold, then the\n i-th row of rtm_init is a point (v,h,n) on the limit\n cycle, at phase phi_vec(i).\n \"\"\"\n\n t = 0.0\n dt = 0.01\n t_final = 2000.0 # if fewer than max_spikes spikes occur\n # by this time, the program gives\n # up and sets (v,h,n) equal\n # to the values at time t_final.\n maxNumSpikes = 3\n N = len(i_ext)\n numSpikes = np.zeros(N, dtype=int)\n done = np.zeros(N) # done[i]=1 indicates that we are\n # done with neuron i.\n iteration = 0\n numSteps = int(t_final / dt)\n\n v = -70.0 * np.ones(N)\n # m = m_i_inf(v)\n n = n_i_inf(v)\n h = h_i_inf(v)\n x0 = np.hstack((v, h, n))\n\n tSpikes = np.zeros((N, maxNumSpikes))\n initialConition = np.zeros((N, 3))\n\n # ofile = open(\"v.txt\", \"w\")\n i = 1\n while (np.sum(done) < N) and (t < t_final):\n\n v_old = v\n h_old = h\n n_old = n\n t_old = t\n\n x = eulerIntegrator(x0, dt, f)\n i += 1\n\n v = x[:N]\n h = x[N: (2 * N)]\n n = x[(2 * N):]\n t = i * dt\n\n x0 = copy(x)\n\n # ofile.write(\"%18.4f %18.4f \\n\" % (i*dt, v))\n indices = np.where((v_old >= spikeThreshold) &\n (v < spikeThreshold))[0]\n\n numInstantSpikes = len(indices)\n for k in indices:\n numSpikes[k] += 1\n ts = (t_old * (v_old[k] - spikeThreshold) +\n t * (spikeThreshold - v[k])) / (v_old[k] - v[k])\n\n if numSpikes[k] < 4:\n tSpikes[k, numSpikes[k] - 1] = ts\n\n thr = tSpikes[:, -1] + phiVec * (tSpikes[:, -1] - tSpikes[:, -2])\n indices = np.where((numSpikes == maxNumSpikes) &\n (t > thr) &\n (t_old <= thr))\n\n for i0 in range(len(indices)):\n k = indices[i0]\n initialConition[k, 0] = (\n v_old[k] * (t - thr[k]) + v[k] * (thr[k] - t_old)) / dt\n initialConition[k, 1] = (\n h_old[k] * (t - thr[k]) + h[k] * (thr[k] - t_old)) / dt\n initialConition[k, 2] = (\n n_old[k] * (t - thr[k]) + n[k] * (thr[k] - t_old)) / dt\n done[indices] = 1\n\n indices = np.where(done == 0)[0]\n initialConition[indices, 0] = v[indices]\n initialConition[indices, 1] = h[indices]\n initialConition[indices, 2] = n[indices]\n\n # print (\"Period is %10.3f [ms]\" % T)\n\n return initialConition\n# -------------------------------------------------------------------#\n\n\ndef tau_peak_function(tau_d, tau_r, tau_d_q):\n\n dt = 0.01\n dt05 = 0.5 * dt\n\n s = 0\n t = 0\n s_inc = exp(-t / tau_d_q) * (1.0 - s) / tau_r - s * tau_d\n while s_inc > 0:\n t_old = t\n s_inc_old = s_inc\n s_tmp = s + dt05 * s_inc\n s_inc_tmp = exp(-(t + dt05) / tau_d_q) * \\\n (1.0 - s_tmp) / tau_r - s_tmp / tau_d\n s = s + dt * s_inc_tmp\n t = t + dt\n s_inc = exp(-t / tau_d_q) * (1.0 - s) / tau_r - s / tau_d\n\n return (t_old * (-s_inc) + t * s_inc_old) / (s_inc_old - s_inc)\n\n\ndef tau_d_q_function(tau_d, tau_r, tau_hat):\n\n # set an interval for tau_d_q\n tau_d_q_left = 1.0\n while tau_peak_function(tau_d, tau_r, tau_d_q_left) > tau_hat:\n tau_d_q_left *= 0.5\n\n tau_d_q_right = tau_r\n while tau_peak_function(tau_d, tau_r, tau_d_q_right) < tau_hat:\n tau_d_q_right *= 2.0\n\n # bisection method\n while tau_d_q_right - tau_d_q_left > 1e-12:\n tau_d_q_mid = 0.5 * (tau_d_q_left + tau_d_q_right)\n if (tau_peak_function(tau_d, tau_r, tau_d_q_mid) <= tau_hat):\n tau_d_q_left = tau_d_q_mid\n else:\n tau_d_q_right = tau_d_q_mid\n\n return 0.5 * (tau_d_q_left + tau_d_q_right)\n\n\ndef spikeDetection(t, V, spikeThreshold):\n tSpikes = []\n v = np.asarray(V)\n nSteps = len(V)\n\n for i in range(1, nSteps):\n if (V[i - 1] <= spikeThreshold) & (V[i] > spikeThreshold):\n\n ts = ((i - 1) * dt * (V[i - 1] - spikeThreshold) +\n i * dt * (spikeThreshold - V[i])) / (V[i - 1] - V[i])\n tSpikes.append(ts)\n return tSpikes\n\n\ndef display_time(time):\n ''' print wall time '''\n\n hour = int(time/3600)\n minute = (int(time % 3600))/60\n second = time-(3600.*hour+60.*minute)\n print \"Done in %d hours %d minutes %.6f seconds\" \\\n % (hour, minute, second)\n\n\ndef spikeToFile(t_spikes, fileName):\n\n f = open(fileName, \"w\")\n n = len(t_spikes)\n for i in range(n):\n for j in range(len(t_spikes[i])):\n f.write(\"%18.4f\" % t_spikes[i][j])\n f.write(\"\\n\")\n\n f.close()\n\n\ndef read_from_file(fileName):\n\n with open(fileName, \"r\") as text:\n data = []\n for line in text:\n line = line.split()\n line = [float(i) for i in line]\n data.append(line)\n\n return data\n\n\ntau_dq_i = tau_d_q_function(tau_d_i, tau_r_i, tau_peak_i)\n" }, { "alpha_fraction": 0.3852140009403229, "alphanum_fraction": 0.4326477646827698, "avg_line_length": 25.85572052001953, "blob_id": "8972b4363a5f60e7a1e077df1f60ba9cf47613a6", "content_id": "4fd4c0ae91d73b0c9c73dc77083c4438ba0601e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5397, "license_type": "no_license", "max_line_length": 91, "num_lines": 201, "path": "/python/17_Frequency_Current_Curves/HH_F_I_CURVE/HH_F_I_CURVE.py", "repo_name": "SaeedTaghavi/ModelingNeuralDynamics", "src_encoding": "UTF-8", "text": "from scipy.integrate import odeint\nimport numpy as np\nfrom numpy import exp\nimport pylab as pl\nfrom copy import copy\nfrom time import time\n\n\ndef alpha_h(v):\n return 0.07 * exp(-(v + 70.0) / 20.0)\n\n\ndef alpha_m(v):\n return (v + 45.0) / 10.0 / (1 - exp(-(v + 45.0) / 10.0))\n\n\ndef alpha_n(v):\n return 0.01 * (-60.0 - v) / (exp((-60.0 - v) / 10.0) - 1.0)\n\n\ndef beta_h(v):\n return 1.0 / (exp(-(v + 40.0) / 10.0) + 1.0)\n\n\ndef beta_m(v):\n return 4.0 * exp(-(v + 70.0) / 18.0)\n\n\ndef beta_n(v):\n return 0.125 * exp(-(v + 70.0) / 80.0)\n\n\ndef h_inf(v):\n return alpha_h(v) / (alpha_h(v) + beta_h(v))\n\n\ndef m_inf(v):\n return alpha_m(v) / (alpha_m(v) + beta_m(v))\n\n\ndef n_inf(v):\n return alpha_n(v) / (alpha_n(v) + beta_n(v))\n\n\ndef derivative(x0, i_ext):\n\n v, m, n, h, = x0\n I_na = -g_na * h * m ** 3 * (v - v_na)\n I_k = -g_k * n ** 4 * (v - v_k)\n I_l = -g_l * (v - v_l)\n\n dv = (i_ext + I_na + I_k + I_l) / c\n dm = alpha_m(v) * (1.0 - m) - beta_m(v) * m\n dn = alpha_n(v) * (1.0 - n) - beta_n(v) * n\n dh = alpha_h(v) * (1.0 - h) - beta_h(v) * h\n\n return np.array([dv, dm, dn, dh])\n\n\ndef rungeKuttaIntegrator(x, h, f, i_ext):\n\n k1 = h * f(x, i_ext)\n k2 = h * f(x + 0.5 * k1, i_ext)\n k3 = h * f(x + 0.5 * k2, i_ext)\n k4 = h * f(x + k3, i_ext)\n\n x = x + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0\n\n return x\n\n\nc = 1.0\ng_k = 36.0\ng_na = 120.0\ng_l = 0.3\nv_k = -82.0\nv_na = 45.0\nv_l = -59.0\n\ni_ext_vec = np.linspace(3, 13, 23)\nt_final = 3000.0\ndt = 0.05\n\n\nv = -70.0\nm = m_inf(v)\nh = 0.7 # h_inf(v)\nn = 0.6 # n_inf(v)\ninitialConditions = [v, m, n, h]\nvThreshold = -20.0\n\n\nif __name__ == \"__main__\":\n\n pl.figure(figsize=(7, 3))\n\n start = time()\n\n N = int(600 / dt)\n num_steps = int(t_final/dt)\n frequencies = np.zeros(len(i_ext_vec))\n\n for direction in [\"forward\", \"backward\"]:\n \n if direction == \"backward\":\n i_ext_vec = i_ext_vec[::-1]\n\n for ii in range(len(i_ext_vec)):\n\n\n num_spikes = 0\n t_spikes = []\n i_ext = i_ext_vec[ii]\n v = np.zeros(num_steps)\n m = np.zeros_like(v)\n n = np.zeros_like(v)\n h = np.zeros_like(v)\n\n for i in range(num_steps):\n v[i], m[i], n[i], h[i] = rungeKuttaIntegrator(initialConditions,\n dt,\n derivative,\n i_ext)\n\n initialConditions = copy([v[i], m[i], n[i], h[i]])\n # condition to find steady state\n if ((i % N) == 0) and (i > 0):\n maxv = max(v[i - N:i])\n minv = min(v[i - N:i])\n maxm = max(m[i - N:i])\n minm = min(m[i - N:i])\n maxn = max(n[i - N:i])\n minn = min(n[i - N:i])\n maxh = max(h[i - N:i])\n minh = min(h[i - N:i])\n if (((maxv - minv) < 0.0001 * abs(maxv + minv)) &\n ((maxm - minm) < 0.0001 * abs(maxm + minm)) &\n ((maxh - minh) < 0.0001 * abs(maxh + minh)) &\n ((maxn - minn) < 0.0001 * abs(maxn + minn))):\n frequencies[ii] = 0.0\n print \"I =%10.3f, f =%10.2f\" % (i_ext, frequencies[ii])\n break\n\n # spike detection\n if (v[i-1] < vThreshold) & (v[i] >= vThreshold):\n num_spikes += 1\n tmp = ((i - 1) * dt * (v[i - 1] - vThreshold) +\n i * dt * (vThreshold - v[i])) / (v[i - 1] - v[i])\n t_spikes.append(tmp)\n # print num_spikes\n\n if num_spikes == 4:\n frequencies[ii] = 1000.0 / (t_spikes[-1] - t_spikes[-2])\n print \"I =%10.3f, f =%10.2f, t =%18.6f\" % (i_ext, frequencies[ii], tmp)\n break\n \n # save to file\n if direction == \"backward\":\n np.savetxt(\"backward.txt\", zip(i_ext_vec, frequencies), fmt=\"%20.9f\")\n else:\n np.savetxt(\"forward.txt\", zip(i_ext_vec, frequencies), fmt=\"%20.9f\")\n\n print \"Done in %10.3f\" % (time() - start)\n\n \n f_forward = np.loadtxt(\"forward.txt\")\n\n I = f_forward[:, 0]\n f = f_forward[:, 1]\n\n pl.plot(I, f, \"ko\", label=\"forward\")\n\n index = np.where(f == 0)[0]\n index = max(index)\n I_c = (I[index] + I[index + 1]) / 2.0;\n pl.plot([I[index + 1], I[index + 1]], [0, f[index + 1]], '--b', lw=1)\n\n\n\n f_backward = np.loadtxt(\"backward.txt\")\n\n I = f_backward[:, 0][::-1]\n f = f_backward[:, 1][::-1]\n\n pl.plot(I, f, \"ro\", fillstyle=\"none\", markersize=8, label=\"backward\")\n\n index = np.where(f == 0)[0]\n index = max(index)\n I_star = (I[index] + I[index + 1]) / 2.0;\n\n pl.plot([I[index + 1], I[index + 1]], [0, f[index + 1]], '--b', lw=1)\n pl.text(I_star - 0.1, -20, r\"$I_{\\ast}$\", fontsize=20, color=\"b\")\n pl.text(I_c - 0.1, -20, r\"$I_c$\", fontsize=20, color=\"b\")\n\n pl.xlim(min(i_ext_vec), max(i_ext_vec))\n pl.xlabel(\"I\", fontsize=16)\n pl.ylabel(\"frequency\", fontsize=16)\n pl.legend(fontsize=14, frameon=False)\n pl.tight_layout()\n pl.tick_params(labelsize=14)\n pl.savefig(\"fig_17_1.png\")" }, { "alpha_fraction": 0.39419087767601013, "alphanum_fraction": 0.47362181544303894, "avg_line_length": 16.946807861328125, "blob_id": "0e02d148207c2fcc8af65de6509138adca42d53b", "content_id": "2e4d9a6596413221e05cc6debb3a5fd95a981916", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1687, "license_type": "no_license", "max_line_length": 68, "num_lines": 94, "path": "/python/01_Modeling_a_Single_Neuron/HH_VOLTAGE_TRACE/main.py", "repo_name": "SaeedTaghavi/ModelingNeuralDynamics", "src_encoding": "UTF-8", "text": "from scipy.integrate import odeint\nimport numpy as np\nfrom numpy import exp\nimport pylab as pl\n\n\nc = 1.0\ng_k = 36.0\ng_na = 120.0\ng_l = 0.3\nv_k = -82.0\nv_na = 45.0\nv_l = -59.0\ni_ext = 7.0\nt_final = 200.0\ndt = 0.01\n\n\ndef beta_n(v):\n return 0.125 * exp(-(v + 70.0) / 80.0)\n\n\ndef beta_m(v):\n return 4.0 * exp(-(v + 70.0) / 18.0)\n\n\ndef beta_h(v):\n return 1. / (exp(-(v + 40.0) / 10.0) + 1.0)\n\n\ndef alpha_n(v):\n return 0.01 * (-60.0 - v) / (exp((-60.0 - v) / 10.0) - 1.0)\n\n\ndef alpha_m(v):\n if np.abs(v+45.0) > 1.0e-8:\n return (v + 45.0) / 10.0 / (1.0 - exp(-(v + 45.0) / 10.0))\n else:\n return 1.0\n\n\ndef alpha_h(v):\n return 0.07*exp(-(v+70)/20)\n\n\ndef h_inf(v):\n return alpha_h(v) / (alpha_h(v) + beta_h(v))\n\n\ndef m_inf(v):\n return alpha_m(v) / (alpha_m(v) + beta_m(v))\n\n\ndef n_inf(v):\n return alpha_n(v) / (alpha_n(v) + beta_n(v))\n\n\ndef derivative(x0, t):\n '''\n define HH Model\n '''\n v, m, n, h, = x0\n dv = (i_ext - g_na * h * m ** 3 * \\\n (v - v_na) - g_k * n ** 4 * (v - v_k) - g_l * (v - v_l)) / c\n dm = alpha_m(v) * (1.0 - m) - beta_m(v) * m\n dn = alpha_n(v) * (1.0 - n) - beta_n(v) * n\n dh = alpha_h(v) * (1.0 - h) - beta_h(v) * h\n\n return [dv, dm, dn, dh]\n\n\n\nv = -70.0\nm = m_inf(v)\nh = h_inf(v)\nn = n_inf(v)\nx0 = [v, m, n, h]\n\nif __name__ == \"__main__\":\n\n t = np.arange(0, t_final, dt)\n sol = odeint(derivative, x0, t)\n v = sol[:, 0]\n\n pl.figure(figsize=(7, 3))\n pl.plot(t, v, lw=2, c=\"k\")\n pl.xlim(min(t), max(t))\n pl.ylim(-100, 50)\n pl.xlabel(\"time [ms]\")\n pl.ylabel(\"v [mV]\")\n pl.yticks(range(-100, 100, 50))\n pl.tight_layout()\n pl.savefig(\"fig_1_3.png\")\n # pl.show()\n" }, { "alpha_fraction": 0.41124477982521057, "alphanum_fraction": 0.4689418077468872, "avg_line_length": 22.818714141845703, "blob_id": "a32ada1d3bc5055668f1f889252fd28aad0c3c82", "content_id": "50b0c48caae9b2ac7ceeed85e75b6d24dcfdbc72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4073, "license_type": "no_license", "max_line_length": 77, "num_lines": 171, "path": "/python/20_Chemical_Synapses/S_SLOW_BUILDUP/main.py", "repo_name": "SaeedTaghavi/ModelingNeuralDynamics", "src_encoding": "UTF-8", "text": "from scipy.integrate import odeint\nimport numpy as np\nfrom numpy import exp\nimport pylab as pl\n\n\ndef alpha_h(v):\n return 0.128 * exp(-(v + 50.0) / 18.0)\n\n\ndef alpha_m(v):\n return 0.32 * (v + 54) / (1.0 - exp(-(v + 54.0) / 4.0))\n\n\ndef alpha_n(v):\n return 0.032 * (v + 52) / (1.0 - exp(-(v + 52.0) / 5.0))\n\n\ndef beta_h(v):\n return 4.0 / (1.0 + exp(-(v + 27.0) / 5.0))\n\n\ndef beta_m(v):\n return 0.28 * (v + 27.0) / (exp((v + 27.0) / 5.0) - 1.0)\n\n\ndef beta_n(v):\n return 0.5 * exp(-(v + 57.0) / 40.0)\n\n\ndef h_inf(v):\n return alpha_h(v) / (alpha_h(v) + beta_h(v))\n\n\ndef m_inf(v):\n return alpha_m(v) / (alpha_m(v) + beta_m(v))\n\n\ndef n_inf(v):\n return alpha_n(v) / (alpha_n(v) + beta_n(v))\n\n\ndef derivative(x0, t):\n '''\n define Traub Model\n '''\n v, m, n, h, q, s = x0\n dv = i_ext - g_na * h * m ** 3 * \\\n (v - v_na) - g_k * n ** 4 * (v - v_k) - g_l * (v - v_l)\n dm = alpha_m(v) * (1.0 - m) - beta_m(v) * m\n dn = alpha_n(v) * (1.0 - n) - beta_n(v) * n\n dh = alpha_h(v) * (1.0 - h) - beta_h(v) * h\n dq = 0.5 * (1.0 + np.tanh(0.1 * v)) * (1 - q) * 10.0 - q / tau_d_q\n ds = q * (1 - s)/tau_r - s/tau_d\n\n return [dv, dm, dn, dh, dq, ds]\n\n\ndef initial_condition(v):\n m = m_inf(v)\n h = h_inf(v)\n n = n_inf(v)\n q = 0.0\n s = 0.0\n return [v, m, n, h, q, s]\n\n\ndef tau_peak_function(tau_d, tau_r, tau_d_q):\n\n # dt = 0.01\n dt05 = 0.5 * dt\n\n s = 0\n t = 0\n s_inc = exp(-t / tau_d_q) * (1.0 - s) / tau_r - s * tau_d\n while s_inc > 0:\n t_old = t\n s_inc_old = s_inc\n s_tmp = s + dt05 * s_inc\n s_inc_tmp = exp(-(t + dt05) / tau_d_q) * \\\n (1.0 - s_tmp) / tau_r - s_tmp / tau_d\n s = s + dt * s_inc_tmp\n t = t + dt\n s_inc = exp(-t / tau_d_q) * (1.0 - s) / tau_r - s / tau_d\n\n return (t_old * (-s_inc) + t * s_inc_old) / (s_inc_old - s_inc)\n\n\ndef tau_d_q_function(tau_d, tau_r, tau_hat):\n\n # set an interval for tau_d_q\n tau_d_q_left = 1.0\n while tau_peak_function(tau_d, tau_r, tau_d_q_left) > tau_hat:\n tau_d_q_left *= 0.5\n\n tau_d_q_right = tau_r\n while tau_peak_function(tau_d, tau_r, tau_d_q_right) < tau_hat:\n tau_d_q_right *= 2.0\n\n # bisection method\n while tau_d_q_right - tau_d_q_left > 1e-12:\n tau_d_q_mid = 0.5 * (tau_d_q_left + tau_d_q_right)\n if (tau_peak_function(tau_d, tau_r, tau_d_q_mid) <= tau_hat):\n tau_d_q_left = tau_d_q_mid\n else:\n tau_d_q_right = tau_d_q_mid\n\n return 0.5 * (tau_d_q_left + tau_d_q_right)\n\n\nc = 1\ng_k = 80.0\ng_na = 100.0\ng_l = 0.1\nv_k = -100.0\nv_na = 50.0\nv_l = -67.0\ni_ext = 0.2\nt_final = 2000.0\ndt = 0.01\nv = -70.0\nspikeThreshold = -20.0\n\nif __name__ == \"__main__\":\n\n # condition is tau_d >> T, tau_d_q << tau_r\n\n tau_d = 500.0\n tau_r = 100.0\n tau_d_q = 1.0\n # tau_peak = 20.0\n # print tau_d_q_function(tau_d, tau_r, tau_peak)\n x0 = initial_condition(v)\n t = np.arange(0, t_final, dt)\n sol = odeint(derivative, x0, t)\n V = sol[:, 0]\n S = sol[:, -1]\n nSteps = len(V)\n\n #spike detection\n nSpikes = 0\n tSpikes = []\n for i in range(1, nSteps):\n if (V[i - 1] <= spikeThreshold) & (V[i] > spikeThreshold):\n nSpikes += 1\n ts = ((i - 1) * dt * (V[i - 1] - spikeThreshold) +\n i * dt * (spikeThreshold - V[i])) / (V[i - 1] - V[i])\n tSpikes.append(ts)\n \n period = tSpikes[-1] - tSpikes[-2]\n print \"Period is %10.3f ms\" % period\n\n\n # --------------------------------------------------------------#\n \n fig, ax = pl.subplots(2, figsize=(7, 5), sharex=True)\n ax[0].plot(t, V, lw=2, c=\"k\")\n ax[1].plot(t, S, lw=2, c=\"k\")\n\n ax[0].set_xlim(min(t), max(t))\n ax[0].set_ylim(-100, 100)\n # ax[1].set_ylim([0, 1])\n ax[1].set_xlabel(\"time [ms]\", fontsize=14)\n ax[0].set_ylabel(\"v [mV]\", fontsize=14)\n ax[1].set_ylabel(\"s\", fontsize=14)\n ax[0].set_yticks([-100, 0, 100])\n # ax[1].set_yticks([0, 0.5, 1])\n\n pl.tight_layout()\n pl.savefig(\"fig_20_9.png\", dpi=150)\n # pl.show()\n" }, { "alpha_fraction": 0.5775862336158752, "alphanum_fraction": 0.6706896424293518, "avg_line_length": 15.083333015441895, "blob_id": "5fd59957bcd54cd74070717fc6ded58efc547a46", "content_id": "7ea16ef6d8f1c6b627e752c47be5a884aa0b2921", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 580, "license_type": "no_license", "max_line_length": 63, "num_lines": 36, "path": "/python/08_Quadratic_Integrate_and_Fire_(QIF)_and_Theta_Neurons/THREE_CIRCLES/main.py", "repo_name": "SaeedTaghavi/ModelingNeuralDynamics", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom math import pi\ntheta = np.arange(0,101,1)\ntheta = theta /100.\ntheta = theta * 2.*pi\n\nx=np.cos(theta)\ny=np.sin(theta)\n\ntheta0=-0.4*pi\nx0=np.cos(theta0)\ny0=np.sin(theta0)\neps=0.15\n\nplt.figure(figsize=(5,5))\n\nplt.plot(x,y)\nplt.scatter(x0,y0,s=1000*eps,facecolors='black')\n#plt.fill(x0+eps*x,y0+eps*y)\ny0=-y0\nplt.scatter(x0,y0,s=1000*eps,facecolors='none', edgecolors='r')\n#plt.fill(x0+eps*x,y0+eps*y,'r')\nplt.ylim((-1.5,1.50))\nplt.xlim((-1.5,1.50))\nplt.show()\n\n#inja jadide\nym1 = np.ma.masked_where(y1 > 0.5, y1)\n\n\n\n\n\n\nexit()\n\n" }, { "alpha_fraction": 0.7764623761177063, "alphanum_fraction": 0.7952646017074585, "avg_line_length": 50.28571319580078, "blob_id": "2adf29d8d752262a2e68662d11bc47fba9bce08a", "content_id": "24924281504dbb5332f61b3426af60cf5dba29ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1436, "license_type": "no_license", "max_line_length": 425, "num_lines": 28, "path": "/README.md", "repo_name": "SaeedTaghavi/ModelingNeuralDynamics", "src_encoding": "UTF-8", "text": "# ModelingNeuralDynamics\nAn Introduction to Modeling Neuronal Dynamics - Christoph Borgers in python\n\n![Cover](https://github.com/Ziaeemehr/ModelingNeuralDynamics/blob/master/python/30_The_PING_Model_of_Gamma_Rhythms/PING_4/fig.png )\n<p align=\"center\">\n Ping Model of Gamma Rhythm \n</p>\n\n<p align=\"center\">\n <img src=\"https://github.com/Ziaeemehr/ModelingNeuralDynamics/blob/master/python/22_A_Wilson_Cowan_Model_of_an_Oscillatory_E-I_Network/WILSON_COWAN_PHASE_PLANE/fig_22_3.png\"> \n</p>\n<p align=\"center\">\nWilson-Cowan phase plane\n</p>\n\n\n\n### Introduction \nThis book is intended as a text for a one-semester course on Mathematical and Computational Neuroscience for upper-level undergraduate and beginning graduate students of mathematics, the natural sciences, engineering, or computer science. An undergraduate introduction to differential equations is more than enough mathematical background. Only a slim, high school-level background in physics is assumed, and none in biology.\n\nTopics include models of individual nerve cells and their dynamics, models of networks of neurons coupled by synapses and gap junctions, origins and functions of population rhythms in neuronal networks, and models of synaptic plasticity.\n\nAn extensive online collection of Matlab programs generating the figures accompanies the book.\n\n### matlab code gathered from here\nhttps://link.springer.com/book/10.1007/978-3-319-51171-9\n\n### Python codes provided by me\n" }, { "alpha_fraction": 0.38394132256507874, "alphanum_fraction": 0.429945707321167, "avg_line_length": 28.826704025268555, "blob_id": "0cc992a2e927c189c3d008c57cb56ea8b2090eaf", "content_id": "8498440a307d1970e72972f98818a478f417f40c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10499, "license_type": "no_license", "max_line_length": 79, "num_lines": 352, "path": "/python/34_Nested_Gamma_Theta_Rhythms/PING_WITH_THETA_INHIBITION/lib.py", "repo_name": "SaeedTaghavi/ModelingNeuralDynamics", "src_encoding": "UTF-8", "text": "from scipy.integrate import odeint\nfrom numpy import exp, matmul\nfrom copy import copy\nimport numpy as np\nimport pylab as pl\nfrom main import *\n\n# def i_ext_e_function(t):\n# return i_ext_e * (1.0 + alpha * sin(2 * pi * t / P))\n\n\ndef alpha_ex(t):\n return exp(-10.0 * np.sin(np.pi * t / P) ** 2)\n\n\ndef h_e_inf(v):\n alpha_h = 0.128 * exp(-(v + 50) / 18)\n beta_h = 4.0 / (1.0 + exp(-(v + 27.0) / 5.0))\n return (alpha_h / (alpha_h + beta_h))\n\n\ndef h_i_inf(v):\n alpha_h = 0.07 * exp(-(v + 58.0) / 20.0)\n beta_h = 1.0 / (exp(-0.1 * (v + 28.0)) + 1.0)\n return (alpha_h / (alpha_h + beta_h))\n\n\ndef m_e_inf(v):\n alpha_m = 0.32 * (v + 54.0) / (1.0 - exp(-(v + 54.0) / 4.0))\n beta_m = 0.28 * (v + 27.0) / (exp((v + 27.0) / 5.0) - 1.0)\n return (alpha_m / (alpha_m + beta_m))\n\n\ndef m_i_inf(v):\n alpha_m = 0.1 * (v + 35.0) / (1.0 - exp(-(v + 35.0) / 10.0))\n beta_m = 4.0 * exp(-(v + 60.0) / 18.0)\n return (alpha_m / (alpha_m + beta_m))\n\n\ndef n_e_inf(v):\n alpha_n = 0.032 * (v + 52.0) / (1.0 - exp(-(v + 52.0) / 5.0))\n beta_n = 0.5 * exp(-(v + 57.0) / 40.0)\n return (alpha_n / (alpha_n + beta_n))\n\n\ndef n_i_inf(v):\n alpha_n = -0.01 * (v + 34.0) / (exp(-0.1 * (v + 34.0)) - 1.0)\n beta_n = 0.125 * exp(-(v + 44.0) / 80.0)\n return (alpha_n / (alpha_n + beta_n))\n\n\ndef tau_h_e(v):\n alpha_h = 0.128 * exp(-(v + 50.0) / 18.0)\n beta_h = 4.0 / (1.0 + exp(-(v + 27.0) / 5.0))\n return (1.0 / (alpha_h + beta_h))\n\n\ndef tau_h_i(v):\n alpha_h = 0.07 * exp(-(v + 58.0) / 20.0)\n beta_h = 1.0 / (exp(-0.1 * (v + 28.0)) + 1.0)\n tau_h = 1.0 / (alpha_h + beta_h)\n phi = 5.0\n return (tau_h / phi)\n\n\ndef tau_n_e(v):\n alpha_n = 0.032 * (v + 52.0) / (1.0 - exp(-(v + 52.0) / 5.0))\n beta_n = 0.5 * exp(-(v + 57.0) / 40.0)\n return (1.0 / (alpha_n + beta_n))\n\n\ndef tau_n_i(v):\n alpha_n = -0.01 * (v + 34.0) / (exp(-0.1 * (v + 34.0)) - 1.0)\n beta_n = 0.125 * exp(-(v + 44.0) / 80.0)\n tau_n = 1.0 / (alpha_n + beta_n)\n phi = 5.0\n return (tau_n / phi)\n# -------------------------------------------------------------------#\n\n\ndef tau_peak_function(tau_d, tau_r, tau_d_q):\n\n dt = 0.01\n dt05 = 0.5 * dt\n\n s = 0\n t = 0\n s_inc = exp(-t / tau_d_q) * (1.0 - s) / tau_r - s * tau_d\n while s_inc > 0:\n t_old = t\n s_inc_old = s_inc\n s_tmp = s + dt05 * s_inc\n s_inc_tmp = exp(-(t + dt05) / tau_d_q) * \\\n (1.0 - s_tmp) / tau_r - s_tmp / tau_d\n s = s + dt * s_inc_tmp\n t = t + dt\n s_inc = exp(-t / tau_d_q) * (1.0 - s) / tau_r - s / tau_d\n\n return (t_old * (-s_inc) + t * s_inc_old) / (s_inc_old - s_inc)\n# -------------------------------------------------------------------#\n\n\ndef tau_d_q_function(tau_d, tau_r, tau_hat):\n\n # set an interval for tau_d_q\n tau_d_q_left = 1.0\n while tau_peak_function(tau_d, tau_r, tau_d_q_left) > tau_hat:\n tau_d_q_left *= 0.5\n\n tau_d_q_right = tau_r\n while tau_peak_function(tau_d, tau_r, tau_d_q_right) < tau_hat:\n tau_d_q_right *= 2.0\n\n # bisection method\n while tau_d_q_right - tau_d_q_left > 1e-12:\n tau_d_q_mid = 0.5 * (tau_d_q_left + tau_d_q_right)\n if (tau_peak_function(tau_d, tau_r, tau_d_q_mid) <= tau_hat):\n tau_d_q_left = tau_d_q_mid\n else:\n tau_d_q_right = tau_d_q_mid\n\n return 0.5 * (tau_d_q_left + tau_d_q_right)\n# -------------------------------------------------------------------#\n\n\ndef derivativePopulation(x0, t=0):\n\n v_e = x0[:num_e]\n h_e = x0[num_e: 2 * num_e]\n n_e = x0[2 * num_e: 3 * num_e]\n q_e = x0[3 * num_e: 4 * num_e]\n s_e = x0[4 * num_e: 5 * num_e]\n n = 5 * num_e\n v_i = x0[n: n + num_i]\n h_i = x0[n + num_i: n + 2 * num_i]\n n_i = x0[n + 2 * num_i: n + 3 * num_i]\n q_i = x0[n + 3 * num_i: n + 4 * num_i]\n s_i = x0[n + 4 * num_i:]\n\n I_L_e = 0.1 * (v_e + 67.0)\n I_K_e = 80.0 * n_e ** 4 * (v_e + 100.0)\n I_Na_e = 100.0 * h_e * m_e_inf(v_e) ** 3 * (v_e - 50.0)\n I_syn_e = matmul(g_ee, s_e) * (v_rev_e - v_e) + \\\n matmul(g_ie, s_i) * (v_rev_i - v_e)\n\n dv_e = -I_L_e - I_K_e - I_Na_e + I_syn_e + i_ext_e + \\\n g_ex * alpha_ex(t) * (v_rev_i - v_e)\n dh_e = (h_e_inf(v_e) - h_e) / tau_h_e(v_e)\n dn_e = (n_e_inf(v_e) - n_e) / tau_n_e(v_e)\n dq_e = 0.5 * (1 + np.tanh(0.1 * v_e)) * (1.0 - q_e) * 10.0 - q_e / tau_dq_e\n ds_e = q_e * (1.0 - s_e) / tau_r_e - s_e / tau_d_e\n\n I_L_i = 0.1 * (v_i + 65.0)\n I_K_i = 9.0 * n_i ** 4 * (v_i + 90.0)\n I_Na_i = 35.0 * m_i_inf(v_i) ** 3 * h_i * (v_i - 55.0)\n I_syn_i = matmul(g_ei, s_e) * (v_rev_e - v_i) + \\\n matmul(g_ii, s_i) * (v_rev_i - v_i)\n\n dv_i = i_ext_i - I_Na_i - I_K_i - I_L_i + I_syn_i\n dh_i = (h_i_inf(v_i) - h_i) / tau_h_i(v_i)\n dn_i = (n_i_inf(v_i) - n_i) / tau_n_i(v_i)\n dq_i = 0.5 * (1.0 + np.tanh(0.1 * v_i)) * (1.0 - q_i) * 10 - q_i / tau_dq_i\n ds_i = q_i * (1.0 - s_i) / tau_r_i - s_i / tau_d_i\n\n return np.hstack((dv_e, dh_e, dn_e, dq_e, ds_e,\n dv_i, dh_i, dn_i, dq_i, ds_i))\n# -------------------------------------------------------------------#\n\n\ndef derivative(x0, t=0):\n\n n0 = len(x0) / 3\n v_e = x0[:n0]\n h_e = x0[n0: (2 * n0)]\n n_e = x0[(2 * n0): (3 * n0)]\n\n I_L_e = 0.1 * (v_e + 67.0)\n I_K_e = 80 * n_e ** 4 * (v_e + 100.0)\n I_Na_e = 100 * h_e * m_e_inf(v_e) ** 3 * (v_e - 50.0)\n\n dv_e = i_ext_e - I_L_e - I_K_e - I_Na_e\n dh_e = (h_e_inf(v_e) - h_e) / tau_h_e(v_e)\n dn_e = (n_e_inf(v_e) - n_e) / tau_n_e(v_e)\n\n return np.hstack((dv_e, dh_e, dn_e))\n# -------------------------------------------------------------------#\n\n\ndef splayState(i_ext_e, phiVec, f):\n \"\"\"\n input: i_ext=column vector of external drives \n phi_vec = column vector of phases at which \n neurons are to be initialized\n The length, num, of i_ext is the total number \n of neurons.\n output: a num-by-3 array called rtm_init. The columns\n contain values of v, h, and n. If i_ext(i) is below\n the firing threshold, then the i-th row of the\n matrix rtm_init contains the stable equilibrium point.\n If i_ext(i) is above the firing threshold, then the\n i-th row of rtm_init is a point (v,h,n) on the limit\n cycle, at phase phi_vec(i).\n \"\"\"\n\n t = 0.0\n dt = 0.01\n t_final = 2000.0 # if fewer than max_spikes spikes occur\n # by this time, the program gives\n # up and sets (v,h,n) equal\n # to the values at time t_final.\n maxNumSpikes = 3\n N = len(i_ext_e)\n numSpikes = np.zeros(N, dtype=int)\n done = np.zeros(N) # done[i]=1 indicates that we are\n # done with neuron i.\n iteration = 0\n numSteps = int(t_final / dt)\n\n v = -70.0 * np.ones(N)\n m = m_e_inf(v)\n n = n_e_inf(v)\n h = h_e_inf(v)\n x0 = np.hstack((v, h, n))\n\n tSpikes = np.zeros((N, maxNumSpikes))\n initialConition = np.zeros((N, 3))\n\n # ofile = open(\"v.txt\", \"w\")\n i = 1\n while (np.sum(done) < N) and (t < t_final):\n\n v_old = v\n h_old = h\n n_old = n\n t_old = t\n\n x = rungeKuttaIntegrator(x0, dt, f)\n i += 1\n\n v = x[:N]\n h = x[N: (2 * N)]\n n = x[(2 * N):]\n t = i * dt\n\n x0 = copy(x)\n\n # ofile.write(\"%18.4f %18.4f \\n\" % (i*dt, v))\n indices = np.where((v_old >= spikeThreshold) &\n (v < spikeThreshold))[0]\n\n numInstantSpikes = len(indices)\n for k in indices:\n numSpikes[k] += 1\n ts = (t_old * (v_old[k] - spikeThreshold) +\n t * (spikeThreshold - v[k])) / (v_old[k] - v[k])\n\n if numSpikes[k] < 4:\n tSpikes[k, numSpikes[k] - 1] = ts\n\n thr = tSpikes[:, -1] + phiVec * (tSpikes[:, -1] - tSpikes[:, -2])\n indices = np.where((numSpikes == maxNumSpikes) &\n (t > thr) &\n (t_old <= thr))\n\n for i0 in range(len(indices)):\n k = indices[i0]\n initialConition[k, 0] = (\n v_old[k] * (t - thr[k]) + v[k] * (thr[k] - t_old)) / dt\n initialConition[k, 1] = (\n h_old[k] * (t - thr[k]) + h[k] * (thr[k] - t_old)) / dt\n initialConition[k, 2] = (\n n_old[k] * (t - thr[k]) + n[k] * (thr[k] - t_old)) / dt\n done[indices] = 1\n\n indices = np.where(done == 0)[0]\n initialConition[indices, 0] = v[indices]\n initialConition[indices, 1] = h[indices]\n initialConition[indices, 2] = n[indices]\n\n # print (\"Period is %10.3f [ms]\" % T)\n\n return initialConition\n# -------------------------------------------------------------------#\n\n\ndef spikeDetection(t, V, spikeThreshold):\n tSpikes = []\n v = np.asarray(V)\n nSteps = len(V)\n\n for i in range(1, nSteps):\n if (V[i - 1] <= spikeThreshold) & (V[i] > spikeThreshold):\n\n ts = ((i - 1) * dt * (V[i - 1] - spikeThreshold) +\n i * dt * (spikeThreshold - V[i])) / (V[i - 1] - V[i])\n tSpikes.append(ts)\n return tSpikes\n# -------------------------------------------------------------------#\n\n\ntau_dq_e = tau_d_q_function(tau_d_e, tau_r_e, tau_peak_e)\ntau_dq_i = tau_d_q_function(tau_d_i, tau_r_i, tau_peak_i)\n# -------------------------------------------------------------------#\n\n\ndef display_time(time):\n ''' print wall time '''\n\n hour = int(time/3600)\n minute = (int(time % 3600))/60\n second = time-(3600.*hour+60.*minute)\n print \"Done in %d hours %d minutes %.6f seconds\" \\\n % (hour, minute, second)\n# -------------------------------------------------------------------#\n\n\ndef spikeToFile(t_spikes, fileName):\n\n f = open(fileName, \"w\")\n n = len(t_spikes)\n for i in range(n):\n for j in range(len(t_spikes[i])):\n f.write(\"%18.4f\" % t_spikes[i][j])\n f.write(\"\\n\")\n\n f.close()\n# -------------------------------------------------------------------#\n\n\ndef rungeKuttaIntegrator(x, dt, f):\n\n k1 = dt * f(x)\n k2 = dt * f(x + 0.5 * k1)\n k3 = dt * f(x + 0.5 * k2)\n k4 = dt * f(x + k3)\n\n x = x + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0\n\n return x\n# -------------------------------------------------------------------#\n\n\ndef read_from_file(fileName):\n\n with open(fileName, \"r\") as text:\n data = []\n for line in text:\n line = line.split()\n line = [float(i) for i in line]\n data.append(line)\n\n return data\n" }, { "alpha_fraction": 0.437988817691803, "alphanum_fraction": 0.4960893988609314, "avg_line_length": 16.568628311157227, "blob_id": "ebe1e9dbdc1e13c23eaf06d3cac58d3f09eb9c2a", "content_id": "8eea0b9b31e3cf7b59ed1dc598e4484a63953e82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 895, "license_type": "no_license", "max_line_length": 55, "num_lines": 51, "path": "/python/07_Linear_Integrate_and_Fire_(LIF)_Neurons/LIF_VOLTAGE_TRACE2/main.py", "repo_name": "SaeedTaghavi/ModelingNeuralDynamics", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pylab as pl\n\n\ndef integrate_rk4(x, dt, f):\n k1 = dt * f(x)\n k2 = dt * f(x + 0.5 * k1)\n k3 = dt * f(x + 0.5 * k2)\n k4 = dt * f(x + k3)\n\n x = x + (k1 + 2.0 * (k2 + k3) + k4) / 6.0\n return x\n\n\ndef derivative(v):\n dv = -v / tau_m + I\n return dv\n\n\nt_final = 50.0\ntau_m = 2.0\ndt = 0.01\nI = 1 / (1 - np.exp(-20.0 / tau_m)) / tau_m\nprint I\n\n\n\nif __name__ == \"__main__\":\n\n numSteps = int(t_final / dt)\n v = np.zeros(numSteps)\n t = np.arange(0, t_final, dt)\n\n for i in range(1, numSteps):\n v_new = integrate_rk4(v[i - 1], dt, derivative)\n\n if v_new <= 1:\n v[i] = v_new\n else:\n v[i] = 0.0\n\n\npl.figure(figsize=(7, 3))\npl.xlabel(\"time [ms]\", fontsize=14)\npl.ylabel(\"v [mV]\", fontsize=14)\npl.ylim([0, 2])\npl.xlim(0, max(t))\npl.tight_layout()\npl.plot(t, v, lw=2, c=\"k\")\npl.savefig(\"fig_7_5.png\")\npl.show()" }, { "alpha_fraction": 0.4011194109916687, "alphanum_fraction": 0.4757462739944458, "avg_line_length": 17.697673797607422, "blob_id": "d084cda70fe473050adf55cd08b644239498092d", "content_id": "f58f4f794c1a8b893e0ab17d5b3c6e3183c90608", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1608, "license_type": "no_license", "max_line_length": 69, "num_lines": 86, "path": "/python/30_The_PING_Model_of_Gamma_Rhythms/2_CELL_PING/main.py", "repo_name": "SaeedTaghavi/ModelingNeuralDynamics", "src_encoding": "UTF-8", "text": "from scipy.integrate import odeint\nimport numpy as np\nimport pylab as pl\nimport lib\n\n\ni_ext_e = 1.4\ni_ext_i = 0.0\ng_ei = 0.25\ng_ie = 0.25\nv_rev_e = 0.0\nv_rev_i = -75.0\ntau_r_e = 0.5\ntau_peak_e = 0.5\ntau_d_e = 3.0\ntau_r_i = 0.5\ntau_peak_i = 0.5\ntau_d_i = 9.0\nt_final = 200.0\ndt = 0.01\n\n# ------------------------------------------------------------------#\n\n\nif __name__ == \"__main__\":\n\n # initial conditions\n v_e = -75.0\n h_e = 0.1\n n_e = 0.1\n q_e = 0\n s_e = 0\n v_i = -75.0\n h_i = 0.1\n n_i = 0.1\n q_i = 0\n s_i = 0\n initialConditions = [v_e, h_e, n_e, q_e, s_e,\n v_i, h_i, n_i, q_i, s_i]\n\n t = np.arange(0, t_final, dt)\n sol = odeint(lib.derivative,\n initialConditions,\n t)\n\n v_e = sol[:, 0]\n v_i = sol[:, 5]\n\n eSpikes = lib.spikeDetection(t, v_e, -20.0)\n period = eSpikes[-1] - eSpikes[-2]\n print \"Period of E neuron %10.3f ms\" % period\n\n\n\n pl.figure(figsize=(7, 3))\n pl.plot(t, v_e, lw=2, c=\"r\", label=r\"$v_e$\")\n pl.plot(t, v_i, lw=2, c=\"b\", label=r\"$v_i$\")\n pl.xlim(min(t), max(t))\n # pl.ylim(-100, 50)\n pl.xlabel(\"time [ms]\", fontsize=16)\n pl.ylabel(\"v [mV]\", fontsize=16)\n pl.legend(fontsize=14, loc=\"upper right\")\n pl.xticks(range(0, int(t_final) + 1, 50))\n pl.tight_layout()\n pl.tick_params(labelsize=14)\n\n pl.savefig(\"fig_30_3.png\")\n pl.show()\n\n# RTM parameters\n# c = 1\n# g_k = 80\n# g_na = 100\n# g_l = 0.1\n# v_k = -100\n# v_na = 50\n# v_l = -67\n\n# WB parameters\n# c = 1.0\n# g_k = 9.0\n# g_Na = 35.0\n# g_l = 0.1\n# v_k = -90.0\n# v_na = 55.0\n# v_l = -65.0\n" } ]
11
tedconf/gmond_python_modules
https://github.com/tedconf/gmond_python_modules
2b64ddeaf08c8f0449f99f5de9635c79c97fc38e
bae8b6bb6e3ee214582e3a180a1634ef47e16e18
74c7b48585f48f8c0458cd78f8af8da23489b17e
refs/heads/master
2017-04-29T16:58:40.389022
2014-05-23T19:05:48
2014-05-23T19:05:48
20,110,047
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6996699571609497, "alphanum_fraction": 0.7128713130950928, "avg_line_length": 16.823530197143555, "blob_id": "4fdb41bfc55610df9e8c85e9d4beff286be2682e", "content_id": "9f739fbf7ab15488d3bc60747749d876c4d5bbb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 606, "license_type": "no_license", "max_line_length": 80, "num_lines": 34, "path": "/celery/README.md", "repo_name": "tedconf/gmond_python_modules", "src_encoding": "UTF-8", "text": "celery\n===============\n\nPython module for ganglia 3.1.\n\nThis module allows you to collect from Celery Distributed Task Queue\nfrom http://docs.celeryproject.org.\n\nPrerequisite\n============\n\nMake sure Celery exposes it's API over HTTP e.g.\n\ncurl http://localhost:8989/api/worker/\n\nor similar needs to succeed for this module to work.\n\n\nInstall\n===============\n\nCopy ganglia_celery.py from python_modules to your python modules directory e.g.\n\n/usr/lib64/ganglia/python_modules\n\nand celery.pyconf to\n\n/etc/ganglia/conf.d/\n\nRestart Gmond and you are done.\n\n## AUTHOR\n\nAuthor: Vladimir Vuksan https://github.com/vvuksan\n" }, { "alpha_fraction": 0.6773241758346558, "alphanum_fraction": 0.7520905137062073, "avg_line_length": 28.897058486938477, "blob_id": "32d7ebf7831e0b59544a559da779c7b96b3e2d26", "content_id": "1bcc7ffb92d6c32b796280bc161b52c3f09ebbd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2033, "license_type": "no_license", "max_line_length": 100, "num_lines": 68, "path": "/network/multi_interface/README.mkdn", "repo_name": "tedconf/gmond_python_modules", "src_encoding": "UTF-8", "text": "multi_interface\n===============\n\nPython module for ganglia 3.1+\n\nThis module allows you to collect per network interface network stats. Out\nof the box Ganglia provides only aggregate network metrics. This module will\ngive you rx (receive) and tx (transmit) stats for every interface it encounters\ne.g.\n\nvalue for rx_bytes_lo is 21847.3723\nvalue for rx_pkts_lo is 17.5771\nvalue for rx_errs_lo is 0.0000\nvalue for rx_drops_lo is 0.0000\nvalue for tx_bytes_lo is 21847.3723\nvalue for tx_pkts_lo is 17.5771\nvalue for tx_errs_lo is 0.0000\nvalue for tx_drops_lo is 0.0000\nvalue for rx_bytes_eth0 is 0.0000\nvalue for rx_pkts_eth0 is 0.0000\nvalue for rx_errs_eth0 is 0.0000\nvalue for rx_drops_eth0 is 0.0000\nvalue for tx_bytes_eth0 is 0.0000\nvalue for tx_pkts_eth0 is 0.0000\nvalue for tx_errs_eth0 is 0.0000\nvalue for tx_drops_eth0 is 0.0000\nvalue for rx_bytes_eth1 is 0.0000\nvalue for rx_pkts_eth1 is 0.0000\nvalue for rx_errs_eth1 is 0.0000\nvalue for rx_drops_eth1 is 0.0000\nvalue for tx_bytes_eth1 is 0.0000\nvalue for tx_pkts_eth1 is 0.0000\nvalue for tx_errs_eth1 is 0.0000\nvalue for tx_drops_eth1 is 0.0000\n\nYou can run the multi_interface.py script by hand to see all of the metrics.\n\nIn addition this script can be used to override \"default\" bytes_in, bytes_out, pkts_in and pkts_out\nmetrics. To do that you will need to \n\n* set send_aggregate_bytes_packets to True in multi_interface.pyconf\n* Uncomment bytes_in, bytes_out metrics to be sent in in multi_interface.pyconf\n* Comment out those same metrics you uncommented in step above in gmond.conf so they don't override \n each other\n\n\nInstall \n=============== \n\nCopy multi_interface.py from python_modules to your python modules directory e.g.\n\n/usr/lib64/ganglia/python_modules\n\nand multi_interface.pyconf to\n\n/etc/ganglia/conf.d/\n\nRestart Gmond and you are done. If you want only specific interfaces add a space\ndelimited list of interfaces in multi_interface.pyconf e.g.\n\n param interfaces {\n value = \"eth0 eth2\"\n }\n\n\n## AUTHOR\n\nAuthor: Vladimir Vuksan https://github.com/vvuksan\n" }, { "alpha_fraction": 0.6297488808631897, "alphanum_fraction": 0.6372918486595154, "avg_line_length": 33.95498275756836, "blob_id": "c46e010cd5ba01b68d312ddfb47a434bfffa3f55", "content_id": "101b2daf2bc2dc7bcf08f60b851bf790cbc5ead5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10871, "license_type": "no_license", "max_line_length": 210, "num_lines": 311, "path": "/rabbit/python_modules/rabbitmq.py", "repo_name": "tedconf/gmond_python_modules", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.4\nimport sys\nimport os\nimport json\nimport urllib2\nimport time\nfrom string import Template\nimport itertools\nimport threading\n\nglobal url, descriptors, last_update, vhost, username, password, url_template, result, result_dict, keyToPath\n\n\nJSON_PATH_SEPARATOR = \"?\"\nMETRIC_TOKEN_SEPARATOR = \"___\"\n \nINTERVAL = 10\ndescriptors = list()\nusername, password = \"guest\", \"guest\"\nstats = {}\nkeyToPath = {}\nlast_update = None\n#last_update = {}\ncompiled_results = {\"nodes\" : None, \"queues\" : None, \"connections\" : None}\n#Make initial stat test time dict\n#for stat_type in ('queues', 'connections','exchanges', 'nodes'):\n# last_update[stat_type] = None\n\n### CONFIGURATION SECTION ###\nSTATS = ['nodes', 'queues']\n\n# QUEUE METRICS #\nkeyToPath['rmq_messages_ready'] = \"%s{0}messages_ready\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_messages_unacknowledged'] = \"%s{0}messages_unacknowledged\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_backing_queue_ack_egress_rate'] = \"%s{0}backing_queue_status{0}avg_ack_egress_rate\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_backing_queue_ack_ingress_rate'] = \"%s{0}backing_queue_status{0}avg_ack_ingress_rate\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_backing_queue_egress_rate'] = \"%s{0}backing_queue_status{0}avg_egress_rate\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_backing_queue_ingress_rate'] = \"%s{0}backing_queue_status{0}avg_ingress_rate\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_backing_queue_mirror_senders'] = \"%s{0}backing_queue_status{0}mirror_senders\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_memory'] = \"%s{0}memory\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_consumers'] = \"%s{0}consumers\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_messages'] = \"%s{0}messages\".format(JSON_PATH_SEPARATOR)\n\nRATE_METRICS = [\n 'rmq_backing_queue_ack_egress_rate',\n 'rmq_backing_queue_ack_ingress_rate',\n 'rmq_backing_queue_egress_rate',\n 'rmq_backing_queue_ingress_rate'\n]\n\nQUEUE_METRICS = ['rmq_messages_ready',\n\t\t'rmq_messages_unacknowledged',\n\t\t'rmq_backing_queue_ack_egress_rate',\n\t\t'rmq_backing_queue_ack_ingress_rate',\n\t\t'rmq_backing_queue_egress_rate',\n\t\t'rmq_backing_queue_ingress_rate',\n\t\t'rmq_backing_queue_mirror_senders',\n\t\t'rmq_memory',\n 'rmq_consumers',\n\t\t'rmq_messages']\n\n# NODE METRICS #\nkeyToPath['rmq_disk_free'] = \"%s{0}disk_free\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_disk_free_alarm'] = \"%s{0}disk_free_alarm\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_fd_used'] = \"%s{0}fd_used\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_fd_used'] = \"%s{0}fd_used\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_mem_used'] = \"%s{0}mem_used\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_proc_used'] = \"%s{0}proc_used\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_sockets_used'] = \"%s{0}sockets_used\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_mem_alarm'] = \"%s{0}mem_alarm\".format(JSON_PATH_SEPARATOR) #Boolean\nkeyToPath['rmq_mem_binary'] = \"%s{0}mem_binary\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_mem_code'] = \"%s{0}mem_code\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_mem_proc_used'] = \"%s{0}mem_proc_used\".format(JSON_PATH_SEPARATOR)\nkeyToPath['rmq_running'] = \"%s{0}running\".format(JSON_PATH_SEPARATOR) #Boolean\n\nNODE_METRICS = ['rmq_disk_free', 'rmq_mem_used', 'rmq_disk_free_alarm', 'rmq_running', 'rmq_proc_used', 'rmq_mem_proc_used', 'rmq_fd_used', 'rmq_mem_alarm', 'rmq_mem_code', 'rmq_mem_binary', 'rmq_sockets_used']\n\t\n\n\n\ndef metric_cleanup():\n pass\n\ndef dig_it_up(obj,path):\n try:\n\tpath = path.split(JSON_PATH_SEPARATOR)\n return reduce(lambda x,y:x[y],path,obj)\n except:\n print \"Exception\"\n return False\n\ndef refreshStats(stats = ('nodes', 'queues'), vhosts = ['/']):\n\n global url_template\n global last_update, url, compiled_results\n\n now = time.time()\n\n if not last_update:\n diff = INTERVAL\n else:\n diff = now - last_update\n\n if diff >= INTERVAL or not last_update:\n\tprint \"Fetching Results after %d seconds\" % INTERVAL\n\tlast_update = now\n for stat in stats:\n for vhost in vhosts:\n if stat in ('nodes'):\n vhost = '/'\n\t\tresult_dict = {}\n urlstring = url_template.safe_substitute(stats = stat, vhost = vhost)\n print urlstring\n result = json.load(urllib2.urlopen(urlstring))\n\t\t# Rearrange results so entry is held in a dict keyed by name - queue name, host name, etc.\n\t\tif stat in (\"queues\", \"nodes\", \"exchanges\"):\n\t\t for entry in result:\n\t\t name = entry['name']\n\t\t\tresult_dict[name] = entry\n\t\t compiled_results[(stat, vhost)] = result_dict\n\n return compiled_results\n\n\ndef validatedResult(value):\n if not isInstance(value, bool):\n return float(value)\n else:\n return None\n\ndef list_queues(vhost):\n global compiled_results\n queues = compiled_results[('queues', vhost)].keys()\n return queues\n\ndef list_nodes():\n global compiled_results\n nodes = compiled_results[('nodes', '/')].keys()\n return nodes\n\ndef getQueueStat(name):\n refreshStats(stats = STATS, vhosts = vhosts)\n #Split a name like \"rmq_backing_queue_ack_egress_rate.access\"\n \n #handle queue names with . in them\n print name\n stat_name, queue_name, vhost = name.split(METRIC_TOKEN_SEPARATOR)\n \n vhost = vhost.replace('-', '/') #decoding vhost from metric name\n # Run refreshStats to get the result object\n result = compiled_results[('queues', vhost)]\n \n value = dig_it_up(result, keyToPath[stat_name] % queue_name)\n \n if zero_rates_when_idle and stat_name in RATE_METRICS and 'idle_since' in result[queue_name].keys():\n value = 0\n\n #Convert Booleans\n if value is True:\n value = 1\n elif value is False:\n value = 0\n\n return float(value)\n\ndef getNodeStat(name):\n refreshStats(stats = STATS, vhosts = vhosts)\n #Split a name like \"rmq_backing_queue_ack_egress_rate.access\"\n stat_name, node_name, vhost = name.split(METRIC_TOKEN_SEPARATOR)\n vhost = vhost.replace('-', '/') #decoding vhost from metric name\n\n result = compiled_results[('nodes', '/')]\n value = dig_it_up(result, keyToPath[stat_name] % node_name)\n\n print name,value\n #Convert Booleans\n if value is True:\n value = 1\n elif value is False:\n value = 0\n\n return float(value)\n\ndef product(*args, **kwds):\n # replacement for itertools.product\n # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy\n pools = map(tuple, args) * kwds.get('repeat', 1)\n result = [[]]\n for pool in pools:\n result = [x+[y] for x in result for y in pool]\n for prod in result:\n yield tuple(prod)\n\ndef str2bool(string):\n if string.lower() in (\"yes\", \"true\"):\n return True\n if string.lower() in (\"no\", \"false\"):\n return False\n raise Exception(\"Invalid value of the 'zero_rates_when_idle' param, use one of the ('true', 'yes', 'false', 'no')\")\n \ndef metric_init(params):\n ''' Create the metric definition object '''\n global descriptors, stats, vhost, username, password, urlstring, url_template, compiled_results, STATS, vhosts, zero_rates_when_idle\n print 'received the following params:'\n #Set this globally so we can refresh stats\n if 'host' not in params:\n params['host'], params['vhost'],params['username'],params['password'],params['port'] = \"localhost\", \"/\", \"guest\", \"guest\", \"15672\"\n if 'zero_rates_when_idle' not in params:\n params['zero_rates_when_idle'] = \"false\"\n\n # Set the vhosts as a list split from params\n vhosts = params['vhost'].split(',')\n username, password = params['username'], params['password']\n host = params['host']\n port = params['port']\n\n zero_rates_when_idle = str2bool(params['zero_rates_when_idle'])\n \n url = 'http://%s:%s/api/$stats/$vhost' % (host,port)\n base_url = 'http://%s:%s/api' % (host,port)\n password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()\n password_mgr.add_password(None, base_url, username, password)\n handler = urllib2.HTTPBasicAuthHandler(password_mgr)\n opener = urllib2.build_opener(handler)\n opener.open(base_url)\n urllib2.install_opener(opener)\n url_template = Template(url)\n print params\n\n refreshStats(stats = STATS, vhosts = vhosts)\n\n def metric_handler(name):\n if 15 < time.time() - metric_handler.timestamp:\n metric_handler.timestamp = time.time()\n return refreshStats(stats = STATS, vhosts = vhosts)\n\n \n\n def create_desc(prop):\n\td = {\n\t 'name' : 'XXX',\n\t 'call_back' : getQueueStat,\n\t 'time_max' : 60,\n\t 'value_type' : 'uint',\n\t 'units' : 'units',\n\t 'slope' : 'both',\n\t 'format' : '%d',\n\t 'description' : 'XXX',\n\t 'groups' : params[\"metric_group\"],\n\t}\n\n\tfor k,v in prop.iteritems():\n\t d[k] = v\n\treturn d\n\n\n def buildQueueDescriptors():\n for vhost, metric in product(vhosts, QUEUE_METRICS):\n queues = list_queues(vhost)\n for queue in queues:\n name = \"{1}{0}{2}{0}{3}\".format(METRIC_TOKEN_SEPARATOR, metric, queue, vhost.replace('/', '-'))\n\t\tprint name\n\t\td1 = create_desc({'name': name.encode('ascii','ignore'),\n\t\t 'call_back': getQueueStat,\n 'value_type': 'float',\n\t\t 'units': 'N',\n\t\t 'slope': 'both',\n\t\t 'format': '%f',\n\t\t 'description': 'Queue_Metric',\n\t\t 'groups' : 'rabbitmq,queue'})\n\t\tprint d1\n\t\tdescriptors.append(d1)\n \n def buildNodeDescriptors():\n for metric in NODE_METRICS:\n for node in list_nodes():\n name = \"{1}{0}{2}{0}-\".format(METRIC_TOKEN_SEPARATOR, metric, node)\n print name\n d2 = create_desc({'name': name.encode('ascii','ignore'),\n\t\t 'call_back': getNodeStat,\n 'value_type': 'float',\n\t\t 'units': 'N',\n\t\t 'slope': 'both',\n\t\t 'format': '%f',\n\t\t 'description': 'Node_Metric',\n\t\t 'groups' : 'rabbitmq,node'}) \n print d2\n descriptors.append(d2)\n\n buildQueueDescriptors()\n buildNodeDescriptors()\n # buildTestNodeStat()\n\t\n return descriptors\n\ndef metric_cleanup():\n pass\n \n\nif __name__ == \"__main__\":\n url = 'http://%s:%s@localhost:15672/api/$stats' % (username, password)\n url_template = Template(url)\n print \"url_template is \", url_template\n### in config files we use '/' in vhosts names but we should convert '/' to '-' when calculating a metric\n parameters = {\"vhost\":\"/\", \"username\":\"guest\",\"password\":\"guest\", \"metric_group\":\"rabbitmq\", \"zero_rates_when_idle\": \"yes\"}\n metric_init(parameters)\n result = refreshStats(stats = ('queues', 'nodes'), vhosts = ('/'))\n print '***'*20\n getQueueStat('rmq_backing_queue_ack_egress_rate___nfl_client___-')\n getNodeStat('rmq_disk_free___rmqone@inrmq01d1___-')\n getNodeStat('rmq_mem_used___rmqone@inrmq01d1___-')\n" } ]
3
mikegchambers/cfn-yaml-snippet
https://github.com/mikegchambers/cfn-yaml-snippet
8037cb6a84e0ffe691e1d50eccf808c8fda135b7
6f226c3b7d757d686815a3b50f44e07a14471047
890555fcd90b466fb545db2a05d62c9b53c12f3e
refs/heads/master
2022-02-22T23:34:42.107346
2022-02-13T06:04:00
2022-02-13T06:04:00
124,055,851
5
3
null
null
null
null
null
[ { "alpha_fraction": 0.5661016702651978, "alphanum_fraction": 0.5762711763381958, "avg_line_length": 40.1705436706543, "blob_id": "168365101b9d1d260c43e875ec52929e77840a72", "content_id": "2b6912eaf3d02c0a0313fa1959d7bbbbdce47faa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5310, "license_type": "no_license", "max_line_length": 436, "num_lines": 129, "path": "/create-cfn-snippet.py", "repo_name": "mikegchambers/cfn-yaml-snippet", "src_encoding": "UTF-8", "text": "#!/bin/python\n\nimport argparse\nimport urllib.request\nimport json\nfrom pprint import pprint\n\n\n# Input arguments:\n\nparser = argparse.ArgumentParser(description='Create an AWS CloudfFormation TextMate Snippet file.')\nparser.add_argument('--input', type=str, default=\"CloudFormationResourceSpecification.json\",\n help='Source (Input) file from AWS')\n\nparser.add_argument('--output', type=str, default=\"yaml.json\",\n help='Output file')\n\nparser.add_argument('--remote', type=bool, default=False,\n help='Attempt to get the source file direct from AWS.')\n\nparser.add_argument('--url', type=str, default=\"https://d2stg8d246z9di.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json\",\n help='Input web link')\n\nargs = parser.parse_args()\n\n# Load the source data:\n\nif args.remote == True:\n response = urllib.request.urlopen(args.url)\n data = response.read()\nelse:\n data = json.load(open(args.input))\n\ndata = json.load(open(args.input))\n\n# Start the output data, add the default/extra snippets:\n\noutput = {}\noutput[\"cfn\"] ={ \"prefix\" : \"cfn\", \"body\" : \"AWSTemplateFormatVersion: 2010-09-09\\r\\n\\r\\nDescription: #String\\r\\n\\r\\nMetadata:\\r\\n\\t#template metadata\\r\\n\\r\\nParameters:\\r\\n\\t#set of parameters\\r\\n\\r\\nMappings:\\r\\n\\t#set of mappings\\r\\n\\r\\nConditions:\\r\\n\\t#set of conditions\\r\\n\\r\\nTransform:\\r\\n\\t#set of transforms\\r\\n\\r\\nResources:\\r\\n\\t#set of resources\\r\\n\\r\\nOutputs:\\r\\n\\t#set of outputs\\r\\n\", \"description\" : \"Full template.\" }\noutput[\"cfn-lite\"] ={ \"prefix\" : \"cfn-lite\", \"body\" : \"AWSTemplateFormatVersion: 2010-09-09\\r\\n\\r\\nDescription: #String\\r\\n\\r\\nParameters:\\r\\n\\t#set of parameters\\r\\n\\r\\nResources:\\r\\n\\t#set of resources\\r\\n\\r\\nOutputs:\\r\\n\\t#set of outputs\\r\\n\", \"description\" : \"Full template.\" }\noutput[\"metadata\"] ={ \"prefix\" : \"metadata\", \"body\" : \"\", \"description\" : \"\" }\noutput[\"parameters\"] ={ \"prefix\" : \"parameters\", \"body\" : \"${1:LogicalID}:\\r\\n\\tType: String\\r\\n\\tDefault: t2.micro\\r\\n\\tAllowedValues:\\r\\n\\t\\t- t2.micro\\r\\n\\t\\t- m1.small\\r\\n\\t\\t- m1.large\\r\\n\\tDescription: Enter t2.micro, m1.small, or m1.large. Default is t2.micro.\\r\\n\", \"description\" : \"\" }\noutput[\"mappings\"] ={ \"prefix\" : \"mappings\", \"body\" : \"${1:LogicalID}:\\r\\n\\tKey01:\\r\\n\\t\\tName: Value01\\r\\n\\tKey02:\\r\\n\\t\\tName: Value02\\r\\n\\tKey03:\\r\\n\\t\\tName: Value03\\r\\n\", \"description\" : \"\" }\noutput[\"conditions\"] ={ \"prefix\" : \"conditions\", \"body\" : \"${1:LogicalID}:\\r\\n\\tIntrinsic function\\r\\n\", \"description\" : \"\" }\noutput[\"transforms\"] ={ \"prefix\" : \"transforms\", \"body\" : \"\", \"description\" : \"\" }\noutput[\"outputs\"] ={ \"prefix\" : \"outputs\", \"body\" : \"${1:LogicalID}:\\r\\n\\tDescription: Information about the value\\r\\n\\tValue: Value to return\\r\\n\\tExport:\\r\\n\\t\\tName: Value to export\\r\\n\", \"description\" : \"\" }\n\n# Add the resources to the output\n\nfor d in data['ResourceTypes']:\n\n prefix = d.replace('AWS::', \"\")\n prefix = prefix.replace('::', \"-\")\n prefix = prefix.lower()\n\n body = \"\"\n description = \"\"\n scope = \"source.cloudformation\"\n\n body = body + ( '${1:LogicalID}:\\r\\n' )\n\n # add a name placeholder\n body = body + ( '\\tType: \\\"' + d + '\\\"\\r\\n' )\n body = body + ( \"\\tProperties:\\r\\n\")\n\n description = description + d + \"\\r\\n\" + data['ResourceTypes'][d]['Documentation']\n\n # for each resources 'properties':\n for p in data['ResourceTypes'][d]['Properties']:\n\n required = data['ResourceTypes'][d]['Properties'][p]['Required']\n\n item = \"\"\n itemList = 0\n\n\n if ( 'PrimitiveType' in data['ResourceTypes'][d]['Properties'][p] ):\n item = data['ResourceTypes'][d]['Properties'][p]['PrimitiveType']\n \n if ( 'PrimitiveItemType' in data['ResourceTypes'][d]['Properties'][p] ):\n item = data['ResourceTypes'][d]['Properties'][p]['PrimitiveItemType']\n \n\n if ( 'ItemType' in data['ResourceTypes'][d]['Properties'][p] ):\n item = data['ResourceTypes'][d]['Properties'][p]['ItemType']\n\n if ( 'Type' in data['ResourceTypes'][d]['Properties'][p] ):\n if ( data['ResourceTypes'][d]['Properties'][p]['Type'] == \"List\" ):\n itemList = 1\n else:\n itemList = 2\n item = data['ResourceTypes'][d]['Properties'][p]['Type']\n\n ###########################\n\n if (itemList == 0):\n body = body + ( \"\\t\\t\" + p + \": \" + item + \"\" )\n if (required):\n body = body + ( \" #required\\r\\n\" )\n else:\n body = body + ( \"\\r\\n\" )\n\n\n elif (itemList == 1):\n body = body + ( \"\\t\\t\" + p + \":\" + \"\" )\n if (required):\n body = body + ( \" #required\\r\\n\" )\n else:\n body = body + ( \"\\r\\n\" )\n\n body = body + ( \"\\t\\t\\t- \" + item + \"\\r\\n\")\n\n\n\n elif (itemList == 2):\n body = body + ( \"\\t\\t\" + p + \":\" + \"\" )\n if (required):\n body = body + ( \" #required\\r\\n\" )\n else: \n body = body + ( \"\\r\\n\" )\n\n body = body + ( \"\\t\\t\\t\" + item + \"\\r\\n\")\n \n output[d] ={ \"prefix\" : prefix, \"body\" : body, \"description\" : description }\n\n#print( json.dumps(output) )\n\nwith open(args.output, \"w\") as text_file:\n text_file.write( json.dumps(output, indent=4 ))" } ]
1
jyh947/Wiki-Bot
https://github.com/jyh947/Wiki-Bot
7c3e9400b72d747d3a4d9d17f22f9091a36e3d23
438577f3fb91745eb33e66f47273a90960b8e96b
450852252f23574f9c686ca2a31316479bf85189
refs/heads/master
2017-12-04T05:07:45.111904
2015-05-28T14:11:28
2015-05-28T14:11:28
31,521,868
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7981366515159607, "alphanum_fraction": 0.7981366515159607, "avg_line_length": 106, "blob_id": "2ccbfb69032fcc9d5cad8908069108f3ae5b0cca", "content_id": "f2d1e5db059172b3657c92d99eac524ff53c528b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 322, "license_type": "no_license", "max_line_length": 278, "num_lines": 3, "path": "/README.md", "repo_name": "jyh947/Wiki-Bot", "src_encoding": "UTF-8", "text": "# UnmobilizeLinksReddit\n#### Introduction\nThis robot is a derivative of the Reddit Notifier robot that I also wrote. The gui is basically a stripped down version of the other robot. This robot looks for wikipedia links that are posted with the mobile domain and replies to the Reddit submission with a non-mobile link. \n" }, { "alpha_fraction": 0.5661796927452087, "alphanum_fraction": 0.5720233917236328, "avg_line_length": 43.16128921508789, "blob_id": "1c345c9ba0793ff4ad289f979b917068f5bc6ff5", "content_id": "eda431cc19e87ade69fe54efb7ce791599c20139", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13690, "license_type": "no_license", "max_line_length": 186, "num_lines": 310, "path": "/wiki_bot.py", "repo_name": "jyh947/Wiki-Bot", "src_encoding": "UTF-8", "text": "import praw\nimport time\nimport os.path\nimport threading\nimport ConfigParser\nimport tkMessageBox\nimport Tkinter as tk\n\nclass ParseInput(object):\n def Reddit(self, gui):\n gui.REDDIT_USERNAME = gui.REDDIT_USERNAME_entry.get()\n gui.REDDIT_PASSWORD = gui.REDDIT_PASSWORD_entry.get()\n\n gui.REDDIT_USERNAME = check_reddit_username(gui.REDDIT_USERNAME)\n gui.REDDIT_USERNAME_entry.delete(0, 'end')\n if gui.REDDIT_USERNAME == None:\n tkMessageBox.showerror(title = 'Error!', message = 'Bad Reddit username!', parent = gui.gui)\n return\n gui.REDDIT_USERNAME_entry.insert(0, gui.REDDIT_USERNAME)\n if len(gui.REDDIT_PASSWORD) == 0:\n tkMessageBox.showerror(title = 'Error!', message = 'Please enter a Reddit password!', parent = gui.gui)\n return\n\n self.reddit = praw.Reddit(user_agent = 'wiki unmobilizer by /u/PC4U v0.1')\n\n try:\n user = self.reddit.get_redditor(gui.REDDIT_USERNAME)\n except Exception as detail:\n tkMessageBox.showerror(title = 'Error!', message = 'Message from Reddit:\\n' + str(detail), parent = gui.gui)\n print detail\n print 'Incorrect password! Please try again!'\n gui.REDDIT_LOGIN_var.set('Not Logged In!')\n gui.START_button['state'] = 'disabled'\n return\n if user.link_karma < 2:\n tkMessageBox.showerror(title = 'Error!', message = 'You must have at least 1 link karma!', parent = gui.gui)\n return\n # authentication\n try:\n self.reddit.login(gui.REDDIT_USERNAME, gui.REDDIT_PASSWORD)\n print 'Correct password!'\n gui.REDDIT_LOGIN_var.set('Logged Into Reddit!')\n gui.START_button['state'] = 'normal'\n except Exception as detail:\n tkMessageBox.showerror(title = 'Error!', message = 'Message from Reddit:\\n' + str(detail), parent = gui.gui)\n print detail\n print 'Incorrect password! Please try again!'\n gui.REDDIT_LOGIN_var.set('Not Logged In!')\n gui.START_button['state'] = 'disabled'\n return\n gui.post_ids = gui.post_ids.strip('[')\n gui.post_ids = gui.post_ids.strip(']')\n gui.post_ids = gui.post_ids.split(', ')\n gui.post_ids = [post.strip(\"'\") for post in gui.post_ids]\n\n def Save(self, gui, startup):\n if startup:\n self.all_posts = []\n self.posts_replied_to = []\n if not os.path.exists('config_wiki.cfg') and startup:\n return\n gui.REDDIT_USERNAME = gui.REDDIT_USERNAME_entry.get()\n\n # Do error checking here\n gui.REDDIT_USERNAME = check_reddit_username(gui.REDDIT_USERNAME)\n gui.REDDIT_USERNAME_entry.delete(0, 'end')\n if gui.REDDIT_USERNAME == None:\n tkMessageBox.showerror(title = 'Error!', message = 'Bad Reddit username!', parent = gui.gui)\n else:\n gui.REDDIT_USERNAME_entry.insert(0, gui.REDDIT_USERNAME)\n\n cfgfile = open('config_wiki.cfg','w')\n Config = ConfigParser.ConfigParser()\n Config.add_section('Main')\n Config.set('Main', 'REDDIT_USERNAME', gui.REDDIT_USERNAME)\n Config.set('Main', 'post_ids', gui.post_ids)\n Config.write(cfgfile)\n cfgfile.close()\n gui.TEXT_var.set('Saved settings to \"config_wiki.cfg\"\\n\\n')\n\n thread = threading.Thread(target = lambda: set_output(gui))\n thread.start()\n print 'Saving worked!'\n\n def Start(self, gui):\n # Disable buttons here\n gui.REDDIT_USERNAME_entry['state'] = 'disabled'\n gui.REDDIT_PASSWORD_entry['state'] = 'disabled'\n gui.REDDIT_LOGIN_button['state'] = 'disabled'\n gui.SAVE_button['state'] = 'disabled'\n\n if not gui.START_button_var.get():\n set_to_normal(gui)\n return\n if gui.REDDIT_LOGIN_var.get() != 'Logged Into Reddit!':\n set_to_normal(gui)\n tkMessageBox.showerror(title = 'Error!', message = 'Please login to both Gmail and Reddit!', parent = gui.gui)\n return\n\n self.subreddit = self.reddit.get_subreddit('all')\n def looping(self, gui):\n sleep_time = 30\n stale_post_time = 600\n while gui.START_button_var.get():\n gui.TEXT_var.set('\\n\\n')\n # get current time\n current_time = time.time()\n posts_this_round = []\n # get 10 new posts and place into all_posts\n posts_to_grab = 30\n max_posts = 240\n prev_posts = 6000\n new_posts = 6000\n while prev_posts == new_posts:\n prev_posts = posts_to_grab\n new_posts = 0\n posts_this_round = []\n for submission in self.subreddit.get_new(limit = posts_to_grab):\n if submission not in self.all_posts and submission not in posts_this_round and (current_time - submission.created_utc) < stale_post_time:\n posts_this_round.append(submission)\n new_posts += 1\n if posts_to_grab >= max_posts:\n break\n posts_to_grab *= 2\n message = ''\n num_messages = 0\n for post in posts_this_round:\n if post.id in gui.post_ids and '.m.wikipedia.org' in post.domain:\n self.posts_replied_to.append(post)\n elif post not in self.posts_replied_to and '.m.wikipedia.org' in post.domain:\n num_messages += 1\n self.posts_replied_to.append(post)\n domain = post.url.replace('.m.wikipedia.org', '.wikipedia.org')\n message = 'Here is a non-mobile link:\\n\\n' + domain\n message += '\\n\\n^^Message ^^me ^^about ^^this ^^bot: ^^/u/PC4U'\n try:\n post.add_comment(message)\n except Exception as detail:\n print 'Error posting', message\n print message\n # push new posts into queue\n current_text = 'Found ' + str(num_messages) + ' new posts that the robot will reply to\\n\\n'\n print 'Found', str(num_messages), 'new posts that the robot will reply to'\n gui.TEXT_var.set(current_text)\n for post in posts_this_round:\n self.all_posts.append(post)\n\n # clear posts older than 'stale_post_time' seconds old\n print 'Clean-up time'\n cleanup(self.all_posts, current_time, stale_post_time)\n cleanup(self.posts_replied_to, current_time, stale_post_time)\n gui.post_ids = []\n #for post in self.posts_replied_to:\n for post in self.posts_replied_to:\n gui.post_ids.append(str(post.id))\n current_text_backup = current_text\n #let script sleep for 'sleep_time' seconds\n for integer in range(sleep_time):\n current_text = current_text.strip('\\n')\n print 'Waiting', sleep_time - integer, 'seconds'\n current_text += '\\nWaiting ' + str(sleep_time - integer) + ' seconds\\n'\n gui.TEXT_var.set(current_text)\n current_text = current_text_backup\n time.sleep(1)\n if not gui.START_button_var.get():\n set_to_normal(gui)\n print 'Exiting thread'\n gui.TEXT_var.set('Automation Stopped!\\n\\n')\n thread = threading.Thread(target = lambda: set_output(gui))\n thread.start()\n gui.one_loop = False\n return\n\n set_to_normal(gui)\n print 'Exiting thread'\n gui.TEXT_var.set('Automation Stopped!\\n\\n')\n thread = threading.Thread(target = lambda: set_output(gui))\n thread.start()\n gui.one_loop = False\n\n if not gui.one_loop:\n gui.one_loop = True\n thread = threading.Thread(target = lambda: looping(self, gui))\n thread.start()\n else:\n print 'One thread is already active'\n\nclass GUI(object):\n def init(self):\n self.parse_object = ParseInput()\n\n self.one_loop = False\n self.gui = tk.Tk()\n self.gui.title('Unmobilize Links by /u/PC4U')\n self.gui.resizable(False, False)\n self.gui.protocol(\"WM_DELETE_WINDOW\", lambda: on_closing(self))\n\n self.mainframe = tk.Frame(self.gui)\n self.mainframe.grid(column = 0, row = 0, padx = 10, pady = 10)\n self.mainframe.columnconfigure(0, weight = 1)\n self.mainframe.rowconfigure(0, weight = 1)\n\n self.post_ids = []\n self.title = tk.StringVar()\n self.REDDIT_USERNAME = tk.StringVar()\n self.REDDIT_USERNAME_var = tk.StringVar()\n self.REDDIT_PASSWORD = tk.StringVar()\n self.REDDIT_PASSWORD_var = tk.StringVar()\n self.REDDIT_LOGIN_var = tk.StringVar()\n self.OUTPUT_var = tk.StringVar()\n self.TEXT_var = tk.StringVar()\n self.START_button_var = tk.IntVar()\n\n self.title.set('This is a robot will automatically scan /r/all\\n' +\n 'and replace mobile links with non mobile ones\\n' +\n 'in the comment section of the original post\\n')\n self.title_label = tk.Label(self.mainframe, textvariable = self.title)\n self.title_label.grid(column = 1, row = 1, columnspan = 2)\n\n self.REDDIT_USERNAME_var.set('Reddit Username: ')\n self.REDDIT_USERNAME_label = tk.Label(self.mainframe, textvariable = self.REDDIT_USERNAME_var)\n self.REDDIT_USERNAME_label.grid(column = 1, row = 2, sticky = 'W')\n self.REDDIT_USERNAME_entry = tk.Entry(self.mainframe, width = 30, textvariable = self.REDDIT_USERNAME)\n self.REDDIT_USERNAME_entry.grid(column = 2, row = 2, sticky = 'W')\n\n self.REDDIT_PASSWORD_var.set('Reddit Password: ')\n self.REDDIT_PASSWORD_label = tk.Label(self.mainframe, textvariable = self.REDDIT_PASSWORD_var)\n self.REDDIT_PASSWORD_label.grid(column = 1, row = 3, sticky = 'W')\n self.REDDIT_PASSWORD_entry = tk.Entry(self.mainframe, width = 30, textvariable = self.REDDIT_PASSWORD, show = '*')\n self.REDDIT_PASSWORD_entry.grid(column = 2, row = 3, sticky = 'W')\n\n self.REDDIT_LOGIN_var.set('Not Logged In!')\n self.REDDIT_LOGIN_label = tk.Label(self.mainframe, textvariable = self.REDDIT_LOGIN_var)\n self.REDDIT_LOGIN_label.grid(column = 2, row = 4, sticky = 'W')\n self.REDDIT_LOGIN_button = tk.Button(self.mainframe, text='Log Into Reddit', command = lambda: self.parse_object.Reddit(self))\n self.REDDIT_LOGIN_button.grid(column = 1, row = 4, sticky = 'W')\n\n self.SAVE_button = tk.Button(self.mainframe, text='Save data to config_wiki.cfg', command = lambda: self.parse_object.Save(self, False))\n self.SAVE_button.grid(column = 1, row = 5, sticky = 'W')\n\n self.START_button = tk.Checkbutton(self.mainframe, text='Start Automation', command = lambda: self.parse_object.Start(self), variable = self.START_button_var, state = 'disabled')\n self.START_button.grid(column = 2, row = 5, sticky = 'W')\n\n self.OUTPUT_var.set('Output:')\n self.OUTPUT = tk.Label(self.mainframe, textvariable = self.OUTPUT_var)\n self.OUTPUT.grid(column = 1, row = 6, columnspan = 2, sticky = 'W')\n\n self.TEXT_var.set('\\n\\n')\n self.TEXT = tk.Label(self.mainframe, textvariable = self.TEXT_var)\n self.TEXT.grid(column = 1, row = 7, columnspan = 2, sticky = 'W')\n\n get_config_data(self)\n self.parse_object.Save(self, True)\n\ndef on_closing(gui):\n gui.START_button.deselect()\n gui.parse_object.Save(gui, False)\n gui.gui.quit()\n\ndef cleanup(list, current_time, stale_post_time):\n for post in list:\n if (current_time - post.created_utc) > stale_post_time:\n list.remove(post)\n\ndef get_config_data(gui):\n if not os.path.exists('config_wiki.cfg'):\n return\n \n Config = ConfigParser.ConfigParser()\n Config.read('config_wiki.cfg')\n\n try:\n gui.REDDIT_USERNAME = Config.get('Main', 'REDDIT_USERNAME')\n gui.REDDIT_USERNAME = check_reddit_username(gui.REDDIT_USERNAME)\n gui.REDDIT_USERNAME_entry.delete(0, 'end')\n if gui.REDDIT_USERNAME == None:\n tkMessageBox.showerror(title = 'Error!', message = 'Bad Reddit username!', parent = gui.gui)\n else:\n gui.REDDIT_USERNAME_entry.insert(0, gui.REDDIT_USERNAME)\n except Exception as detail:\n print 'Missing REDDIT_USERNAME'\n \n try:\n gui.post_ids = Config.get('Main', 'post_ids')\n except Exception as detail:\n print 'Missing post_ids'\n\ndef set_output(gui):\n time.sleep(3)\n gui.TEXT_var.set('\\n\\n')\n\ndef set_to_normal(gui):\n gui.START_button.deselect()\n gui.REDDIT_USERNAME_entry['state'] = 'normal'\n gui.REDDIT_PASSWORD_entry['state'] = 'normal'\n gui.REDDIT_LOGIN_button['state'] = 'normal'\n gui.SAVE_button['state'] = 'normal'\n\ndef check_reddit_username(string):\n string = string.replace(' ', '')\n for char in string:\n if not char.isalnum() and char != '_' and char != '-':\n print 'bad', char\n return None\n return string\n\nif __name__ == '__main__':\n gui = GUI()\n gui.init()\n gui.gui.mainloop()\n" } ]
2
vas-ya-pupkin/connect_game
https://github.com/vas-ya-pupkin/connect_game
016580c04ffc07c292fd925a9fa74ac85222dde8
7d2c0c7178f4ae1bd23d6035843047fcab2332a6
d77e7e01055655078471a87df9f3d2c81cd9d0e3
refs/heads/master
2022-07-11T06:17:29.833179
2020-02-07T06:06:40
2020-02-07T06:06:40
237,966,221
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4640151560306549, "alphanum_fraction": 0.467803031206131, "avg_line_length": 25.399999618530273, "blob_id": "5ef32a51795c5bb254feddff2657b71b50e8d8b9", "content_id": "319e8419c25872976ec28638d5602c79279332b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 560, "license_type": "no_license", "max_line_length": 82, "num_lines": 20, "path": "/main.py", "repo_name": "vas-ya-pupkin/connect_game", "src_encoding": "UTF-8", "text": "from game import Game\n\nif __name__ == '__main__':\n game = Game(6, 7)\n game.draw()\n\n while not game.is_finished:\n try:\n col, row = input(f'Ход игрока {game.player}. \\n'\n f'Координаты (строка столбец) > ').strip().split(' ')\n col = int(col)\n row = int(row)\n except ValueError:\n continue\n\n try:\n game.new_turn(col, row)\n game.draw()\n except (ValueError, RuntimeError) as e:\n print(str(e))\n" }, { "alpha_fraction": 0.5238796472549438, "alphanum_fraction": 0.527877151966095, "avg_line_length": 27.12425994873047, "blob_id": "fc6fb8112efd9905ccaf9bd1db5006c0f270e972", "content_id": "d0034e5bb8b185df9d2fe713eb6635af95c439ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5350, "license_type": "no_license", "max_line_length": 109, "num_lines": 169, "path": "/game.py", "repo_name": "vas-ya-pupkin/connect_game", "src_encoding": "UTF-8", "text": "import numpy as np\nimport itertools\nfrom typing import Iterator\n\nnp.set_printoptions(threshold=np.inf)\n\n\nclass Game:\n EMPTY = 'X'\n PLAYERS = {\n 1: '●',\n 2: '○',\n }\n WINNING_LENGTH = 4 # длина ряда для победы\n\n def __init__(self, rows: int, columns: int):\n self.rows = rows\n self.columns = columns\n self.field = np.chararray((rows, columns), unicode=True)\n self.field.fill(self.EMPTY)\n\n self.turn_generator = self.turn()\n self.current_player = self._change_turn()\n\n self.finished = False\n\n def turn(self) -> Iterator[int]:\n \"\"\"\n Возвращает номер игрока, чья очередь ходить\n :return:\n \"\"\"\n while True:\n for player in self.PLAYERS.keys():\n yield player\n\n def draw(self) -> None:\n \"\"\"\n Вывод игрового поля\n :return:\n \"\"\"\n drawable = self._prepare_field_for_drawing()\n print(drawable)\n print()\n\n def _prepare_field_for_drawing(self) -> str:\n return '\\n'.join(\n [\n ' '.join(row) for\n row in self.field\n ]\n )\n\n def new_turn(self, row: int, column: int) -> bool:\n \"\"\"\n Осуществление хода\n :param row:\n :param column:\n :return:\n \"\"\"\n if self.finished:\n raise RuntimeError('Игра окончена')\n\n row, column = self._user_input_to_machine(row, column)\n if any([row < 0, column < 0, row > self.rows, column > self.columns]):\n raise ValueError(f'Допустимые значения: 1-{self.rows}, 1-{self.columns}')\n\n real_row = self._gravity(row, column)\n if real_row == -1:\n raise ValueError('Этот столбец полностью занят')\n\n self._set_new_dot(real_row, column)\n\n if self._is_current_player_a_winner():\n self.finished = True\n self._congrats()\n\n self.current_player = self._change_turn()\n return True\n\n def _congrats(self) -> None:\n print(f\"Игрок {self.current_player} победил!\")\n\n def _gravity(self, row: int, column: int):\n \"\"\"\n Возвращает номер строки, до которой падает шар\n :param row:\n :param column:\n :return:\n \"\"\"\n real_row = -1\n for i in range(row - 1, self.rows)[::-1]:\n if self.field[i][column] == self.EMPTY:\n real_row = i\n break\n return real_row\n\n def _set_new_dot(self, row: int, column: int) -> None:\n \"\"\"\n Вставка символа игрока в поле\n :param row:\n :param column:\n :return:\n \"\"\"\n self.field[row][column] = self.PLAYERS[self.current_player]\n\n def _change_turn(self) -> int:\n \"\"\"\n Изменение текущего игрока\n :return:\n \"\"\"\n return next(self.turn_generator)\n\n def _is_current_player_a_winner(self) -> bool:\n \"\"\"\n Победил ли текущий игрок\n :return:\n \"\"\"\n for row in self.field.tolist() + np.rot90(self.field).tolist(): # горизонталь/вертикаль\n if self._is_winning_seq_present(row):\n return True\n\n lists = [self.field, np.rot90(self.field)] # для одинаковой проверки диагоналей в обоих направлениях\n for i in lists:\n for no, row in enumerate(i):\n diags = [np.diag(i, k=no), np.diag(i, k=-no)] # одинаковое смещение вниз и вверх\n\n if all([\n len(d) < self.WINNING_LENGTH for d in diags\n ]): # (проверяем длину обеих на случай несимметричности поля)\n continue\n\n if any([\n self._is_winning_seq_present(x) for x in diags\n ]):\n return True\n return False\n\n def _is_winning_seq_present(self, row):\n \"\"\"\n Есть ли в списке последовательность достаточной для победы длины\n :return:\n \"\"\"\n lengths = [\n len(list(x[1])) for x in\n itertools.groupby(row) if\n x[0] == self.PLAYERS[self.current_player]\n ] # длина всех последовательностей символов текущего игрока\n if (lengths and\n max(lengths) >= self.WINNING_LENGTH):\n return True\n return False\n\n @property\n def player(self):\n return self.current_player\n\n @property\n def is_finished(self):\n return self.finished\n\n @staticmethod\n def _user_input_to_machine(row: int, column: int):\n \"\"\"\n Преобразование ввода пользователя, который считает клетки с единицы, в индексы массива (с нуля)\n :param row:\n :param column:\n :return:\n \"\"\"\n return row - 1, column - 1\n" } ]
2
JianyuanLin/DivideWord
https://github.com/JianyuanLin/DivideWord
c474c1b9af006b91d741f0df355a5cd6813a1e3f
46335771ecd99d4c5dadba131d3718907a7f1aff
1c6eb3980388568900791d544216aa9c21806959
refs/heads/master
2020-05-23T11:24:56.735582
2019-05-15T02:47:42
2019-05-15T02:47:42
186,736,168
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.423785924911499, "alphanum_fraction": 0.4386521279811859, "avg_line_length": 36.80769348144531, "blob_id": "4d4c7b648863fa42f79c267b3939140a43f8e1f5", "content_id": "b2fb76b4837ee5b678983f68d9762687ec97a56c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5070, "license_type": "no_license", "max_line_length": 133, "num_lines": 130, "path": "/divide_word.py", "repo_name": "JianyuanLin/DivideWord", "src_encoding": "UTF-8", "text": "#encoding:utf-8\r\nimport math\r\nimport re\r\n\r\n\r\ndef DivideWord(text_path, result_path, vocab_path, word_size=5, freq_threshold=0.0001, co_threshold=0.99999, free_threshold=0.99999):\r\n if word_size <= 1:\r\n print(\"word size can't be 1 or less!\")\r\n exit()\r\n pattern = r',|\\.|/|;|\\'|`|\\[|\\]|<|>|\\?|:|\"|\\{|\\}|\\~|!|@|#|\\$|%|\\^|&|\\(|\\)|-|=|\\_|\\+|,|。|、|;|‘|’|【|】|·|!| |…|(|)'\r\n with open(text_path, encoding=\"utf8\") as f:\r\n lines = f.readlines()\r\n sentences = []\r\n for line in lines:\r\n ll = line.strip()\r\n sentences += re.split(pattern, ll)\r\n with open(\"./temp.txt\", \"w\", encoding=\"utf8\") as f:\r\n for s in sentences:\r\n f.write(s+\"\\n\")\r\n with open(\"./temp.txt\", encoding=\"utf8\") as f:\r\n lines = f.readlines()\r\n word_freq = {}\r\n word_left = {}\r\n word_right = {}\r\n word_num = 0\r\n # count the numbers of every word\r\n all_num = len(lines)\r\n for length in range(1, word_size + 1):\r\n for _, line in enumerate(lines):\r\n print(\"Get the word whose length is \"+str(length)+\"...\"+str(_/all_num*100)+\"%\")\r\n string = line.strip()\r\n string_length = len(string)\r\n for i in range(string_length - length + 1):\r\n word = string[i:i + length]\r\n word_num += 1\r\n if word not in word_freq.keys():\r\n word_freq[word] = 1\r\n word_left[word] = {}\r\n word_right[word] = {}\r\n if i != 0:\r\n word_left[word][string[i - 1]] = 1\r\n if i + length < string_length:\r\n word_right[word][string[i + length]] = 1\r\n else:\r\n word_freq[word] += 1\r\n if i != 0:\r\n lw = string[i - 1]\r\n if lw not in word_left[word]:\r\n word_left[word][lw] = 1\r\n else:\r\n word_left[word][lw] += 1\r\n if i + length < string_length:\r\n rw = string[i + length]\r\n if rw not in word_right[word]:\r\n word_right[word][rw] = 1\r\n else:\r\n word_right[word][rw] += 1\r\n # calculate the freq of every word and generate word_dict1\r\n word_dict1 = []\r\n for word in word_freq.keys():\r\n word_freq[word] = word_freq[word] / word_num\r\n if word_freq[word] > freq_threshold:\r\n word_dict1.append(word)\r\n # calculate the co of every word in word_dict1 and generate word_dict2\r\n word_dict2 = []\r\n for word in word_dict1:\r\n length = len(word)\r\n if length > 1:\r\n co = min(\r\n [word_freq[word] / word_freq[word[:index]] / word_freq[word[index:]]\r\n for index in range(1, length)]\r\n )\r\n if co > co_threshold:\r\n word_dict2.append(word)\r\n else:\r\n word_dict2.append(word)\r\n # calculate the free of every word in word_dict2 and generate word_dict3\r\n word_dict3 = []\r\n for word in word_dict2:\r\n left_num = 0\r\n left_h = 0\r\n for lw in word_left[word]:\r\n left_num += word_left[word][lw]\r\n for lw in word_left[word]:\r\n p = word_left[word][lw] / left_num\r\n left_h -= p * math.log(p)\r\n right_num = 0\r\n right_h = 0\r\n for rw in word_right[word]:\r\n right_num += word_right[word][rw]\r\n for rw in word_right[word]:\r\n p = word_right[word][rw] / right_num\r\n right_h -= p * math.log(p)\r\n free = min(left_h, right_h)\r\n if free > free_threshold:\r\n word_dict3.append(word)\r\n result_dict = {}\r\n for word in word_dict3:\r\n result_dict[word] = word_freq[word]\r\n with open(vocab_path, \"w\", encoding=\"utf8\") as f:\r\n for word in sorted(result_dict, key=result_dict.__getitem__, reverse=True):\r\n if len(word) > 1:\r\n f.write(word+\"\\n\")\r\n with open(result_path, \"w\", encoding=\"utf8\") as f:\r\n index = 0\r\n for line in lines:\r\n index += 1\r\n words = []\r\n string = line.strip()\r\n length = len(string)\r\n start = 0\r\n end = word_size\r\n while True:\r\n if start >= length:\r\n break\r\n if end > length:\r\n end = length\r\n if string[start:end] in word_dict3:\r\n words.append(string[start:end])\r\n start = end\r\n end = start + word_size\r\n else:\r\n end -= 1\r\n if end - start <= 1:\r\n words.append(string[start])\r\n start += 1\r\n end = start + word_size\r\n for word in words:\r\n f.write(word+\" \")\r\n f.write(\"\\n\")\r\n" } ]
1
grantsrb/simple_autoencoder
https://github.com/grantsrb/simple_autoencoder
76cc48aee1d65be24e3b14c8540d6e7a62bd7110
320f98d1d59afa1faa09febe6feb6d7d3c41af2a
4447a1ba6b27b39a8e7eb73a18f055f52b054804
refs/heads/master
2020-03-14T20:18:30.735776
2018-05-02T00:23:49
2018-05-02T00:23:49
131,774,579
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7286995649337769, "alphanum_fraction": 0.7690582871437073, "avg_line_length": 32.56989288330078, "blob_id": "684a8cafff9606293164ce71a87d8e77979b1b0f", "content_id": "5a4c50b4f0846e808ea2827acc76eab84366519f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3122, "license_type": "no_license", "max_line_length": 376, "num_lines": 93, "path": "/readme.md", "repo_name": "grantsrb/simple_autoencoder", "src_encoding": "UTF-8", "text": "# Simple Autoencoder\n\n## Description\nThe autoencoder first reduces images from Cifar-10 to a low dimensional vector of random variables using a conv net. \n\nMore specifically, the autoencoder reduces the image into two vectors. One is treated as a vector of means for a normal distribution. The other is treated as a corresponding vector of standard deviations. These two vectors are used to construct a z vector whose entries are drawn from the normal distributions created by the corresponding mean and standard deviation vectors. \n\nThe z vector is used to predict the class of the image and is then fed into a convolution transpose net to reconstruct the original image.\n\nLosses from both the prediction error and the reconstruction error are used in backprop.\n\nIdeally, the autoencoder can be trained to create a semantically rich z vector that can be used for activities like Reinforcement Learning or machine memory. These applications are not included in this project.\n\n## Experimental Setup\n\n#### Encoder Architecture\n\n- 3x3 Convolution, 16 filters, stride 1, padding 1\n- ReLU\n- 2D Batch Normalization\n- 3x3 Convolution, 32 filters, stride 2, padding 1\n- ReLU\n- 2D Batch Normalization\n- 3x3 Convolution, 64 filters, stride 2, padding 1\n- ReLU\n- 2D Batch Normalization\n- 3x3 Convolution, 64 filters, stride 2, padding 1\n- ReLU\n- 2D Batch Normalization\n- 1024 -> 256 Fully Connected (means); 1024 -> 256 Fully Connected (stds)\n- Draw from Normal Distribution, multiply by stds and add means\n\n#### Classifier Architecture\n\n- 256 -> 200 Fully Connected\n- ReLU\n- 1d Batch Normalization\n- 200 -> 10 Fully Connected\n\n#### Reconstruction Architecture\n\n- 256 -> 1024 Fully Connected\n- ReLU\n- 1d Batch Normalization\n- 5x5 Convolution Transpose, 64 filters, stride 1, padding 0\n- ReLU\n- 2D Batch Normalization\n- 5x5 Convolution Transpose, 64 filters, stride 1, padding 0\n- ReLU\n- 2D Batch Normalization\n- 4x4 Convolution Transpose, 32 filters, stride 2, padding 0\n- ReLU\n- 2D Batch Normalization\n- 5x5 Convolution Transpose, 16 filters, stride 1, padding 0\n- ReLU\n- 2D Batch Normalization\n- 3x3 Convolution Transpose, 3 filters, stride 1, padding 0\n\nThe images used for this autoencoder were the Cifar-10 training dataset. The images were not preprocessed in any way before being fed to the autoencoder. 45000 were used as a training set, 5000 were kept as a validation set.\n\n## Results\nThe final training and validation accuracies varied depending on the portion of loss contributed by the classification error. Classification accuracy was improved by adding a simple normalizing preprocessing step to the data. This, however, reduced the quality of the reconstructed images. \n\nHere are some examples of the reconstructed images.\n----\nReconstruction:\n![Image 1a](./imgs/remakes2.png)\n\nOriginal:\n![Image 1b](./imgs/reals2.png)\n\n----\nReconstruction:\n![Image 2a](./imgs/remakes4.png)\n\nOriginal:\n![Image 2b](./imgs/reals4.png)\n\n----\nReconstruction:\n![Image 3a](./imgs/remakes7.png)\n\nOriginal:\n![Image 3b](./imgs/reals7.png)\n\n----\nReconstruction:\n![Image 4a](./imgs/remakes12.png)\n\nOriginal:\n![Image 4b](./imgs/reals12.png)\n\n----\n" }, { "alpha_fraction": 0.603943943977356, "alphanum_fraction": 0.6194249987602234, "avg_line_length": 40.99224853515625, "blob_id": "a9f5e80c9d7f1f42fb7c04dcaa5614e15ca1277e", "content_id": "1ce949efc4720a8fd090457f730d3995ddeef872", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5426, "license_type": "no_license", "max_line_length": 130, "num_lines": 129, "path": "/encoder.py", "repo_name": "grantsrb/simple_autoencoder", "src_encoding": "UTF-8", "text": "import torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport numpy as np\n\nclass Encoder(nn.Module):\n\n def cuda_if(self, tobj):\n if torch.cuda.is_available():\n tobj = tobj.cuda()\n return tobj\n\n def __init__(self, obs_size, n_classes, emb_size=256, bnorm=True):\n \"\"\"\n obs_size - the size of the input data. Shape = (..., C, H, W)\n \"\"\"\n super(Encoder, self).__init__()\n self.obs_size = obs_size\n self.emb_size = emb_size\n self.bnorm = bnorm\n\n # Encoder\n self.convs = nn.ModuleList([])\n shape = [*self.obs_size[-3:]]\n\n ksize=3; padding=1; stride=1; out_depth = 16\n self.convs.append(self.conv_block(obs_size[-3], out_depth, ksize=ksize, padding=padding, stride=stride, bnorm=self.bnorm))\n shape = self.get_new_shape(shape, out_depth, ksize=ksize, stride=stride, padding=padding)\n\n ksize=3; padding=0; stride=2; in_depth=out_depth\n out_depth = 32\n self.convs.append(self.conv_block(in_depth, out_depth, ksize=ksize, padding=padding, stride=stride, bnorm=self.bnorm))\n shape = self.get_new_shape(shape, out_depth, ksize=ksize, stride=stride, padding=padding)\n\n ksize=3; padding=1; stride=2; in_depth = out_depth\n out_depth = 64\n self.convs.append(self.conv_block(in_depth, out_depth, ksize=ksize, padding=padding, stride=stride, bnorm=self.bnorm))\n shape = self.get_new_shape(shape, out_depth, ksize=ksize, stride=stride, padding=padding)\n\n ksize=3; padding=1; stride=2; in_depth = out_depth\n out_depth = 64\n self.convs.append(self.conv_block(in_depth, out_depth, ksize=ksize, padding=padding, stride=stride, bnorm=self.bnorm))\n shape = self.get_new_shape(shape, out_depth, ksize=ksize, stride=stride, padding=padding)\n\n self.features = nn.Sequential(*self.convs)\n self.feat_shape = shape\n self.flat_size = int(np.prod(shape))\n self.mu = nn.Linear(self.flat_size, emb_size)\n self.sigma = nn.Linear(self.flat_size, emb_size)\n\n # Reconstructor\n self.deconvs = nn.ModuleList([])\n\n ksize=5; padding=0; stride=1; in_depth = out_depth\n out_depth = 64\n self.deconvs.append(self.deconv_block(in_depth, out_depth, ksize=ksize, padding=padding, stride=stride, bnorm=self.bnorm))\n\n ksize=5; padding=0; stride=1; in_depth = out_depth\n out_depth = 64\n self.deconvs.append(self.deconv_block(in_depth, out_depth, ksize=ksize, padding=padding, stride=stride, bnorm=self.bnorm))\n\n ksize=4; padding=0; stride=2; in_depth = out_depth\n out_depth = 32\n self.deconvs.append(self.deconv_block(in_depth, out_depth, ksize=ksize, padding=padding, stride=stride, bnorm=self.bnorm))\n\n ksize=5; padding=0; stride=1; in_depth = out_depth\n out_depth = 16\n self.deconvs.append(self.deconv_block(in_depth, out_depth, ksize=ksize, padding=padding, stride=stride, bnorm=self.bnorm))\n\n ksize=3; padding=0; stride=1; in_depth = out_depth\n out_depth = obs_size[-3]\n self.deconvs.append(self.deconv_block(in_depth, out_depth, ksize=ksize, padding=padding, stride=stride, bnorm=False))\n\n self.rwd_flat = nn.Sequential(nn.Linear(emb_size, self.flat_size),nn.ReLU(), nn.BatchNorm1d(1024))\n self.rwd_features = nn.Sequential(*self.deconvs)\n\n # Classifier\n block = []\n block.append(nn.Linear(self.emb_size, 200))\n block.append(nn.ReLU())\n block.append(nn.BatchNorm1d(200))\n block.append(nn.Linear(200,int(n_classes)))\n self.classifier = nn.Sequential(*block)\n\n def get_new_shape(self, old_shape, depth, ksize=3, stride=1, padding=1):\n new_shape = [depth]\n for i in range(len(old_shape[1:])):\n new_shape.append((old_shape[i+1] - ksize + 2*padding)//stride + 1)\n return new_shape\n\n def forward(self, x):\n fx = self.features(x)\n fx = fx.view(-1, self.flat_size)\n mu = self.mu(fx)\n sigma = self.sigma(fx)\n z = mu + sigma*Variable(self.cuda_if(torch.normal(means=torch.zeros(mu.shape), std=1)))\n fx = self.rwd_flat(z)\n fx = fx.view(-1, *self.feat_shape)\n remake = self.rwd_features(fx)\n return z, remake\n\n def classify(self, z):\n return self.classifier(z)\n\n def conv_block(self,in_depth,out_depth,ksize=3,stride=1,padding=1,activation='relu',bnorm=False):\n block = []\n block.append(nn.Conv2d(in_depth, out_depth, ksize, stride=stride, padding=padding))\n if activation is None:\n pass\n elif activation.lower() == 'relu':\n block.append(nn.ReLU())\n elif activation.lower() == 'tanh':\n block.append(nn.Tanh())\n if bnorm:\n block.append(nn.BatchNorm2d(out_depth))\n return nn.Sequential(*block)\n\n def deconv_block(self,in_depth,out_depth,ksize=3,stride=1,padding=1,activation='relu',bnorm=False):\n block = []\n block.append(nn.ConvTranspose2d(in_depth, out_depth, ksize, stride=stride, padding=padding))\n if activation is None:\n pass\n elif activation.lower() == 'relu':\n block.append(nn.ReLU())\n elif activation.lower() == 'tanh':\n block.append(nn.Tanh())\n if bnorm:\n block.append(nn.BatchNorm2d(out_depth))\n return nn.Sequential(*block)\n \n" }, { "alpha_fraction": 0.5412728190422058, "alphanum_fraction": 0.5482041835784912, "avg_line_length": 33.4782600402832, "blob_id": "4169355e70b5f82cf7756f197ed575eb54dbbd2e", "content_id": "b36ed54b469c2c380d602ed9550b61d374316ad8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1591, "license_type": "no_license", "max_line_length": 80, "num_lines": 46, "path": "/trainer.py", "repo_name": "grantsrb/simple_autoencoder", "src_encoding": "UTF-8", "text": "import torch\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport numpy as np\n\nclass Trainer():\n\n def cuda_if(self, tobj):\n if torch.cuda.is_available():\n tobj = tobj.cuda()\n return tobj\n\n def __init__(self, net, lr=1e-3, pred_coef=.1):\n self.net = net\n self.pred_coef = pred_coef\n self.optim = optim.Adam(self.net.parameters(), lr=lr)\n\n def batch_loss(self, x, y=None):\n loss = 0\n zs, remakes = self.net.forward(x)\n acc = None\n if y is not None:\n logits = self.net.classify(zs)\n loss = self.pred_coef * F.cross_entropy(logits, y)\n maxes, max_idxs = torch.max(logits.data, dim=-1)\n acc = torch.eq(max_idxs, y.data).float().mean()\n return loss + F.mse_loss(remakes, x), acc\n\n def train(self, X, y=None, batch_size=128):\n idxs = self.cuda_if(torch.randperm(len(X)).long())\n losses = []\n accuracies = []\n for i in range(0, len(X), batch_size):\n self.optim.zero_grad()\n batch_idxs = idxs[i:i+batch_size]\n batch_x = X[batch_idxs]\n if y is not None: batch_y = y[batch_idxs]\n else: batch_y = None\n loss, acc = self.batch_loss(Variable(batch_x), Variable(batch_y))\n loss.backward()\n self.optim.step()\n losses.append(loss.data[0])\n accuracies.append(acc)\n print(i,\"/\", len(X), \"– Loss:\", losses[-1], \"– Acc:\", acc, end='\\r')\n return losses, accuracies\n\n" }, { "alpha_fraction": 0.6331677436828613, "alphanum_fraction": 0.6568589806556702, "avg_line_length": 30.530120849609375, "blob_id": "3ea6b5c152ee90eb37cf5e7f1c87ca07d13c4f13", "content_id": "25b93bf0f7a9b0ddc9d5bc62d267cd6c067483c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2619, "license_type": "no_license", "max_line_length": 103, "num_lines": 83, "path": "/main.py", "repo_name": "grantsrb/simple_autoencoder", "src_encoding": "UTF-8", "text": "import torch\nimport torchvision\nfrom torch.autograd import Variable\nfrom trainer import Trainer\nfrom encoder import Encoder\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\n\ndef cuda_if(tobj):\n if torch.cuda.is_available():\n tobj = tobj.cuda()\n return tobj\n\ndef preprocess(imgs, mean, std):\n return (imgs-mean)/(std+1e-7)\n\ndef postprocess(remakes, mean, std):\n return remakes*(std+1e-7) + mean\n\nn_epochs = 500\nbatch_size = 128\nlr = .001\npred_coef = .25 # Portion of loss from classification\nprocess = False\nresume = False\n\nif len(sys.argv) > 1:\n for i in range(len(sys.argv)):\n str_arg = str(sys.argv[i])\n if 'lr=' == str_arg[:3]: lr = float(str_arg[3:])\n if 'pred_coef=' in str_arg: pred_coef = float(str_arg[len('pred_coef='):])\n\nprint(\"lr:\", lr)\nprint(\"pred_coef:\", pred_coef)\n\ncifar = torchvision.datasets.CIFAR10(\"/Users/satchelgrant/Datasets/cifar10\", train=True, download=True)\nimgs = cifar.train_data\nimgs = cuda_if(torch.FloatTensor(imgs.transpose((0,3,1,2))))\nmean = imgs.mean()\nstd = imgs.std()\nif process:\n imgs = preprocess(imgs, mean, std)\nlabels = cuda_if(torch.LongTensor(cifar.train_labels))\nperm = cuda_if(torch.randperm(len(imgs)))\ntrain_imgs = imgs[perm[:45000]]\ntrain_labels = labels[perm[:45000]]\nval_imgs = imgs[perm[45000:]]\nval_labels = labels[perm[45000:]]\n \nnet = Encoder(imgs.shape, torch.max(labels)+1)\nnet = cuda_if(net)\nif resume:\n net.load_state_dict(torch.load('network.p'))\ntrainer = Trainer(net, lr=lr, pred_coef=pred_coef)\n\nfor epoch in range(n_epochs):\n print(\"Begin Epoch\", epoch)\n losses, accuracies = trainer.train(train_imgs, train_labels, batch_size)\n print(\"Avg Loss:\", np.mean(losses), \"– Avg Acc:\", np.mean(accuracies))\n if (epoch % 10) == 0:\n acc = 0\n val_batch_size = 300\n for i in range(0,len(val_imgs), val_batch_size):\n zs, remakes = net.forward(Variable(val_imgs[i:i+val_batch_size]))\n logits = net.classify(zs)\n _, max_idxs = torch.max(logits.data, dim=-1)\n acc += torch.eq(max_idxs, val_labels[i:i+val_batch_size]).float().mean()\n acc = acc/(len(val_imgs)/float(val_batch_size))\n torch.save(net.state_dict(), 'network.p')\n print(\"Val Acc:\", acc)\n\nzs, remakes = net.forward(Variable(val_imgs[:20]))\ntorch.save(net.state_dict(), 'network.p')\nif process:\n remakes = postprocess(remakes, mean, std)\nremakes = remakes.data.cpu().numpy()\nreals = val_imgs[:20]\nif process:\n reals = postprocess(reals, mean, std)\nreals = reals.cpu().numpy()\nnp.save('remakes.npy', remakes)\nnp.save('reals.npy', reals[:20])\n" } ]
4
donalhill/awkward1_combinatorics_test
https://github.com/donalhill/awkward1_combinatorics_test
2a0c424fc01b3422a12bea5fae4669cb20860fbf
87c47c6665fade65e8e9a5ce96b91e3d03f5c940
49dcafe202384b89808335ae3767fcbc62f2517b
refs/heads/master
2022-12-15T07:19:39.731632
2020-09-15T21:25:14
2020-09-15T21:25:14
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6383561491966248, "alphanum_fraction": 0.6691780686378479, "avg_line_length": 30.7391300201416, "blob_id": "cb463a1a1839aa95770fbb83feea2f3c0e7a020a", "content_id": "4158ed40a5c1d7e5645ff06919cd49d540ede055", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1460, "license_type": "no_license", "max_line_length": 112, "num_lines": 46, "path": "/python/simple_combiner.py", "repo_name": "donalhill/awkward1_combinatorics_test", "src_encoding": "UTF-8", "text": "import uproot4 as uproot\nimport sys,os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport awkward1 as ak\n\ndef calc_invariant_mass(p1, p2):\n masses = np.sqrt(2*p1[\"pt\"]*p2[\"pt\"]*(np.cosh(p1[\"eta\"] - p2[\"eta\"]) - np.cos(p1[\"phi\"] - p2[\"phi\"])))\n\nfrom matplotlib import rc\nrc('font',**{'family':'serif','serif':['Roman']})\nrc('text', usetex=True)\n\n#Points to home dir of project\npath = \"./\"\n\n#Open ROOT file from Pythia Delphes production with FCCSW\nfile = uproot.open(f\"{path}/output/rootfiles/FCCDelphesOutput_100events.root\")\ntree = file['events'] #Get TTree from file\n\n#Get the charged tracks\ntr = tree.arrays(filter_name=\"pfcharged.core*\")\ntr[\"p\"] = np.sqrt(tr[\"pfcharged.core.p4.px\"]**2 + tr[\"pfcharged.core.p4.py\"]**2 + tr[\"pfcharged.core.p4.pz\"]**2)\ntr[\"pt\"] = np.sqrt(tr[\"pfcharged.core.p4.px\"]**2 + tr[\"pfcharged.core.p4.py\"]**2)\ntr['eta'] = np.log((tr['p'] + tr['pfcharged.core.p4.pz'])/(tr['p'] - tr['pfcharged.core.p4.pz']))/2\ntr['phi'] = np.arctan2(tr['pfcharged.core.p4.py'], tr['pfcharged.core.p4.px'])\n\n#Pions\npi_cut = abs(tr[\"pfcharged.core.pdgId\"]) == 211\npi = tr[pi_cut]\n#Number of pions in each event\npi_sum = ak.num(pi_cut)\n#Keep events with 2 or more pions\npi = pi[pi_sum >= 2]\n\n#Make pion pairs per event\npi_pairs = ak.combinations(pi, 2)\n#pt of first pion pair from first event\n#print(pi_pairs[0][\"pt\"][0])\n\npi1, pi2 = ak.unzip(pi_pairs)\n\nm_pipi = calc_invariant_mass(pi1, pi2)\n\nplt.hist(ak.flatten(m_pipi),bins=400)\nplt.show()\n" } ]
1
sils-webinfo/FarmersMarket
https://github.com/sils-webinfo/FarmersMarket
96f304299d7c8f5bcc6224a0ec3a995d601680b0
e535d6faf7b0d035f73dbb4bb30bdb0338ce880a
f91381f65af253c75c7415b38855e3a4eebc9270
refs/heads/master
2021-01-12T08:48:25.069015
2016-12-17T02:22:00
2016-12-17T02:22:00
76,699,162
0
0
null
2016-12-17T02:27:31
2016-12-05T19:56:38
2016-12-13T11:59:48
null
[ { "alpha_fraction": 0.658072829246521, "alphanum_fraction": 0.6680631637573242, "avg_line_length": 28.55238151550293, "blob_id": "79a0835980ac7df6a4bc94690fb870efc58280ec", "content_id": "c4b719fcb269172d5a9ad9e64bbd85082effbc69", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3103, "license_type": "permissive", "max_line_length": 76, "num_lines": 105, "path": "/server.py", "repo_name": "sils-webinfo/FarmersMarket", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, make_response, redirect\nfrom flask.ext.restful import Api, Resource, reqparse, abort\n\nimport json\nimport string\nimport random\n\n\n# Load data from disk.\n# This simply loads the data from our \"database,\" which is just a JSON file.\nwith open('data.json') as data:\n data = json.load(data)\n\n\n# Generate a unique ID for a new farm.\n# By default this will consist of six lowercase numbers and letters.\ndef generate_id(size=6, chars=string.ascii_lowercase + string.digits):\n return ''.join(random.choice(chars) for _ in range(size))\n\n\n# Respond with 404 Not Found if no farm with the specified ID exists.\ndef error_if_farm_not_found(farm_id):\n if farm_id not in data['farms']:\n message = \"No farm with ID: {}\".format(farm_id)\n abort(404, message=message)\n\n\n# Given the data for a farm, generate an HTML representation\n# of that farm.\ndef render_farm_as_html(farm):\n return render_template('farm.html', farm=farm)\n\n\n# Given the data for a list of farms, generate an HTML representation\n# of that list.\ndef render_farm_list_as_html(farms):\n return render_template('farms.html', farms=farms)\n\n\n# Raises an error if the string x is empty (has zero length).\ndef nonempty_string(x):\n s = str(x)\n if len(x) == 0:\n raise ValueError('string is empty')\n return s\n\n\n# Specify the data necessary to create a new farm.\nnew_farm_parser = reqparse.RequestParser()\nfor arg in ['name', 'description']:\n new_farm_parser.add_argument(\n arg, type=nonempty_string, required=True,\n help=\"'{}' is a required value\".format(arg))\nnew_farm_parser.add_argument(\n 'products', type=nonempty_string, required=True, action='append',\n help=\"'{}' is a required value\".format(arg))\n\n\n# Define our farm resource.\nclass Farm(Resource):\n\n # If a farm with the specified ID does not exist,\n # respond with a 404, otherwise respond with an HTML representation.\n def get(self, farm_id):\n error_if_farm_not_found(farm_id)\n return make_response(\n render_farm_as_html(\n data['farms'][farm_id]), 200)\n\n\n# Define our farm list resource.\nclass FarmList(Resource):\n\n # Respond with an HTML representation of the farm list.\n def get(self):\n return make_response(\n render_farm_list_as_html(data['farms']), 200)\n\n # Add a new farm to the list, and respond with an HTML\n # representation of the updated list.\n def post(self):\n farm = new_farm_parser.parse_args()\n farm_id = generate_id()\n farm['@id'] = 'request/' + farm_id\n data['farms'][farm_id] = farm\n return make_response(\n render_farm_list_as_html(data['farms']), 201)\n\n\n# Assign URL paths to our resources.\napp = Flask(__name__)\napi = Api(app)\napi.add_resource(FarmList, '/requests')\napi.add_resource(Farm, '/request/<string:farm_id>')\n\n\n# Redirect from the index to the list of farms.\[email protected]('/')\ndef index():\n return redirect(api.url_for(FarmList), code=303)\n\n\n# Start the server.\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8888, debug=True)\n" } ]
1
LasseJacobs/std_unordered_map_py_wrapper
https://github.com/LasseJacobs/std_unordered_map_py_wrapper
5d325e1759a4d29cedbaaceacd054df70e8e69e5
3fa1b302ec1528194d97182a806639db9c8cbac4
724bf72f9fd73688fbbb6559efff7b39f2a133cf
refs/heads/master
2020-07-10T03:07:36.615234
2019-08-24T12:12:42
2019-08-24T12:12:42
204,151,739
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6283524632453918, "alphanum_fraction": 0.6360152959823608, "avg_line_length": 12.050000190734863, "blob_id": "57bf2274eac377a102e577bb48049ae91fff7434", "content_id": "777944bf681ae6ffb0337da70b7bf041c002f3a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 261, "license_type": "no_license", "max_line_length": 66, "num_lines": 20, "path": "/Makefile", "repo_name": "LasseJacobs/std_unordered_map_py_wrapper", "src_encoding": "UTF-8", "text": "#C++ Makefile\nCC=g++\n\nVERSION=-std=c++14\nCFLAGS=-c -fPIC\nLDFLAGS=\nPNAME=hello\n\n\nall: build\n\nbuild: map.o\n\t$(CC) $(VERSION) -shared -Wl,-soname,libmap.so -o libmap.so map.o\n\nmap.o: map.cpp\n\t$(CC) $(CFLAGS) $(VERSION) map.cpp\n\nclean:\n\trm *o\n\techo 'clean done...'\n" }, { "alpha_fraction": 0.46880051493644714, "alphanum_fraction": 0.46880051493644714, "avg_line_length": 16.872833251953125, "blob_id": "aa52f93468315840416dd6f8670807b4d7b940d0", "content_id": "2de4f6a756bdec35b860e46f9890246ee168dda9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3093, "license_type": "no_license", "max_line_length": 69, "num_lines": 173, "path": "/map.cpp", "repo_name": "LasseJacobs/std_unordered_map_py_wrapper", "src_encoding": "UTF-8", "text": "\n#include <string>\n#include <unordered_map>\n\nnamespace pw\n{\n template<typename T>\n struct result\n {\n T value;\n bool found;\n };\n \n typedef unsigned int size_type;\n}\n\nnamespace ds \n{\n typedef std::unordered_map<std::string, std::string> map;\n typedef pw::result<const char*> result; \n}\n\nextern \"C\" \n{\n /*\n * Constructors \n */\n \n ds::map* new_map() \n { \n return new ds::map(); \n }\n \n \n /*\n * Capacity \n */\n \n bool m_empty(const ds::map* map)\n {\n return map->empty();\n }\n \n pw::size_type m_size(const ds::map* map)\n {\n return map->size();\n }\n \n pw::size_type m_max_size(const ds::map* map)\n {\n return map->max_size();\n }\n \n \n /*\n * Modifiers \n */\n \n void m_clear(ds::map* map) \n { \n map->clear();\n }\n \n void m_set(ds::map* map, const char* key, const char* value) \n {\n (*map)[key] = value;\n }\n \n void m_erase(ds::map* map, const char* key) \n { \n map->erase(key);\n }\n \n void m_swap(ds::map* map, ds::map* other)\n {\n map->swap(*other);\n }\n \n \n /*\n * Lookup \n */\n \n // at -> look up how to implement exceptions\n \n const char* m_get(const ds::map* map, const char* key) \n {\n // operator[] -> check what happens when non-existing access \n auto itr = map->find(key);\n if(itr == map->end())\n return nullptr;\n \n return itr->second.c_str();\n }\n \n pw::size_type m_count(const ds::map* map, const char* key) \n {\n map->count(key);\n }\n \n ds::result m_find(const ds::map* map, const char* key)\n {\n auto itr = map->find(key);\n if(itr == map->end())\n return {\"\", false};\n \n return {itr->second.c_str(), true};\n }\n \n \n /*\n * Bucket interface \n */\n \n pw::size_type m_bucket_count(const ds::map* map)\n {\n return map->bucket_count();\n }\n \n pw::size_type m_max_bucket_count(const ds::map* map)\n {\n return map->max_bucket_count();\n }\n \n pw::size_type m_bucket_size(const ds::map* map, pw::size_type n)\n {\n return map->bucket_size(n);\n }\n \n pw::size_type m_bucket(const ds::map* map, const char* key)\n {\n return map->bucket(key);\n }\n \n \n /*\n * Hash Policy \n */\n \n float m_load_factor(const ds::map* map)\n {\n return map->load_factor();\n }\n \n float m_get_max_load_factor(const ds::map* map)\n {\n return map->max_load_factor();\n }\n \n void m_set_max_load_factor(ds::map* map, float ml)\n {\n map->max_load_factor(ml);\n }\n \n void m_rehash(ds::map* map, pw::size_type count)\n {\n return map->rehash(count);\n }\n \n void m_reserve(ds::map* map, pw::size_type count)\n {\n return map->reserve(count);\n }\n \n \n /*\n * Destructor \n */\n \n void delete_map(ds::map* map) \n { \n delete map;\n }\n}\n" }, { "alpha_fraction": 0.6676923036575317, "alphanum_fraction": 0.670769214630127, "avg_line_length": 15.25, "blob_id": "09129163042209fa919d2d9ee956f5899d6613b1", "content_id": "85d9df592383dda0d0d5e89a36b859d064b3b86e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 325, "license_type": "no_license", "max_line_length": 63, "num_lines": 20, "path": "/README.md", "repo_name": "LasseJacobs/std_unordered_map_py_wrapper", "src_encoding": "UTF-8", "text": "# std::unordered_map Python wrapper\nA python wrapper class for the std::unordered_map class (c++). \n\n**Note:**\n - All methods that make use of iterators are excluded. \n - Only the string type is supported.\n \n## How to use\nBuild the C++ library:\n\n```\n$ make\n```\n\nThen run the demo code:\n\n```\n$ python3 main.py\nHello World\n```\n" }, { "alpha_fraction": 0.5493965148925781, "alphanum_fraction": 0.5509611368179321, "avg_line_length": 22.06185531616211, "blob_id": "6980344898c29d95099762706039fe54049f684e", "content_id": "6100e0de782e9df6818eddcefe806280aeeb4e31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4474, "license_type": "no_license", "max_line_length": 69, "num_lines": 194, "path": "/map.py", "repo_name": "LasseJacobs/std_unordered_map_py_wrapper", "src_encoding": "UTF-8", "text": "from ctypes import *\nlib = cdll.LoadLibrary('./libmap.so')\n\nclass c_result(Structure):\n _fields_ = [('value', c_char_p), ('found', c_bool)]\n\n###################\n# __init__(self):\nlib.new_map.restype = c_void_p;\n\n\n###################\n# empty(self):\nlib.m_empty.argtypes = [c_void_p]\n \n# size(self):\nlib.m_size.argtypes = [c_void_p]\nlib.m_size.restype = c_ulong\n \n# max_size(self):\nlib.m_max_size.argtypes = [c_void_p]\nlib.m_max_size.restype = c_ulong\n\n\n##################\n# clear(self):\nlib.m_clear.argtypes = [c_void_p]\n\n# set(self, key, value):\nlib.m_set.argtypes = [c_void_p, c_char_p, c_char_p]\n\n# erase(self, key):\nlib.m_erase.argtypes = [c_void_p, c_char_p]\n\n# swap(self, other_map):\nlib.m_swap.argtypes = [c_void_p, c_void_p]\n\n\n##################\n# get(self, key):\nlib.m_get.argtypes = [c_void_p, c_char_p]\nlib.m_get.restype = c_char_p\n\n# count(self, key):\nlib.m_count.argtypes = [c_void_p, c_char_p]\nlib.m_count.restype = c_ulong\n\n# find(self, key):\nlib.m_find.argtypes = [c_void_p, c_char_p]\nlib.m_find.restype = c_result\n\n\n################\n# bucket_count(self):\nlib.m_bucket_count.argtypes = [c_void_p]\nlib.m_bucket_count.restype = c_ulong\n \n# max_bucket_count(self):\nlib.m_max_bucket_count.argtypes = [c_void_p]\nlib.m_max_bucket_count.restype = c_ulong\n \n# bucket_size(self, n):\nlib.m_bucket_size.argtypes = [c_void_p, c_ulong]\nlib.m_bucket_size.restype = c_ulong\n \n# bucket(self, key):\nlib.m_bucket.argtypes = [c_void_p, c_char_p]\nlib.m_bucket.restype = c_ulong\n\n\n###############\n# load_factor(self):\nlib.m_load_factor.argtypes = [c_void_p]\nlib.m_load_factor.restype = c_float\n \n# max_load_factor(self):\nlib.m_get_max_load_factor.argtypes = [c_void_p]\nlib.m_get_max_load_factor.restype = c_float\n \n# max_load_factor(self, ml):\nlib.m_set_max_load_factor.argtypes = [c_void_p, c_float]\n \n# rehash(self, count):\nlib.m_rehash.argtypes = [c_void_p, c_ulong]\n\n# reserve(self, count):\nlib.m_reserve.argtypes = [c_void_p, c_ulong]\n\n\n###############\n# __del__(self):\nlib.delete_map.argtypes = [c_void_p]\n\n\n\nclass std_result(object):\n def __init__(self, value, found):\n self.value = value\n self.found = found \n\n\nclass std_map(object):\n def __init__(self):\n self.obj = lib.new_map()\n \n \n ## Capacity\n \n def empty(self):\n return lib.m_empty(self.obj)\n \n def size(self):\n return lib.m_size(self.obj)\n \n def max_size(self):\n return lib.m_max_size(self.obj)\n \n \n ## Modifiers\n \n def clear(self):\n lib.m_clear(self.obj)\n \n def set(self, key, value):\n b_key = key.encode('utf-8')\n b_value = value.encode('utf-8')\n lib.m_set(self.obj, b_key, b_value) \n \n def erase(self, key):\n b_key = key.encode('utf-8')\n lib.m_erase(self.obj, b_key)\n \n def swap(self, other_map):\n lib.m_swap(self.obj, other_map.obj)\n\n \n ## Lookup \n \n def get(self, key): \n b_key = key.encode('utf-8')\n value = lib.m_get(self.obj, b_key)\n \n return value.decode() if value else None \n \n def count(self, key):\n b_key = key.encode('utf-8')\n return lib.m_count(self.obj, b_key)\n \n def find(self, key):\n b_key = key.encode('utf-8')\n pw_result = lib.m_find(self.obj, b_key)\n \n value = pw_result.value.decode() if pw_result.found else None\n return std_result(value , pw_result.found)\n \n \n ## Bucket Interface\n \n def bucket_count(self):\n return lib.m_bucket_count(self.obj)\n \n def max_bucket_count(self):\n return lib.m_max_bucket_count(self.obj)\n \n def bucket_size(self, n):\n return lib.m_bucket_size(self.obj, n)\n \n def bucket(self, key):\n b_key = key.encode('utf-8')\n return lib.m_bucket(self.obj, b_key)\n \n \n ## Hash Policy\n \n def load_factor(self):\n return lib.m_load_factor(self.obj)\n \n def max_load_factor(self):\n return lib.m_get_max_load_factor(self.obj)\n \n def max_load_factor(self, ml):\n lib.m_set_max_load_factor(self.obj, ml)\n \n def rehash(self, count):\n lib.m_rehash(self.obj, count)\n \n def reserve(self, count):\n lib.m_reserve(self.obj, count)\n \n \n ## Destructor\n \n def __del__(self):\n lib.delete_map(self.obj)\n" }, { "alpha_fraction": 0.6263736486434937, "alphanum_fraction": 0.6263736486434937, "avg_line_length": 12, "blob_id": "63ab6a0567f9c7a010715b60e4a6541c9d79a62a", "content_id": "0fd7153e092bda71d0c5b12db6ee28ede963faff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 91, "license_type": "no_license", "max_line_length": 28, "num_lines": 7, "path": "/main.py", "repo_name": "LasseJacobs/std_unordered_map_py_wrapper", "src_encoding": "UTF-8", "text": "from map import std_map\n\n\nm = std_map()\n\nm.set(\"demo\", \"Hello World\")\nprint(m.get(\"demo\"))\n" } ]
5
kartikeyrajvaidya/fb_pages_manager
https://github.com/kartikeyrajvaidya/fb_pages_manager
57d90d5da03b9467ef17c51084cf6145de36df7e
0393d8e3d49c54ba3f57747269d2a99a76654c5e
f9f641172408300996020e186c7958837e5493ec
refs/heads/master
2020-03-31T05:20:57.582169
2018-12-04T06:17:09
2018-12-04T06:17:09
151,942,603
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7258347868919373, "alphanum_fraction": 0.7258347868919373, "avg_line_length": 39.67856979370117, "blob_id": "13317b9473be5a0f59e7c27eaeabefe4c7407601", "content_id": "497a2d2e4f87268e8317f2e3f3d40da8feaf530a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1138, "license_type": "no_license", "max_line_length": 80, "num_lines": 28, "path": "/fb_page_manager/fbapp/forms.py", "repo_name": "kartikeyrajvaidya/fb_pages_manager", "src_encoding": "UTF-8", "text": "from django import forms\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Submit, Layout, Field\n\n# not used\nclass SimpleForm(forms.Form):\n name = forms.CharField(label=\"Page Name\", required=False)\n about = forms.CharField(label=\"About Page\", required=False)\n bio = forms.CharField(label=\"Bio\", required=False)\n website = forms.CharField(label=\"Website\", required=False)\n phone = forms.CharField(label=\"Phone\", required=False)\n whatsapp_number = forms.CharField(label=\"Whatsapp Number\", required=False)\n general_info = forms.CharField(label=\"General Info\", required=False)\n\n impressum = forms.CharField(label=\"Impressum\", required=False)\n description = forms.CharField(label=\"Description\", required=False)\n company_overview = forms.CharField(label=\"Company Overview\", required=False)\n hello = forms.CharField(required=False)\n\n #category = forms.CharField(label=\"Page Category\", required=False)\n\n helper = FormHelper()\n helper.form_method = 'POST'\n helper.layout = Layout(\n Field(\"hello\", type=\"hidden\", hidden=True)\n )\nclass NewPostForm(forms.Form):\n pass" }, { "alpha_fraction": 0.6224408149719238, "alphanum_fraction": 0.6256314516067505, "avg_line_length": 36.21782302856445, "blob_id": "014fdfb90afe2e7cb547ba89041e6025cfddd3df", "content_id": "0b0a8901081b2f7129e992aaf2a0f3f70d73dc1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3761, "license_type": "no_license", "max_line_length": 185, "num_lines": 101, "path": "/fb_page_manager/fbapp/views.py", "repo_name": "kartikeyrajvaidya/fb_pages_manager", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.template import loader\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom requests import request as call\nimport json\nfrom . import forms\n\n\ndef logout(request):\n return render(request, \"fbapp/logout.html\")\n\n\ndef pageFeeds(request):\n if(request.method==\"GET\"):\n token=request.GET[\"token\"]\n pageId = request.GET[\"pageId\"]\n header=\"OAuth \"+ token\n api_url=\"https://graph.facebook.com/\"+ pageId + \"/feed?fields=message,comments,from,likes,shares\"\n page_obj = call('GET', api_url, headers={\"Authorization\": header})\n feeds_obj_json = page_obj.json()['data']\n return render(request, 'fbapp/feeds.html',{'feeds': feeds_obj_json,'pageId':pageId,'token':token })\n return render(400)\n\n\ndef home(request):\n context = {\n \"title\":\"GrowthPlug Page Administrator\"\n }\n # my_template = loader.get_template(\"fbapp/home.html\") # old-way\n # return HttpResponse(my_template.render(context,request))\n return render(request, \"fbapp/home.html\", context)\n\n\ndef dashboard(request):\n if(request.method==\"POST\"):\n token=request.POST.get(\"token\",'')\n header=\"OAuth \"+ token\n details=call('GET', 'https://graph.facebook.com/me/accounts', headers={\"Authorization\": header})\n d2=call('GET','https://graph.facebook.com/me', headers={\"Authorization\":header})\n\n # ------------ new stuff ----------------- #\n\n page_ids_list = details.json()[\"data\"]\n page_attributes='name,phone,overall_star_rating,is_published,location,verification_status'\n\n dict_details = details.json()\n\n page_list = []\n for index in range(len(page_ids_list)):\n page_id = page_ids_list[index][\"id\"]\n page_token = page_ids_list[index][\"access_token\"]\n api_url=\"https://graph.facebook.com/\"+ page_id + \"?fields=\"+page_attributes\n header='OAuth ' + page_token\n page_obj = call('GET', api_url, headers={\"Authorization\": header})\n\n page_obj_json = page_obj.json()\n page_obj_json[\"is_published\"] = str(page_obj_json[\"is_published\"])\n page_ids_list[index][\"page_info\"] = page_obj_json\n\n page_list.append(json.dumps(page_obj.json()))\n\n\n # ------------ new stuff ends----------------- #\n\n typo = str(type(details.json()))\n details=json.dumps(details.json())\n\n d2=json.dumps(d2.json())\n return render(request, \"fbapp/dashboard.html\",{\"title\":\"Page Administrator\",'pages': page_ids_list, 'personal':d2 , 'page_list' : page_list }) #, 'mega_details': mega_details})\n else:\n # here use sessions to save user-id and pageids/tokens\n details = {}\n d2 = {}\n return render(request, \"fbapp/dashboard.html\",{\"title\":\"Page Administrator\",'pages': details, 'personal':d2}) #, 'mega_details': mega_details})\n\n #return render(request, \"fbapp/dashboard.html\")\n\n@csrf_exempt\ndef get_page_details(request):\n if request.method==\"POST\":\n print(\"HELLO\")\n fields='name,about,phone,emails,website,fan_count,link,overall_star_rating,location,displayed_message_response_time'\n pageToken=request.POST.get(\"pageToken\",'')\n pageId=request.POST.get(\"pageId\",'')\n header='OAuth ' + pageToken\n url=\"https://graph.facebook.com/\"+pageId + \"?fields=\"+fields\n details=call('GET', url, headers={\"Authorization\": header})\n\n details=json.dumps(details.json())\n return HttpResponse(details)\n return HttpResponse(400)\n\n#not used\ndef get_form(request):\n\n id = request.GET.get(\"id\",'')\n form = forms.SimpleForm()\n\n return render(request, 'fbapp/pageform.html', {'form_obj': form})\n\n\n" } ]
2
xiangzhihai/mitweek11
https://github.com/xiangzhihai/mitweek11
d0a8607923589bf66443f986f25d2e4b8242f4ae
8b847226cbf1674573be98b3bb10a5347aecf5cf
60167edc890bf75d6a167c7c66ba75b7e67e2e4d
refs/heads/main
2023-06-16T16:29:33.786107
2021-07-19T16:13:52
2021-07-19T16:13:52
387,524,000
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5190504789352417, "alphanum_fraction": 0.544701099395752, "avg_line_length": 38.91916275024414, "blob_id": "0473bd24eba62fdfb39106bd74c982b3a9d745ee", "content_id": "158ed8ec1e394cc8750dedbf286c0794d2e89661", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26666, "license_type": "no_license", "max_line_length": 144, "num_lines": 668, "path": "/code_for_lab11.py", "repo_name": "xiangzhihai/mitweek11", "src_encoding": "UTF-8", "text": "import pdb\nfrom util import *\nimport numpy as np\nimport sm\nimport functools\nimport random\nimport _pickle as cPickle\n\n############################################################################\n#\n# Testing RNN Learning\n#\n############################################################################\n\n# np.random.seed(0) # set the random seed to ensure same output\nnp.seterr(over='raise')\n\n# Learn accumulator\ndef test_linear_accumulator(num_steps = 10000,\n num_seqs = 100, seq_length = 5,\n step_size = .01):\n # generate random training data: num_seqs of seq_length of random\n # numbers between -0.5 and 0.5.\n data = []\n for _ in range(num_seqs): \n x = np.random.random((1, seq_length)) - 0.5 # seq in\n y = np.zeros((1, seq_length)) # seq out\n for j in range(seq_length):\n y[0, j] = x[0, j] + (0.0 if j == 0 else y[0, j-1])\n data.append((x, y))\n # specify rnn\n rnn = RNN(1, 1, 1, quadratic_loss, lambda z: z, quadratic_linear_gradient,\n step_size, lambda z: z, lambda z: 1)\n # train it\n rnn.train_seq_to_seq(data, num_steps)\n # print weights\n print(\"\\nWeights:\", flush=True)\n print(\"Wsx:\", rnn.Wsx); print(\"Wss:\", rnn.Wss); print(\"Wo:\", rnn.Wo)\n print(\"Wss0:\", rnn.Wss0); print(\"Wo0:\", rnn.Wo0)\n return rnn\n\n# Learn delay of 1 dimensional data, e.g. numbers\ndef test_delay_num(delay = 1, num_steps = 10000,\n num_seqs = 10000, seq_length = 10,\n step_size = .005):\n # generate random training data: num_seqs of seq_length of random\n # numbers (between 0 and 1)\n data = []\n for _ in range(num_seqs):\n vals = np.random.random((1, seq_length))\n x = np.hstack([vals, np.zeros((1, delay))]) # seq in, pad right\n y = np.hstack([np.zeros((1, delay)), vals]) # seq out, pad left\n data.append((x, y))\n # specify rnn\n m = (delay + 1) * 2\n rnn = RNN(1, m, 1, quadratic_loss, lambda z: z, quadratic_linear_gradient,\n step_size, lambda z: z, lambda z: 1)\n # train it\n rnn.train_seq_to_seq(data, num_steps)\n # print weights\n print(\"\\nWeights:\", flush=True)\n print(\"Wsx:\", rnn.Wsx); print(\"Wss:\", rnn.Wss); print(\"Wo:\", rnn.Wo)\n print(\"Wss0:\", rnn.Wss0); print(\"Wo0:\", rnn.Wo0)\n # construct a state machine and test with a (fixed) sequence\n mm = rnn.sm()\n print(mm.transduce([np.array([[float(v)]]) \\\n for v in [3, 4, 5, 1, 2, -1, 6]]))\n return rnn\n\n# Learn delay of one-hot encoided characters, e.g. numbers\ndef test_delay_char(delay = 1, num_steps = 10000,\n alphabet = tuple(range(10)),\n num_seqs = 10000, seq_length = 4, step_size = .001):\n # generate random training data: num_seqs of seq_length of\n # integers, represented by one-hot vectors over the alphabet.\n codec = OneHotCodec(alphabet)\n n = codec.n\n data = []\n for _ in range(num_seqs):\n rand_seq = np.random.random_integers(0, n-1, seq_length)\n vals = codec.encode_seq(rand_seq) # one-hot typically\n # first word of alphabet is start/end symbol\n pad = codec.encode_seq(alphabet[0:1] * delay)\n x = np.hstack([vals, pad])\n y = np.hstack([pad, vals])\n data.append((x, y))\n # specify rnn\n m = (delay + 1) * n\n f1, df1 = tanh, tanh_gradient\n loss, f2, dLdf2 = NLL, softmax, NLL_softmax_gradient\n rnn = RNN(n, m, n, loss, f2, dLdf2,\n step_size, f1, df1)\n # train it\n rnn.train_seq_to_seq(data, num_steps)\n # construct a state machine and test with a (fixed) sequence\n mm = rnn.sm()\n vin = [codec.encode(c) for c in [0, 1, 1, 0, 0, 2, 1, 2, 0, 1, 1]]\n vout = mm.transduce(vin)\n cout = [codec.decode_max(v) for v in vout]\n print(cout)\n return rnn\n\n# interpret first bit as lowest order; may leave off highest-order bit\n# s1 and s2 are 1 x k\n# return 1 x k\ndef bin_add(s1, s2): # binary add\n k = s1.shape[1]\n result = np.zeros((1, k))\n carry = 0\n for j in range(k):\n tot = s1[0, j] + s2[0, j] + carry\n result[0,j] = tot % 2\n carry = 1 if tot > 1 else 0\n return result\n\n# Learn binary addition\ndef test_binary_addition(num_seqs = 1000, seq_length = 5, num_steps = 50000,\n step_size = 0.01, num_hidden = 8):\n # generate random training data: num_seqs of seq_length of\n # binary integers.\n data = []\n for _ in range(num_seqs):\n s1 = np.random.random_integers(0, 1, (1, seq_length))\n s2 = np.random.random_integers(0, 1, (1, seq_length))\n x = np.vstack([s1, s2]) # seq in\n y = bin_add(s1, s2) # seq out\n data.append((x, y))\n # specify rnn\n l = 2 # two input dimensions\n m = num_hidden\n n = 1 # one output dimension\n f1 = sigmoid; df1 = sigmoid_gradient\n loss = quadratic_loss\n f2 = lambda z: z; dldz2 = quadratic_linear_gradient\n rnn = RNN(l, m, n, loss, f2, dldz2, step_size, f1, df1)\n # train it\n rnn.train_seq_to_seq(data, num_steps)\n # construct a state machine and test with a (fixed) sequence\n mm = rnn.sm()\n n1 = '01101'\n n2 = '01111'\n # answer is: 11100\n a = [np.array([[float(d1), float(d2)]]).T for d1, d2 in zip(n1, n2)]\n vin = list(reversed(a))\n vout = mm.transduce(vin)\n print(' in:', vin)\n print('out:', vout)\n return rnn\n\n# Predicting the next character in a sequence\n\n# Generate the training data for predicting next character\ndef process_seq_data(words):\n alphabet = sorted(list(functools.reduce(lambda a, b: set(a) | set(b),\n words, set())))\n codec = OneHotCodec(alphabet + ['.'])\n data = []\n for w in words:\n vals = codec.encode_seq(w)\n pad = codec.encode_seq(['.'])\n y = np.hstack([vals, pad])\n x = np.hstack([pad, vals])\n data.append((x, y))\n return data, codec\n\n# Train rnn\ndef train_seq(data, codec, num_steps = 10000, step_size = 0.01,\n num_hidden = 10, interactive = False):\n # specify rnn\n l = codec.n\n m = num_hidden\n n = codec.n\n f1 = tanh; df1 = tanh_gradient\n loss = NLL\n f2 = softmax; dldz2 = NLL_softmax_gradient\n rnn = RNN(l, m, n, loss, f2, dldz2, step_size, f1, df1)\n # train it\n rnn.train_seq_to_seq(data, num_steps)\n return rnn\n\n# Generate the training data and carry out the prediction\ndef generate_seq(words, num_steps = 10000, step_size = 0.05, num_hidden = 20,\n split=0., interactive = False, interactive_top5 = False):\n data, codec = process_seq_data(words) \n if split and len(words) > 1:\n random.shuffle(data)\n k = int((1-split)*len(data))\n data1, data2 = data[:k], data[k:]\n print('Training set size', len(data1), 'Held out set size', len(data2))\n else:\n data1, data2 = data, None\n rnn = train_seq(data1, codec, num_steps = num_steps,\n step_size = step_size, num_hidden = num_hidden,\n interactive = interactive)\n if data2:\n total_loss = 0\n for (x, y) in data2:\n loss, _, _ = rnn.forward_seq(x,y)\n total_loss += loss\n print('Average loss on held out set:', total_loss/len(data2))\n # test by either generating random strings from the beginning or\n # interactively starting from input provided by user.\n if interactive and not(interactive_top5):\n for _ in range(100):\n rnn.gen_seq_interactive(codec)\n elif interactive_top5:\n rnn.gen_seq_interactive_top5(codec)\n else:\n for _ in range(100):\n print(''.join(rnn.gen_seq('.', 100, codec)))\n return rnn, codec\n\n\ndef save_seq(words, out_file,interactive, num_steps = 20000, step_size = 0.001, num_hidden = 150,\n split=0.):\n data, codec = process_seq_data(words) \n if split and len(words) > 1:\n random.shuffle(data)\n k = int((1-split)*len(data))\n data1, data2 = data[:k], data[k:]\n print('Training set size', len(data1), 'Held out set size', len(data2))\n else:\n data1, data2 = data, None\n rnn = train_seq(data1, codec, num_steps = num_steps,\n step_size = step_size, num_hidden = num_hidden,\n interactive = interactive)\n \n cPickle.dump(rnn, open('models/' + out_file, 'wb'))\n\ndef load_seq(words, in_file, interactive, interactive_top5, num_steps = 20000, step_size = 0.001, num_hidden = 150,\n split=0.):\n rnn = cPickle.load(open(in_file,'rb'))\n data, codec = process_seq_data(words) \n \n if interactive and not(interactive_top5):\n for _ in range(100):\n rnn.gen_seq_interactive(codec)\n elif interactive_top5:\n rnn.gen_seq_interactive_top5(codec)\n else:\n for _ in range(100):\n print(''.join(rnn.gen_seq('.', 100, codec)))\n return rnn, codec\n \n \n\n############################################################################\n#\n# Sequence predictions on word lists\n#\n############################################################################\n\nlong_words = ['alabama', 'arkansas', 'mississippi', 'madagascar', \n 'taradiddle', 'hippopotamus', 'missasolemnis', 'abcdefghij']\n\ndirname = '' # default will be current directory\n\ndef test_word(word, interactive = False, num_hidden=1, num_steps=10000, step_size=0.005):\n return generate_seq([word], num_hidden=num_hidden, num_steps=num_steps, step_size=step_size)\n\n# Learn models for two classes, then do classification.\ndef test_language(english = True, split=0.25,\n num_hidden=300, num_steps=500000, step_size=0.001):\n if english:\n data = read_words(dirname + 'baskervilles.txt')\n else:\n data = read_words(dirname + 'mousquetaires.txt')\n\n long = [w.lower() for w in data if len(w) > 5]\n print(len(long), 'long english words')\n\n return generate_seq(long, split=split, num_hidden=num_hidden, num_steps=num_steps, step_size=step_size)\n\n# Generate heavy metal band names\ndef test_metal(interactive = True, interactive_top5 = True, split=0, num_hidden = 150, num_steps = 20000, step_size = .001, train=True):\n data = read_lines(dirname + 'metal_bands.txt')\n if train==True:\n return generate_seq(data, interactive = interactive, split=split,\n num_hidden=num_hidden, num_steps=num_steps, step_size=step_size)\n else:\n in_file = 'models/metal_rnn.p'\n return load_seq(data, in_file, interactive = interactive, interactive_top5 = interactive_top5, split=split,\n num_hidden=num_hidden, num_steps=num_steps, step_size=step_size)\n \n# Generate MIT class names\ndef test_class_names(interactive = True, interactive_top5 = True, split=0, num_hidden = 150, num_steps = 20000, step_size = .001, train=True):\n data = read_lines(dirname + 'MIT_classes.txt')\n if train==True:\n return generate_seq(data, interactive = interactive, split=split,\n num_hidden=num_hidden, num_steps=num_steps, step_size=step_size)\n else:\n in_file = 'models/MIT_classes_rnn.p'\n return load_seq(data, in_file, interactive = interactive, interactive_top5 = interactive_top5, split=split,\n num_hidden=num_hidden, num_steps=num_steps, step_size=step_size)\n\ndef test_company_names(interactive = True, interactive_top5 = True, split=0, num_hidden = 150, num_steps = 20000, step_size = .001, train=True):\n data = read_lines(dirname + 'companies.txt')\n if train==True:\n return generate_seq(data, interactive = interactive, split=split,\n num_hidden=num_hidden, num_steps=num_steps, step_size=step_size)\n else:\n in_file = 'models/companies_rnn.p'\n return load_seq(data, in_file, interactive = interactive, interactive_top5 = interactive_top5, split=split,\n num_hidden=num_hidden, num_steps=num_steps, step_size=step_size)\n\n \n# Generate food names\ndef test_food(interactive = True,interactive_top5 = True, split=0, num_hidden = 150, num_steps = 20000, step_size =.001, train=True):\n data = read_lines(dirname + 'food.txt')\n if train==True:\n return generate_seq(data, interactive = interactive, split=split,\n num_hidden=num_hidden, num_steps=num_steps, step_size=step_size)\n else:\n in_file = 'models/food_rnn.p'\n return load_seq(data, in_file, interactive = interactive, interactive_top5 = interactive_top5, split=split,\n num_hidden=num_hidden, num_steps=num_steps, step_size=step_size)\n \n \n\n# Generate lines from poem\ndef test_poem(interactive=False, split=0, num_hidden = 80, num_steps = 20000, step_size = .001):\n data = read_lines(dirname + 'simple_poem.txt')\n return generate_seq(data, interactive = interactive, split=split,\n num_hidden=num_hidden, num_steps=num_steps, step_size=step_size)\n\n# Utilities for reading files.\ndef read_words(fileName):\n result = []\n with open(fileName, 'r', encoding='utf-8') as f:\n for line in f:\n result.extend(line.split()) # split the words out\n return result\n\ndef read_lines(fileName):\n result = []\n with open(fileName, 'r', encoding='utf-8' ) as f:\n for line in f:\n result.append(line)\n return result\n\n############################################################################\n#\n# RNN class\n#\n############################################################################\n\n# Based on an implementation by Michael Sun\n\nclass RNN:\n weight_scale = .0001\n def __init__(self, input_dim, hidden_dim, output_dim, loss_fn, f2, dloss_f2, step_size=0.1,\n f1 = tanh, df1 = tanh_gradient, init_state = None,\n Wsx = None, Wss = None, Wo = None, Wss0 = None, Wo0 = None,\n adam = True):\n self.input_dim = input_dim\n self.hidden_dim = hidden_dim\n self.output_dim = output_dim\n self.loss_fn = loss_fn\n self.dloss_f2 = dloss_f2\n self.step_size = step_size\n self.f1 = f1\n self.f2 = f2\n self.df1 = df1\n self.adam = adam\n self.init_state = init_state if init_state is not None else \\\n np.zeros((self.hidden_dim, 1))\n self.hidden_state = self.init_state\n self.t = 0\n\n # Initialize weight matrices\n self.Wsx = Wsx if Wsx is not None \\\n else np.random.random((hidden_dim, input_dim)) * self.weight_scale\n self.Wss = Wss if Wss is not None \\\n else np.random.random((hidden_dim, hidden_dim)) * self.weight_scale\n self.Wo = Wo if Wo is not None \\\n else np.random.random((output_dim, hidden_dim)) * self.weight_scale\n self.Wss0 = Wss0 if Wss0 is not None \\\n else np.random.random((hidden_dim, 1)) * self.weight_scale\n self.Wo0 = Wo0 if Wo0 is not None \\\n else np.random.random((output_dim, 1)) * self.weight_scale\n\n # Initialization for ADAM\n if adam:\n self.dLdWsx_sq = np.zeros_like(self.Wsx)\n self.dLdWo_sq = np.zeros_like(self.Wo)\n self.dLdWss_sq = np.zeros_like(self.Wss)\n self.dLdWo0_sq = np.zeros_like(self.Wo0)\n self.dLdWss0_sq = np.zeros_like(self.Wss0)\n\n self.dLdWsx_m = np.zeros_like(self.Wsx)\n self.dLdWo_m = np.zeros_like(self.Wo)\n self.dLdWss_m = np.zeros_like(self.Wss)\n self.dLdWo0_m = np.zeros_like(self.Wo0)\n self.dLdWss0_m = np.zeros_like(self.Wss0)\n\n\n # Just one step of forward propagation. x and y are for a single time step\n # Depends on self.hidden_state and reassigns it\n # Returns predicted output, loss on this output, and dLoss_dz2\n def forward_propagation(self, x):\n new_state = self.f1(np.dot(self.Wsx, x) +\n np.dot(self.Wss, self.hidden_state) + self.Wss0)\n z2 = np.dot(self.Wo, new_state) + self.Wo0\n p = self.f2(z2)\n self.hidden_state = new_state\n return p\n\n def forward_prop_loss(self, x, y):\n p = self.forward_propagation(x)\n loss = self.loss_fn(p, y)\n dL_dz2 = self.dloss_f2(p, y)\n return p, loss, dL_dz2\n\n def b(self, xs, dL_dz2, states):\n dC = np.zeros_like(self.Wsx)\n dB = np.zeros_like(self.Wss)\n dA = np.zeros_like(self.Wo)\n dB0 = np.zeros_like(self.Wss0)\n dA0 = np.zeros_like(self.Wo0)\n dLfuture_dst = np.zeros((self.hidden_dim, 1))\n k = xs.shape[1]\n for t in range(k-1, -1, -1):\n xt = xs[:, t:t+1]\n st = states[:, t:t+1]\n st_minus_1 = states[:, t-1:t] if t-1 >= 0 else self.init_state\n dL_dz2t = dL_dz2[:, t:t+1]\n dL_dA = np.dot(dL_dz2t, st.T)\n dL_dA0 = dL_dz2t\n dLtfuture_dst = np.dot(self.Wo.T, dL_dz2t) + dLfuture_dst\n dLtfuture_dz1t = dLtfuture_dst * self.df1(st)\n dLtfuture_dB = np.dot(dLtfuture_dz1t, st_minus_1.T)\n dLtfuture_dB0 = dLtfuture_dz1t\n dLtfuture_dC = np.dot(dLtfuture_dz1t, xt.T)\n dLfuture_dst = np.dot(self.Wss.T, dLtfuture_dz1t)\n dC += dLtfuture_dC\n dB += dLtfuture_dB\n dB0 += dLtfuture_dB0\n dA += dL_dA\n dA0 += dL_dA0\n return dC, dB, dA, dB0, dA0\n\n # With adagrad\n def sgd_step(self, xs, dLdz2s, states,\n gamma1 = 0.9, gamma2 = 0.999, fudge = 1.0e-8):\n dWsx, dWss, dWo, dWss0, dWo0 = self.b(xs, dLdz2s, states)\n\n self.t += 1\n\n if self.adam:\n self.dLdWsx_m = gamma1 * self.dLdWsx_m + (1 - gamma1) * dWsx\n self.dLdWo_m = gamma1 * self.dLdWo_m + (1 - gamma1) * dWo\n self.dLdWss_m = gamma1 * self.dLdWss_m + (1 - gamma1) * dWss\n self.dLdWo0_m = gamma1 * self.dLdWo0_m + (1 - gamma1) * dWo0\n self.dLdWss0_m = gamma1 * self.dLdWss0_m + (1 - gamma1) * dWss0\n\n self.dLdWsx_sq = gamma2 * self.dLdWsx_sq + (1 - gamma2) * dWsx ** 2\n self.dLdWo_sq = gamma2 * self.dLdWo_sq + (1 - gamma2) * dWo ** 2\n self.dLdWss_sq = gamma2 * self.dLdWss_sq + (1 - gamma2) * dWss ** 2\n self.dLdWo0_sq = gamma2 * self.dLdWo0_sq + (1 - gamma2) * dWo0 ** 2\n self.dLdWss0_sq = gamma2 * self.dLdWss0_sq + (1 - gamma2) * dWss0 ** 2\n\n # Correct for bias\n dLdWsx_mh = self.dLdWsx_m / (1 - gamma1**self.t)\n dLdWo_mh = self.dLdWo_m / (1 - gamma1**self.t)\n dLdWss_mh = self.dLdWss_m / (1 - gamma1**self.t)\n dLdWo0_mh = self.dLdWo0_m / (1 - gamma1**self.t)\n dLdWss0_mh = self.dLdWss0_m / (1 - gamma1**self.t)\n\n dLdWsx_sqh = self.dLdWsx_sq / (1 - gamma2**self.t)\n dLdWo_sqh = self.dLdWo_sq / (1 - gamma2**self.t)\n dLdWss_sqh = self.dLdWss_sq / (1 - gamma2**self.t)\n dLdWo0_sqh = self.dLdWo0_sq / (1 - gamma2**self.t)\n dLdWss0_sqh = self.dLdWss0_sq / (1 - gamma2**self.t)\n\n self.Wsx -= self.step_size * (dLdWsx_mh /\n (fudge + np.sqrt(dLdWsx_sqh)))\n self.Wss -= self.step_size * (dLdWss_mh /\n (fudge + np.sqrt(dLdWss_sqh)))\n self.Wo -= self.step_size * (dLdWo_mh /\n (fudge + np.sqrt(dLdWo_sqh)))\n self.Wss0 -= self.step_size * (dLdWss0_mh /\n (fudge + np.sqrt(dLdWss0_sqh)))\n self.Wo0 -= self.step_size * (dLdWo0_mh /\n (fudge + np.sqrt(dLdWo0_sqh)))\n else:\n self.Wsx -= self.step_size * dWsx\n self.Wss -= self.step_size * dWss\n self.Wo -= self.step_size * dWo\n self.Wss0 -= self.step_size * dWss0\n self.Wo0 -= self.step_size * dWo0\n\n def reset_hidden_state(self):\n self.hidden_state = self.init_state\n\n def forward_seq(self, x, y):\n k = x.shape[1]\n dLdZ2s = np.zeros((self.output_dim, k))\n states = np.zeros((self.hidden_dim, k))\n train_error = 0.0\n self.reset_hidden_state()\n for j in range(k):\n p, loss, dLdZ2 = self.forward_prop_loss(x[:, j:j+1], y[:, j:j+1])\n dLdZ2s[:, j:j+1] = dLdZ2\n states[:, j:j+1] = self.hidden_state\n train_error += loss\n return train_error/k, dLdZ2s, states\n\n # For now, training_seqs will be a list of pairs of np arrays.\n # First will be l x k second n x k where k is the sequence length\n # and can be different for each pair\n def train_seq_to_seq(self, training_seqs, steps = 100000,\n print_interval = None):\n if print_interval is None: print_interval = int(steps / 10)\n num_seqs = len(training_seqs)\n total_train_err = 0\n self.t = 0\n iters = 1\n for step in range(steps):\n i = np.random.randint(num_seqs)\n x, y = training_seqs[i]\n avg_seq_train_error, dLdZ2s, states = self.forward_seq(x, y)\n\n # Check the gradient computation against the numerical grad.\n # grads = self.b(x, dLdZ2s, states)\n # grads_n = self.num_grad(lambda : forward_seq(x, y, dLdZ2s,\n # states)[0])\n # compare_grads(grads, grads_n)\n\n self.sgd_step(x, dLdZ2s, states)\n total_train_err += avg_seq_train_error\n if (step % print_interval) == 0 and step > 0:\n print('%d/10: training error'%iters, total_train_err / print_interval, flush=True)\n total_train_err = 0\n iters += 1\n\n def num_grad(self, f, delta=0.001):\n out = []\n for W in (self.Wsx, self.Wss, self.Wo, self.Wss0, self.Wo0):\n Wn = np.zeros(W.shape)\n out.append(Wn)\n for i in range(W.shape[0]):\n for j in range(W.shape[1]):\n wi = W[i,j]\n W[i,j] = wi - delta\n fxm = f()\n W[i,j] = wi + delta\n fxp = f()\n W[i,j] = wi\n Wn[i,j] = (fxp - fxm)/(2*delta)\n return out\n\n # Return a state machine made out of these weights\n def sm(self):\n return sm.RNN(self.Wsx, self.Wss, self.Wo, self.Wss0, self.Wo0,\n self.f1, self.f2)\n\n # Assume that input and output are same dimension\n def gen_seq(self, init_sym, seq_len, codec):\n assert self.input_dim == self.output_dim\n assert self.f2 == softmax\n result = []\n self.reset_hidden_state()\n x = codec.encode(init_sym)\n for _ in range(seq_len):\n p = self.forward_propagation(x)\n x = np.array([np.random.multinomial(1, p.T[0])]).T\n if codec.decode(x) == '.':\n break\n result.append(codec.decode(x))\n return result\n\n def gen_seq_interactive(self, codec, seq_len = 100, maximize = True):\n self.reset_hidden_state()\n start = '.' + input('Starting string: ')\n result = start[1:]\n for c in start:\n p = self.forward_propagation(codec.encode(c))\n for _ in range(seq_len):\n c = codec.decode_max(p)\n #if c in ['.', '\\n', ' ']: break\n if c in ['.', '\\n']: break\n result = result + c\n x = codec.encode(c)\n p = self.forward_propagation(x)\n print(result)\n return result\n \n def gen_seq_interactive_top5(self, codec, seq_len = 100, maximize = True):\n self.reset_hidden_state()\n start = '.' + input('Starting string: ')\n result = start[1:]\n for c in start:\n p = self.forward_propagation(codec.encode(c))\n \n while True:\n c = codec.decode_max(p)\n #if c in ['.', '\\n', ' '] : break\n if c in ['.', '\\n']: break\n c_top5 = codec.decode_top5(p)\n #print(\"The argmax is :\", c)\n print(\"We recommend that you type one of the top 5 most frequent alphabets that follow '\" + str(result) + \"' : \", c_top5)\n next_character = input(\"Next character after '\" + str(result) + \"' : \")\n result = result + next_character\n x = codec.encode(next_character)\n p = self.forward_propagation(x)\n print(\"Your final result is : \", result)\n return result\n\ndef compare_grads(g, gn):\n names = ('Wsx', 'Wss', 'Wo', 'Wss0', 'Wo0')\n for i in range(len(g)):\n diff = np.max(np.abs(g[i]-gn[i]))\n if diff > 0.001:\n print('Diff in', names[i], 'is', diff)\n print('Analytical')\n print(g[i])\n print('Numerical')\n print(gn[i])\n input('Go?')\n\n############################################################################\n#\n# One-hot encoding/decoding\n#\n############################################################################\n\nclass OneHotCodec:\n def __init__(self, alphabet):\n pairs = list(enumerate(alphabet))\n self.n = len(pairs)\n self.coder = dict([(c, i) for (i, c) in pairs])\n self.decoder = dict(pairs)\n\n # Take a symbol, return a one-hot vector\n def encode(self, c):\n return self.encode_index(self.coder[c])\n\n # Take an index, return a one-hot vector\n def encode_index(self, i):\n v = np.zeros((self.n, 1))\n v[i, 0] = 1\n return v\n\n # Take a one-hot vector, return a symbol\n def decode(self, v):\n return self.decoder[int(np.nonzero(v)[0])]\n\n # Take a probability vector, return max likelihood symbol\n def decode_max(self, v):\n return self.decoder[np.argmax(v)]\n \n def decode_top5(self, v):\n v_viewed = v.reshape(v.shape[0])\n top5_args = np.argsort(v_viewed)[-5:][::-1].tolist()\n return [self.decoder[arg] for arg in top5_args]\n\n def encode_seq(self, cs):\n return np.hstack([self.encode(c) for c in cs])\n\n\nif __name__ == \"__main__\":\n # test_linear_accumulator()\n # test_word(\"abcabcabcabcabc\", interactive = False, num_hidden=3, num_steps=10000, step_size=0.005)\n # test_class_names(interactive=True, interactive_top5=False)\n #test_metal()\n # test_food()\n test_food(interactive = True, interactive_top5 = False, split=0, num_hidden = 150, num_steps = 20000, step_size = .001, train=False)\n ...\n" } ]
1
esershon/rock_paper_scissors
https://github.com/esershon/rock_paper_scissors
df6e8425535c0024d1c77ffb60ae8afd42e7ad55
e291ce43011aac40734878444e699e406f77dee3
f77f2e4e1162b7700c94d3161f0ea5d6e4e74572
refs/heads/master
2020-04-04T12:08:29.149108
2018-11-02T19:59:49
2018-11-02T19:59:49
155,915,621
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6362883448600769, "alphanum_fraction": 0.6396023035049438, "avg_line_length": 33.514286041259766, "blob_id": "e7c61f27e99b6f91eff26881c843d29aa424fde7", "content_id": "952b9bb6b349e5de2008c03d695b7d7a29d1d361", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1207, "license_type": "no_license", "max_line_length": 88, "num_lines": 35, "path": "/rpc.py", "repo_name": "esershon/rock_paper_scissors", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request, redirect, session\napp=Flask(__name__)\napp.secret_key = 'keep it secret, keep it safe'\nimport random\n\[email protected]('/')\ndef rockpaperscissors():\n return render_template('index.html')\n\nresults={'rock':{'paper':'lose', 'rock':'tie', 'scissors':'win'},\n'paper':{'paper': 'tie', 'rock' : 'win', 'scissors': 'lose'},\n'scissors':{'paper' : 'win', 'rock': 'lose', 'scissors': 'tie'}}\n\n \ndef random_weapon():\n weapons=['rock', 'paper', 'scissors']\n print(\"random is working\")\n return weapons[random.randint(0,2)]\n\[email protected]('/results', methods= ['POST'])\ndef playthegame():\n # weapon_from_form = request.form['weapon']\n # computer_choice=random_weapon()\n # winner = results[weapon_from_form][computer_choice]\n session['weapon_from_form'] = request.form['weapon']\n session['computer_weapon']=random_weapon()\n session['winner'] = results[session['weapon_from_form']][session['computer_weapon']]\n count = 0\n if session['winner'] == 'win'\n count = count +1\n return redirect('/')\n # , winner=winner, computer_weapon=computer_choice, user_weapon=weapon_from_form\n\nif __name__==\"__main__\":\n app.run(debug=True)" } ]
1
AFakeman/pushover-notify
https://github.com/AFakeman/pushover-notify
6f0b1e519be1e827ac6473d0e327978e274afa65
5ab1d14ed6b4788ab90d72ccb00451f34ee02939
aa7ce42de802a57de54a0128e993cbeae929e537
refs/heads/master
2020-04-03T16:02:03.310323
2018-10-30T13:17:37
2018-10-30T13:17:37
155,388,154
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7369726896286011, "alphanum_fraction": 0.7369726896286011, "avg_line_length": 22.02857208251953, "blob_id": "09696b959cc13b78dc7fda3121253aa06a20b800", "content_id": "5c09906c64df7f10788dcb2b9d5a43172e72d819", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 806, "license_type": "no_license", "max_line_length": 79, "num_lines": 35, "path": "/README.md", "repo_name": "AFakeman/pushover-notify", "src_encoding": "UTF-8", "text": "# pushover-notify - A tool to get push notified from shell\n\n## Usage\n\nThe package provides two commands: pushover and pushover\\_exec\n\n### Configuration\n\nConfiguration file should be placed in `${XDG_CONFIG_HOME}/pushover.json`.\nCurrently there are only two settings:\n\n apiKey - the pushover api key\n defaultClient (optional) - the default client to send notifications to\n\nNote that if the client is not provided to the pushover command the script will\nnot work.\n\n### pushover\n\nUsage:\n\n pushover -t <title> -m <message> -c <client>\n\nSends a push notification with `<message>`, `<title>` to the `<client>`.\nClient and title are optional.\n\n\n### pushover\\_exec\n\nUsage:\n\n pushover_exec some_command\n\nExecutes `some_command`, piping its output to both stdout and notifications to\nthe `defaultClient`\n" }, { "alpha_fraction": 0.6137229800224304, "alphanum_fraction": 0.6213468909263611, "avg_line_length": 30.479999542236328, "blob_id": "54bf2d8ec835500ea95fa63806cf113fbb314522", "content_id": "f131aa721faa7222fffd3f581bef92f456dba5cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 787, "license_type": "no_license", "max_line_length": 68, "num_lines": 25, "path": "/setup.py", "repo_name": "AFakeman/pushover-notify", "src_encoding": "UTF-8", "text": "import setuptools\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name='pushover-notify',\n version='0.1.0',\n scripts=['pushover', 'pushover_exec'] ,\n author=\"Anton Suslov\",\n author_email=\"[email protected]\",\n description=\"CLI interface for sending Pushover notifications\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/afakeman/pushover-notify\",\n packages=setuptools.find_packages(),\n install_requires=[\n \"requests\",\n ],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.7\",\n \"License :: Other/Propietary License\",\n \"Operating System :: OS Independent\",\n ],\n )\n" }, { "alpha_fraction": 0.5214285850524902, "alphanum_fraction": 0.5285714268684387, "avg_line_length": 16.5, "blob_id": "e400e498340b82eb8b5e503165394ccbd401ead7", "content_id": "c751b0ed6fe79d592fab5590ed80e96eedbfb37e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 140, "license_type": "no_license", "max_line_length": 46, "num_lines": 8, "path": "/pushover_exec", "repo_name": "AFakeman/pushover-notify", "src_encoding": "UTF-8", "text": "#! env sh\n\nARGS=\"$@\"\nif [ $# -eq 0 ]; then\n echo \"Usage: pushover_exec <command>\"\nelse\n \"$@\" | tee /dev/tty | pushover -t \"$ARGS\";\nfi\n" }, { "alpha_fraction": 0.6677140593528748, "alphanum_fraction": 0.6692851781845093, "avg_line_length": 22.574073791503906, "blob_id": "147fd0bedf074aae72645291ad5ba478514cf3bf", "content_id": "7964ac7d86c80144bc266e94e6cd39d3dd43e344", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1273, "license_type": "no_license", "max_line_length": 95, "num_lines": 54, "path": "/pushover", "repo_name": "AFakeman/pushover-notify", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python3\n\nimport requests\nimport sys\nimport argparse\nimport json\n\nimport os\n\nconfig_dir = os.environ.get('XDG_CONFIG_HOME', '~/.config')\n\nAPI_HANDLE = 'https://api.pushover.net/1/messages.json'\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-t', '--title', dest='title', help='title')\nparser.add_argument('-m', '--message', dest='message', help='message', nargs='+')\nparser.add_argument('-v', '--verbose', dest='verbose',\n help='print server response', nargs='+')\nparser.add_argument('-c', '--client', dest='client', help='client to send the notification to')\n\nnamespace = parser.parse_args()\n\nwith open(os.path.join(config_dir, 'pushover.json')) as f:\n config = json.load(f)\n\napi_key = config['apiKey']\nif namespace.client:\n client = namespace.client\nelse:\n client = config['defaultClient']\n\nif namespace.message:\n message = \" \".join(namespace.message)\nelse:\n message = sys.stdin.read().strip()\n\ndata = {\n 'token': api_key,\n 'user': client,\n 'message': message,\n}\n\nif namespace.title:\n data['title'] = namespace.title\n\nreq = requests.post(API_HANDLE, json=data)\n\nif namespace.verbose:\n print(req.json(), file=sys.stderr)\ntry:\n req.raise_for_status()\nexcept:\n print(req.json(), file=sys.stderr)\n raise\n" } ]
4
CursosIE/IE-0217-II-16-G2
https://github.com/CursosIE/IE-0217-II-16-G2
584910d81adc0ca93296b7fcc77436ae82ad792b
d6d845d9305bd2097cba3272d1b904fabdf20629
ff946f2ad02c6c58b7556a282c5f6be374a39850
refs/heads/master
2020-04-11T10:51:13.386554
2016-12-05T06:16:54
2016-12-05T06:16:54
68,146,882
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.484375, "alphanum_fraction": 0.6979166865348816, "avg_line_length": 47, "blob_id": "f9b90c018811997facfc19aae39d800b40068586", "content_id": "c59f45dd92e5183399e8720e23a6546e89dd9a54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 192, "license_type": "no_license", "max_line_length": 170, "num_lines": 4, "path": "/Lab 3/Documentacion/html/search/functions_3.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['poly',['Poly',['../class_poly.html#aa3def076b74bed67904976ad4f9fe9b1',1,'Poly::Poly()'],['../class_poly.html#a7a346680adff050d4876f9e979cb6f69',1,'Poly::Poly(int)']]]\n];\n" }, { "alpha_fraction": 0.7094594836235046, "alphanum_fraction": 0.7094594836235046, "avg_line_length": 15.333333015441895, "blob_id": "01b6b03cc2d31b49c919d8295f4c955c399dd73f", "content_id": "b832d3367032f44e4df1b3661928d74e24cd9e3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 148, "license_type": "no_license", "max_line_length": 63, "num_lines": 9, "path": "/Lab 2/Makefile", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "compilar: \n\tg++ main.cpp Circulo.cpp Cuadrado.cpp Figura.cpp Triangulo.cpp\n\nclean: \n\trm a.out\n\nejecutar: \n\techo \"Generador de figuritas\" \n\t./a.out \n" }, { "alpha_fraction": 0.5889872312545776, "alphanum_fraction": 0.6355041265487671, "avg_line_length": 46.557552337646484, "blob_id": "33beb503068ac28853c624bfcf0f9fe8b077154e", "content_id": "1bcbafda72e17c8a025ffc315b171b6dee27e449", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 13224, "license_type": "no_license", "max_line_length": 985, "num_lines": 278, "path": "/Proyecto I/Ms/html/mergesort_8cpp.html", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/xhtml;charset=UTF-8\"/>\n<meta http-equiv=\"X-UA-Compatible\" content=\"IE=9\"/>\n<meta name=\"generator\" content=\"Doxygen 1.8.11\"/>\n<title>Mergesort: mergesort.cpp File Reference</title>\n<link href=\"tabs.css\" rel=\"stylesheet\" type=\"text/css\"/>\n<script type=\"text/javascript\" src=\"jquery.js\"></script>\n<script type=\"text/javascript\" src=\"dynsections.js\"></script>\n<link href=\"search/search.css\" rel=\"stylesheet\" type=\"text/css\"/>\n<script type=\"text/javascript\" src=\"search/searchdata.js\"></script>\n<script type=\"text/javascript\" src=\"search/search.js\"></script>\n<script type=\"text/javascript\">\n $(document).ready(function() { init_search(); });\n</script>\n<link href=\"doxygen.css\" rel=\"stylesheet\" type=\"text/css\" />\n</head>\n<body>\n<div id=\"top\"><!-- do not remove this div, it is closed by doxygen! -->\n<div id=\"titlearea\">\n<table cellspacing=\"0\" cellpadding=\"0\">\n <tbody>\n <tr style=\"height: 56px;\">\n <td id=\"projectalign\" style=\"padding-left: 0.5em;\">\n <div id=\"projectname\">Mergesort\n </div>\n </td>\n </tr>\n </tbody>\n</table>\n</div>\n<!-- end header part -->\n<!-- Generated by Doxygen 1.8.11 -->\n<script type=\"text/javascript\">\nvar searchBox = new SearchBox(\"searchBox\", \"search\",false,'Search');\n</script>\n <div id=\"navrow1\" class=\"tabs\">\n <ul class=\"tablist\">\n <li><a href=\"index.html\"><span>Main&#160;Page</span></a></li>\n <li class=\"current\"><a href=\"files.html\"><span>Files</span></a></li>\n <li>\n <div id=\"MSearchBox\" class=\"MSearchBoxInactive\">\n <span class=\"left\">\n <img id=\"MSearchSelect\" src=\"search/mag_sel.png\"\n onmouseover=\"return searchBox.OnSearchSelectShow()\"\n onmouseout=\"return searchBox.OnSearchSelectHide()\"\n alt=\"\"/>\n <input type=\"text\" id=\"MSearchField\" value=\"Search\" accesskey=\"S\"\n onfocus=\"searchBox.OnSearchFieldFocus(true)\" \n onblur=\"searchBox.OnSearchFieldFocus(false)\" \n onkeyup=\"searchBox.OnSearchFieldChange(event)\"/>\n </span><span class=\"right\">\n <a id=\"MSearchClose\" href=\"javascript:searchBox.CloseResultsWindow()\"><img id=\"MSearchCloseImg\" border=\"0\" src=\"search/close.png\" alt=\"\"/></a>\n </span>\n </div>\n </li>\n </ul>\n </div>\n <div id=\"navrow2\" class=\"tabs2\">\n <ul class=\"tablist\">\n <li><a href=\"files.html\"><span>File&#160;List</span></a></li>\n <li><a href=\"globals.html\"><span>File&#160;Members</span></a></li>\n </ul>\n </div>\n<!-- window showing the filter options -->\n<div id=\"MSearchSelectWindow\"\n onmouseover=\"return searchBox.OnSearchSelectShow()\"\n onmouseout=\"return searchBox.OnSearchSelectHide()\"\n onkeydown=\"return searchBox.OnSearchSelectKey(event)\">\n</div>\n\n<!-- iframe showing the search results (closed by default) -->\n<div id=\"MSearchResultsWindow\">\n<iframe src=\"javascript:void(0)\" frameborder=\"0\" \n name=\"MSearchResults\" id=\"MSearchResults\">\n</iframe>\n</div>\n\n</div><!-- top -->\n<div class=\"header\">\n <div class=\"summary\">\n<a href=\"#func-members\">Functions</a> </div>\n <div class=\"headertitle\">\n<div class=\"title\">mergesort.cpp File Reference</div> </div>\n</div><!--header-->\n<div class=\"contents\">\n<div class=\"textblock\"><code>#include &lt;cstdlib&gt;</code><br />\n<code>#include &quot;head.h&quot;</code><br />\n</div><table class=\"memberdecls\">\n<tr class=\"heading\"><td colspan=\"2\"><h2 class=\"groupheader\"><a name=\"func-members\"></a>\nFunctions</h2></td></tr>\n<tr class=\"memitem:a11d3bcfd90f8bd0e9a365650a5fb929f\"><td class=\"memItemLeft\" align=\"right\" valign=\"top\">int *&#160;</td><td class=\"memItemRight\" valign=\"bottom\"><a class=\"el\" href=\"mergesort_8cpp.html#a11d3bcfd90f8bd0e9a365650a5fb929f\">merge</a> (int a[], int beg, int end, int mid)</td></tr>\n<tr class=\"memdesc:a11d3bcfd90f8bd0e9a365650a5fb929f\"><td class=\"mdescLeft\">&#160;</td><td class=\"mdescRight\">Funcion la cual recibe el arreglo y por medio de dos contadores a cada lado del arreglo al terminar su ejecucion deja el arreglo original a ordenado. Funcion recibe un arreglo a el cual por medio de dos contadores uno a la izquierda y otro a la derecha se recorre el arreglo por ambos lados revisando que los valores del lado izquierdo deben ser menores a los del lado derecho. Luego cuando ambos contadores de juntan se revisa si la variable ini la cual simboliza la cantidad de elementos que ya fueron menores al lado derecho es mayor al valor mid; si esto sucede significa que todos los elementos del lado derecho fueron menores a los del izquier y solo faltan copiar los valores de ini hasta end. Faltan copiar el resto de elementos sobre el arreglo result, de forma similar si ini es menor a mid. <a href=\"#a11d3bcfd90f8bd0e9a365650a5fb929f\">More...</a><br /></td></tr>\n<tr class=\"separator:a11d3bcfd90f8bd0e9a365650a5fb929f\"><td class=\"memSeparator\" colspan=\"2\">&#160;</td></tr>\n<tr class=\"memitem:ac50541a527e434941a6f8550799dfb1b\"><td class=\"memItemLeft\" align=\"right\" valign=\"top\">void&#160;</td><td class=\"memItemRight\" valign=\"bottom\"><a class=\"el\" href=\"mergesort_8cpp.html#ac50541a527e434941a6f8550799dfb1b\">imprimir</a> (int p[], int size)</td></tr>\n<tr class=\"separator:ac50541a527e434941a6f8550799dfb1b\"><td class=\"memSeparator\" colspan=\"2\">&#160;</td></tr>\n<tr class=\"memitem:a977e301d320602d41a3ffefec4cd366b\"><td class=\"memItemLeft\" align=\"right\" valign=\"top\">int *&#160;</td><td class=\"memItemRight\" valign=\"bottom\"><a class=\"el\" href=\"mergesort_8cpp.html#a977e301d320602d41a3ffefec4cd366b\">sort</a> (int a[], int beg, int end)</td></tr>\n<tr class=\"memdesc:a977e301d320602d41a3ffefec4cd366b\"><td class=\"mdescLeft\">&#160;</td><td class=\"mdescRight\">Funcion la llama la funcion sort sobre ambas mitades del arreglo de forma recursiva hasta tener un arreglo de tamaño 1. <a href=\"#a977e301d320602d41a3ffefec4cd366b\">More...</a><br /></td></tr>\n<tr class=\"separator:a977e301d320602d41a3ffefec4cd366b\"><td class=\"memSeparator\" colspan=\"2\">&#160;</td></tr>\n<tr class=\"memitem:a8f6a43f29b08c4a635f8d8ab239f3fcb\"><td class=\"memItemLeft\" align=\"right\" valign=\"top\">double&#160;</td><td class=\"memItemRight\" valign=\"bottom\"><a class=\"el\" href=\"mergesort_8cpp.html#a8f6a43f29b08c4a635f8d8ab239f3fcb\">get_CPU_time_usage</a> (clock_t clock1, clock_t clock2)</td></tr>\n<tr class=\"separator:a8f6a43f29b08c4a635f8d8ab239f3fcb\"><td class=\"memSeparator\" colspan=\"2\">&#160;</td></tr>\n<tr class=\"memitem:a3c04138a5bfe5d72780bb7e82a18e627\"><td class=\"memItemLeft\" align=\"right\" valign=\"top\"><a class=\"anchor\" id=\"a3c04138a5bfe5d72780bb7e82a18e627\"></a>\nint&#160;</td><td class=\"memItemRight\" valign=\"bottom\"><b>main</b> (int argc, char **argv)</td></tr>\n<tr class=\"separator:a3c04138a5bfe5d72780bb7e82a18e627\"><td class=\"memSeparator\" colspan=\"2\">&#160;</td></tr>\n</table>\n<a name=\"details\" id=\"details\"></a><h2 class=\"groupheader\">Detailed Description</h2>\n<div class=\"textblock\"><dl class=\"section author\"><dt>Author</dt><dd>Jose Alberto Barrantes B50881 Alejandro Cedeño B41672 </dd></dl>\n</div><h2 class=\"groupheader\">Function Documentation</h2>\n<a class=\"anchor\" id=\"a8f6a43f29b08c4a635f8d8ab239f3fcb\"></a>\n<div class=\"memitem\">\n<div class=\"memproto\">\n <table class=\"memname\">\n <tr>\n <td class=\"memname\">double get_CPU_time_usage </td>\n <td>(</td>\n <td class=\"paramtype\">clock_t&#160;</td>\n <td class=\"paramname\"><em>clock1</em>, </td>\n </tr>\n <tr>\n <td class=\"paramkey\"></td>\n <td></td>\n <td class=\"paramtype\">clock_t&#160;</td>\n <td class=\"paramname\"><em>clock2</em>&#160;</td>\n </tr>\n <tr>\n <td></td>\n <td>)</td>\n <td></td><td></td>\n </tr>\n </table>\n</div><div class=\"memdoc\">\n<p>Funcion utlizada para obtener el tiempo de procesamiento en milisegundos. </p><dl class=\"params\"><dt>Parameters</dt><dd>\n <table class=\"params\">\n <tr><td class=\"paramname\">clock1</td><td>Tiempo inicial </td></tr>\n <tr><td class=\"paramname\">clock2</td><td>Tiempo final </td></tr>\n </table>\n </dd>\n</dl>\n<dl class=\"section return\"><dt>Returns</dt><dd>returna la diferencia de final-inicial. </dd></dl>\n\n</div>\n</div>\n<a class=\"anchor\" id=\"ac50541a527e434941a6f8550799dfb1b\"></a>\n<div class=\"memitem\">\n<div class=\"memproto\">\n <table class=\"memname\">\n <tr>\n <td class=\"memname\">void imprimir </td>\n <td>(</td>\n <td class=\"paramtype\">int&#160;</td>\n <td class=\"paramname\"><em>p</em>[], </td>\n </tr>\n <tr>\n <td class=\"paramkey\"></td>\n <td></td>\n <td class=\"paramtype\">int&#160;</td>\n <td class=\"paramname\"><em>size</em>&#160;</td>\n </tr>\n <tr>\n <td></td>\n <td>)</td>\n <td></td><td></td>\n </tr>\n </table>\n</div><div class=\"memdoc\">\n<p>Funcion para imprimir el arreglo. </p><dl class=\"params\"><dt>Parameters</dt><dd>\n <table class=\"params\">\n <tr><td class=\"paramname\">p</td><td>Arreglo </td></tr>\n <tr><td class=\"paramname\">size</td><td>Tamaño de este </td></tr>\n </table>\n </dd>\n</dl>\n\n</div>\n</div>\n<a class=\"anchor\" id=\"a11d3bcfd90f8bd0e9a365650a5fb929f\"></a>\n<div class=\"memitem\">\n<div class=\"memproto\">\n <table class=\"memname\">\n <tr>\n <td class=\"memname\">int* merge </td>\n <td>(</td>\n <td class=\"paramtype\">int&#160;</td>\n <td class=\"paramname\"><em>a</em>[], </td>\n </tr>\n <tr>\n <td class=\"paramkey\"></td>\n <td></td>\n <td class=\"paramtype\">int&#160;</td>\n <td class=\"paramname\"><em>beg</em>, </td>\n </tr>\n <tr>\n <td class=\"paramkey\"></td>\n <td></td>\n <td class=\"paramtype\">int&#160;</td>\n <td class=\"paramname\"><em>end</em>, </td>\n </tr>\n <tr>\n <td class=\"paramkey\"></td>\n <td></td>\n <td class=\"paramtype\">int&#160;</td>\n <td class=\"paramname\"><em>mid</em>&#160;</td>\n </tr>\n <tr>\n <td></td>\n <td>)</td>\n <td></td><td></td>\n </tr>\n </table>\n</div><div class=\"memdoc\">\n\n<p>Funcion la cual recibe el arreglo y por medio de dos contadores a cada lado del arreglo al terminar su ejecucion deja el arreglo original a ordenado. Funcion recibe un arreglo a el cual por medio de dos contadores uno a la izquierda y otro a la derecha se recorre el arreglo por ambos lados revisando que los valores del lado izquierdo deben ser menores a los del lado derecho. Luego cuando ambos contadores de juntan se revisa si la variable ini la cual simboliza la cantidad de elementos que ya fueron menores al lado derecho es mayor al valor mid; si esto sucede significa que todos los elementos del lado derecho fueron menores a los del izquier y solo faltan copiar los valores de ini hasta end. Faltan copiar el resto de elementos sobre el arreglo result, de forma similar si ini es menor a mid. </p>\n<dl class=\"params\"><dt>Parameters</dt><dd>\n <table class=\"params\">\n <tr><td class=\"paramname\">a</td><td>Arreglo a ordenar. </td></tr>\n <tr><td class=\"paramname\">beg</td><td>Indice de inicio del arreglo. </td></tr>\n <tr><td class=\"paramname\">end</td><td>Indice de final del arreglo. </td></tr>\n <tr><td class=\"paramname\">mid</td><td>Indice punto medio del arreglo </td></tr>\n </table>\n </dd>\n</dl>\n<dl class=\"section return\"><dt>Returns</dt><dd>0 para decir que todo salio bien. </dd></dl>\n\n</div>\n</div>\n<a class=\"anchor\" id=\"a977e301d320602d41a3ffefec4cd366b\"></a>\n<div class=\"memitem\">\n<div class=\"memproto\">\n <table class=\"memname\">\n <tr>\n <td class=\"memname\">int* sort </td>\n <td>(</td>\n <td class=\"paramtype\">int&#160;</td>\n <td class=\"paramname\"><em>a</em>[], </td>\n </tr>\n <tr>\n <td class=\"paramkey\"></td>\n <td></td>\n <td class=\"paramtype\">int&#160;</td>\n <td class=\"paramname\"><em>beg</em>, </td>\n </tr>\n <tr>\n <td class=\"paramkey\"></td>\n <td></td>\n <td class=\"paramtype\">int&#160;</td>\n <td class=\"paramname\"><em>end</em>&#160;</td>\n </tr>\n <tr>\n <td></td>\n <td>)</td>\n <td></td><td></td>\n </tr>\n </table>\n</div><div class=\"memdoc\">\n\n<p>Funcion la llama la funcion sort sobre ambas mitades del arreglo de forma recursiva hasta tener un arreglo de tamaño 1. </p>\n<dl class=\"params\"><dt>Parameters</dt><dd>\n <table class=\"params\">\n <tr><td class=\"paramname\">a</td><td>Arreglo a ordenar </td></tr>\n <tr><td class=\"paramname\">beg</td><td>Indice de inicio del arreglo (usualmente 0) </td></tr>\n <tr><td class=\"paramname\">end</td><td>Indice de final </td></tr>\n </table>\n </dd>\n</dl>\n<dl class=\"section return\"><dt>Returns</dt><dd></dd></dl>\n\n</div>\n</div>\n</div><!-- contents -->\n<!-- start footer part -->\n<hr class=\"footer\"/><address class=\"footer\"><small>\nGenerated by &#160;<a href=\"http://www.doxygen.org/index.html\">\n<img class=\"footer\" src=\"doxygen.png\" alt=\"doxygen\"/>\n</a> 1.8.11\n</small></address>\n</body>\n</html>\n" }, { "alpha_fraction": 0.5234375, "alphanum_fraction": 0.71875, "avg_line_length": 31, "blob_id": "fb32bf5b9628814fcfb00fb699f777cca7aa27c9", "content_id": "0c1e874023802848c2e2bc41b7f373b4d49be927", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 128, "license_type": "no_license", "max_line_length": 106, "num_lines": 4, "path": "/Lab 5/html/search/all_d.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['refill',['refill',['../classpila_de_cartas.html#a456bcaa53157a7552296286bf59a7863',1,'pilaDeCartas']]]\n];\n" }, { "alpha_fraction": 0.5759999752044678, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 30.25, "blob_id": "111da56652debedf785bdfbb76bb87dfacf248f2", "content_id": "93ccc964416ac738682dfdaace987bcd71b14af0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 125, "license_type": "no_license", "max_line_length": 103, "num_lines": 4, "path": "/Lab 2/Documentacion/html/search/all_6.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['perimetro',['Perimetro',['../class_cuadrado.html#aa1b3dceb0c4ecfe7680f459c635e6d28',1,'Cuadrado']]]\n];\n" }, { "alpha_fraction": 0.529411792755127, "alphanum_fraction": 0.7287581562995911, "avg_line_length": 75.5, "blob_id": "5864de418be50e371331eccfc95c08a6b3bdf988", "content_id": "8eda588fc25c4158f3219e9b4744c761fdf510d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 306, "license_type": "no_license", "max_line_length": 284, "num_lines": 4, "path": "/Lab 3/Documentacion/html/search/functions_1.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['matrix',['Matrix',['../class_matrix.html#a2dba13c45127354c9f75ef576f49269b',1,'Matrix::Matrix()'],['../class_matrix.html#aeca1d0c59b90eefc898960928486fb5f',1,'Matrix::Matrix(int, int, int)'],['../class_matrix.html#adfbeb67cc3c43d96c53f881d79f919cb',1,'Matrix::Matrix(int, int)']]]\n];\n" }, { "alpha_fraction": 0.6589147448539734, "alphanum_fraction": 0.6589147448539734, "avg_line_length": 11.699999809265137, "blob_id": "6cbf3fd31b3280e60d142671840691367a3d4db0", "content_id": "f5f9c9f13fb1443e1213090338124c0644583f80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 129, "license_type": "no_license", "max_line_length": 19, "num_lines": 10, "path": "/Proyecto I/Qs/head.h", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "\n#include <iostream>\n#include <cmath>\n#include <time.h>\n#include <fstream>\n#ifndef HEAD_H\n#define HEAD_H\n\n\n\n#endif /* HEAD_H */\n\n" }, { "alpha_fraction": 0.3181818127632141, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 22, "blob_id": "987a5733b091a7fd3f80812b709fa2a622bcf5fb", "content_id": "b1e193f7fc8fa34619f970a2742a8c1b009b86f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 22, "license_type": "no_license", "max_line_length": 22, "num_lines": 1, "path": "/Lab 0/README.md", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "# IE-0217-I-16-Lab0-G2" }, { "alpha_fraction": 0.5249999761581421, "alphanum_fraction": 0.699999988079071, "avg_line_length": 29, "blob_id": "3e526032a2b6c72ca3290511e88ac0313c574bb3", "content_id": "5199c0ad596ff564edcb0242e29c2bb6bf7a82e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 120, "license_type": "no_license", "max_line_length": 98, "num_lines": 4, "path": "/Proyecto I/Ms/html/search/functions_3.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['sort',['sort',['../mergesort_8cpp.html#a977e301d320602d41a3ffefec4cd366b',1,'mergesort.cpp']]]\n];\n" }, { "alpha_fraction": 0.5677965879440308, "alphanum_fraction": 0.7118644118309021, "avg_line_length": 28.5, "blob_id": "55a0a71ed6cadd66d719dc514210d3ee8ebcc8bb", "content_id": "297f8ba76426d952d169e818295a8086da58586e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 118, "license_type": "no_license", "max_line_length": 96, "num_lines": 4, "path": "/Lab 5/html/search/functions_5.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['getcard',['getCard',['../classjugador.html#a94d2eaddaaac69ce42933c9da20d40e5',1,'jugador']]]\n];\n" }, { "alpha_fraction": 0.6037735939025879, "alphanum_fraction": 0.6132075190544128, "avg_line_length": 10.666666984558105, "blob_id": "e2fde4bdb333090ce28c37891677a8e3bf7c0a99", "content_id": "b80e5445743fda63532ccfba73331012af0f3c13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 106, "license_type": "no_license", "max_line_length": 32, "num_lines": 9, "path": "/Lab 1/Makefile", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "compilar: \n\tg++ Lab1.cc \n\nclean: \n\trm a.out\n\nejecutar: \n\techo \"Traductor de cadena ARN\" \n\t./a.out $(ARG) \n" }, { "alpha_fraction": 0.48235294222831726, "alphanum_fraction": 0.6176470518112183, "avg_line_length": 33, "blob_id": "75dfdf023c51b77be05a41bdfae1975d7be5d492", "content_id": "24bd7c45a1d1fb5eb133420d69833f80571d47cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 170, "license_type": "no_license", "max_line_length": 90, "num_lines": 5, "path": "/Lab 0/C++/html/search/all_1.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['suma_2ecpp',['suma.cpp',['../suma_8cpp.html',1,'']]],\n ['sumar',['sumar',['../suma_8cpp.html#acda09b8c72ceee96283ce32e936a8f62',1,'suma.cpp']]]\n];\n" }, { "alpha_fraction": 0.5244956612586975, "alphanum_fraction": 0.6570605039596558, "avg_line_length": 48.57143020629883, "blob_id": "0af5d283d2c68df2dce0497b839f5259adb57c88", "content_id": "a194f4dee6016aec6f89a86e772d1687c531cd30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 347, "license_type": "no_license", "max_line_length": 112, "num_lines": 7, "path": "/Lab 5/html/search/all_1.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['card',['Card',['../class_card.html',1,'']]],\n ['casino_2ecpp',['casino.cpp',['../casino_8cpp.html',1,'']]],\n ['correrjuego',['correrJuego',['../classmesa.html#a895972e154fb043837bf1b0928e0ad52',1,'mesa']]],\n ['crearjugadores',['crearJugadores',['../casino_8cpp.html#ab761d9c4daed56ca16c540bcf96a3bc5',1,'casino.cpp']]]\n];\n" }, { "alpha_fraction": 0.4636363685131073, "alphanum_fraction": 0.6727272868156433, "avg_line_length": 26.5, "blob_id": "9fae933c6523c78cd2914120a27410aa7852d356", "content_id": "9a9ee59dffc8fc63464b346148c5efc10ccaf699", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 110, "license_type": "no_license", "max_line_length": 88, "num_lines": 4, "path": "/Lab 0/C++/html/search/all_0.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['main',['main',['../suma_8cpp.html#a3c04138a5bfe5d72780bb7e82a18e627',1,'suma.cpp']]]\n];\n" }, { "alpha_fraction": 0.5968284606933594, "alphanum_fraction": 0.6102834939956665, "avg_line_length": 24.036144256591797, "blob_id": "9bf4148ecd1a4b8fc1c9870e90a2c3ffd0f67b49", "content_id": "0ec9bf098c4195c8b524f9a0be88c68ac3ce5273", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2081, "license_type": "no_license", "max_line_length": 86, "num_lines": 83, "path": "/Lab 2/Circulo.cpp", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "\n\n/* \n * @File: Circulo.cpp\n * @author: jose\n * \n * @date September 6, 2016\n * \n */\n#include \"Circulo.h\"\n\nconst double PI =3.141592653589793238463;\n/**\n * @brief Me crea un circulo de radio ingresado por el usuario\n * @param rad Valor del radio ingresado por el usuario\n */\nCirculo::Circulo() {\n double rad;\n this->color = \"Blanco\";\n this->nombre = \"Marco Polo\";\n std::cout << \"Ingrese el radio del circulo:\" << std::endl;\n std::cin >> rad;\n this->radio = rad;\n}\n/**\n * @brief Me crea una circulo con nombre y color ingresado por el usuario\n * @code \n * this->color = b;\n * this->nombre = a;\n * @param a nomre del circulo\n * @param b Color del circulo.\n */\nCirculo::Circulo(std::string a , std::string b) {\n double rad;\n this->color = b;\n this->nombre = a;\n std::cout << \"Ingrese el radio del circulo:\" << std::endl;\n std::cin >> rad;\n this->radio = rad;\n}\n\nCirculo::Circulo(const Circulo& orig) {\n}\n/**\n * @brief Calcula el perimetro de un circulo\n * @param Per perimetro del circulo\n */\nvoid Circulo::Perimetro() {\n double Per = 2*PI*this->radio;\n this->perimetro = Per;\n \n}\n/**\n * @brief Muestra los atributos de cada circulo\n * @return Informacion de los atributos\n */\nvoid * Circulo::operator ~() {\n \n \n std::cout << \"El nombre del circulo es: \" << this->nombre << std::endl;\n std::cout << \"El color de \" << this->nombre << \" es \" << this->color << std::endl;\n std::cout << \"El largo del radio de este es: \" << this->radio << std::endl;\n}\n/**\n * @brief Informacion del calculo del area y perimetro del circulo\n * @return Informacion de los calculos\n */\n\nvoid * Circulo::operator !() {\n Circulo::Area();\n Circulo::Perimetro();\n std::cout << \"El area del circulo es: \" << this->area << std::endl;\n std::cout << \"El perimetro del circulo es: \" << this->perimetro << std::endl;\n}\n/**\n * @brief Calcula el area del circulo\n * @param area Guarda el resultado del area del circulo\n */\nvoid Circulo::Area() {\n double area = PI * (this->radio*this->radio);\n this->area = area;\n}\n\nCirculo::~Circulo() {\n}\n\n" }, { "alpha_fraction": 0.5779221057891846, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 37.5, "blob_id": "2629dbb587c107a341ab2b3b9bd45dcd9b803c44", "content_id": "f6c6622f903f4bc4fc4ebc029a6ca8d5ab29b692", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 154, "license_type": "no_license", "max_line_length": 132, "num_lines": 4, "path": "/Proyecto I/Ms/html/search/all_0.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['get_5fcpu_5ftime_5fusage',['get_CPU_time_usage',['../mergesort_8cpp.html#a8f6a43f29b08c4a635f8d8ab239f3fcb',1,'mergesort.cpp']]]\n];\n" }, { "alpha_fraction": 0.6233766078948975, "alphanum_fraction": 0.649350643157959, "avg_line_length": 14.199999809265137, "blob_id": "597f0bf8a24ecaed2e5d0ce2f84ab4a154b18133", "content_id": "f98f97885d2d2290a5924d84a70031ee08006d25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 77, "license_type": "no_license", "max_line_length": 45, "num_lines": 5, "path": "/Proyecto2/Makefile", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "install: \n\tg++ -std=c++11 Cadena.cpp main.cpp -o Cadena\n\nclean: \n\trm Cadena\n\n" }, { "alpha_fraction": 0.5864406824111938, "alphanum_fraction": 0.7355931997299194, "avg_line_length": 72.75, "blob_id": "497aaa0d424560b5f01a011ed32edb99dd43a690", "content_id": "7a58c50ae580d6ab18b01d7672b7aec9ab52b0ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 295, "license_type": "no_license", "max_line_length": 273, "num_lines": 4, "path": "/Lab 2/Documentacion/html/search/all_7.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['triangulo',['Triangulo',['../class_triangulo.html',1,'Triangulo'],['../class_triangulo.html#a905d421bd19655a979ccad9e2998db0c',1,'Triangulo::Triangulo()'],['../class_triangulo.html#aa56f00477a32f8c6465b2b7256fdd7d0',1,'Triangulo::Triangulo(std::string, std::string)']]]\n];\n" }, { "alpha_fraction": 0.3650871217250824, "alphanum_fraction": 0.3829995095729828, "avg_line_length": 22.353612899780273, "blob_id": "f994ddcdc1a65d4bebf8fe819dfaa5a9bda37410", "content_id": "daeb84c8d63596d72646453f49a40ac0a08a22bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6141, "license_type": "no_license", "max_line_length": 79, "num_lines": 263, "path": "/Proyecto2/Cadena.cpp", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\n\n/* \n * File: Cadena.cpp\n * Author: jose\n * \n * Created on November 19, 2016, 9:37 PM\n */\n\n#include \"Cadena.h\"\n\nCadena::Cadena() {\n \n}\n\nCadena::Cadena(int size) {\n MP = new double*[size];\n for (int i=0; i < size ; i++) {\n MP[i] = new double[4];\n for (int j=0; j < 4 ; j++) {\n MP[i][j] = 0;\n }\n }\n longitud = size;\n \n}\n\nCadena::Cadena(std::string in) {\n int i;\n longitud = in.length();\n ADN = in;\n MP = new double*[in.length()];\n for (int i=0; i < in.length() ; i++) {\n MP[i] = new double[4];\n for (int j=0; j < 4 ; j++) {\n MP[i][j] = 0;\n }\n }\n \n for (i=0 ; i<in.length() ; i++) {\n if (in[i]=='T') {\n MP[i][3] = 1; \n }\n if (in[i]=='C') {\n MP[i][1] = 1;\n }\n if (in[i]=='A') {\n MP[i][0] = 1;\n }\n if (in[i]=='G') {\n MP[i][2] = 1;\n }\n \n }\n \n}\n\nCadena::Cadena(const Cadena& orig) {\n}\n\nCadena::~Cadena() {\n delete this->PVM;\n \n //delete this->MP;\n \n \n}\n\nvoid Cadena::add( Cadena& other) {\n for(int w = 0; w <this->longitud-1 ; w++ ){\n for(int z =0 ; z<4 ; z++) {\n this->MP[w][z] += other.MP[w][z];\n }\n }\n}\n\nCadena& Cadena::operator +=(Cadena other) {\n for(int w = 0; w <this->longitud ; w++ ){\n for(int z =0 ; z<4 ; z++) {\n this->MP[w][z] += other.MP[w][z];\n std::cout << MP[w][z] << std::endl;\n }\n }\n}\n\nvoid Cadena::imprimir() {\n std::cout << ADN << std::endl;\n}\n\nvoid Cadena::findPVM(int amount) {\n PVM = new double*[this->longitud];\n for(int w = 0; w <this->longitud ; w++ ){\n PVM[w] = new double[4];\n for(int z =0 ; z<4; z++) {\n this->PVM[w][z] = this->MP[w][z]/amount ;\n }\n }\n \n}\n\n\n\nstd::string Cadena::motif() {\n std::string motif;\n std::string patterns[100];\n double temp = 0.35;\n int i = 0;\n bool hayComun = false;\n std::string letraComun;\n int F = 0;\n for(int w = 0; w <this->longitud ; w++ ){\n for(int z =0 ; z<4 ; z++) {\n if(PVM[w][z] > temp) {\n letraComun = this->letras[z];\n if(PVM[w][z]>temp)\n temp=PVM[w][z];\n \n hayComun = true; \n } else {\n \n }\n } \n if(hayComun) {\n motif += letraComun;\n temp = 0.35;\n hayComun = false;\n patterns[F] = motif;\n F++;\n }\n else {\n motif.clear();\n }\n }\n int where;\n int size;\n for(int k = 0 ; k < 100 ; k++) {\n if(patterns[k].length() >= size) {\n size = patterns[k].length();\n where = k;\n }\n }\n std::cout << patterns[where] << std::endl;\n return patterns[where];\n}\n\nstd::string Cadena::cadenaComun() {\n std::string motif;\n std::string patterns[100];\n double temp = 0;\n int i = 0;\n bool hayComun = false;\n std::string letraComun;\n int F = 0;\n for(int w = 0; w <this->longitud-1 ; w++ ){\n for(int z =0 ; z<4 ; z++) {\n if(PVM[w][z] >= temp) {\n letraComun = this->letras[z];\n if(PVM[w][z]>temp)\n temp=PVM[w][z];\n \n hayComun = true; \n } else {\n \n }\n } \n if(hayComun) {\n motif += letraComun;\n temp = 0;\n patterns[F] = motif;\n F++;\n }\n else {\n motif.clear();\n }\n }\n int where;\n int size;\n for(int k = 0 ; k < 100 ; k++) {\n if(patterns[k].length() >= size) {\n size = patterns[k].length();\n where = k;\n }\n }\n std::cout << patterns[where] << std::endl;\n return patterns[where];\n}\n\ndouble** Cadena::matrizPesos() {\n return this->PVM;\n}\n\nstd::string Cadena::cadenaDegenerada() {\n std::string motif;\n std::string patterns[100];\n double temp = 0.5;\n int i = 0;\n bool hayComun = true;\n std::string letraComun;\n int F = 0;\n for(int w = 0; w <this->longitud-1 ; w++ ){\n for(int z =0 ; z<4 ; z++) {\n if(PVM[w][z] > temp) {\n letraComun = this->letras[z];\n if(PVM[w][z]>temp)\n temp=PVM[w][z];\n \n hayComun = true; \n } else { \n if(PVM[w][0] == PVM[w][2]) {\n letraComun = \"R\";\n hayComun = true;\n \n }\n if(PVM[w][2]==PVM[w][1] ) {\n letraComun = \"S\";\n hayComun = true;\n }\n if(PVM[w][0]==PVM[w][1]) {\n letraComun = \"M\";\n }\n if(PVM[w][0]==PVM[w][1]==PVM[w][3]) {\n letraComun = \"H\";\n }\n if(PVM[w][2]==PVM[w][1]==PVM[w][3]) {\n letraComun = \"B\";\n }\n if(PVM[w][0]==PVM[w][1]==PVM[w][2]) {\n letraComun = \"V\";\n }\n if(PVM[w][0]==PVM[w][2]==PVM[w][3]) {\n letraComun = \"D\";\n }\n if(PVM[w][0]==PVM[w][2]==PVM[w][3]==PVM[w][1]) {\n letraComun = \"N\";\n }\n \n }\n } \n if(hayComun) {\n motif += letraComun;\n temp = 0;\n patterns[F] = motif;\n F++;\n }\n else {\n motif.clear();\n }\n }\n int where;\n int size;\n for(int k = 0 ; k < 100 ; k++) {\n if(patterns[k].length() >= size) {\n size = patterns[k].length();\n where = k;\n }\n }\n std::cout << patterns[where] << std::endl;\n return patterns[where];\n}" }, { "alpha_fraction": 0.5357142686843872, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 20, "blob_id": "a2b4d7c4bd671c39deeab5154fbbf48e19ac076b", "content_id": "21c216a3302ef9ee7f9bce04ef206251649019ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 84, "license_type": "no_license", "max_line_length": 62, "num_lines": 4, "path": "/Lab 5/html/search/files_0.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['casino_2ecpp',['casino.cpp',['../casino_8cpp.html',1,'']]]\n];\n" }, { "alpha_fraction": 0.43119266629219055, "alphanum_fraction": 0.6605504751205444, "avg_line_length": 26.25, "blob_id": "724030f1e8d465ed5bf5c76e522cc99826271ea8", "content_id": "22725ca00ff95f864237f1b6c77b2d1b727cf082", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 109, "license_type": "no_license", "max_line_length": 87, "num_lines": 4, "path": "/Lab 1/html/search/functions_2.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['main',['main',['../_lab1_8cc.html#a3c04138a5bfe5d72780bb7e82a18e627',1,'Lab1.cc']]]\n];\n" }, { "alpha_fraction": 0.5845394730567932, "alphanum_fraction": 0.5980263352394104, "avg_line_length": 24.737287521362305, "blob_id": "41cfe809116d27b7109033219b0292062399aaf6", "content_id": "eaa3d5e50a9b7575775ae11d368dbfb6fe8fd580", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3040, "license_type": "no_license", "max_line_length": 139, "num_lines": 118, "path": "/Lab 2/Triangulo.cpp", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "\n\n/* \n * @File: Triangulo.cpp\n * @author: jose\n * \n * @date September 6, 2016\n * \n */\n\n#include \"Triangulo.h\"\n\nusing namespace std;\n/**\n * @brief Me crea un triangulo con nombre y color genericos.\n * \n */\nTriangulo::Triangulo() {\n this->nombre = \"Moises\";\n this->color = \"Blanco\"; \n Triangulo::obtenerLados();\n \n}\n /**\n * @brief Me crea un triangulo con nombre y color ingresado por el usuario\n * @code\n * this->nombre = a; \n * this->color = b;\n * Triangulo::obtenerLados();\n * @endcode\n * @param a Nombre del triangulo\n * @param b Color del triangulo\n * \n */\nTriangulo::Triangulo(std::string a, std::string b) {\n this->nombre = a; \n this->color = b;\n Triangulo::obtenerLados();\n \n \n}\n/**\n * @brief Obtiene los lado del triangulo (tres lados) y los guarda en los lados de cada triangulo creado (this->lado).\n * \n * \n */\nvoid Triangulo::obtenerLados() {\n double l1; \n double l2;\n double l3;\n std::cout << \"Ingrese medida del lado 1:\" << std::endl;\n std::cin >> l1;\n std::cout << \"Medida lado 2:\" << std::endl;\n std::cin >> l2;\n std::cout << \"Medida lado 3:\" << std::endl;\n cin >> l3;\n this->lado1 = l1; \n this->lado2 = l2;\n this->lado3 = l3;\n \n \n \n \n}\n/**\n * @brief Calcula el area del triangulo usando la formula de heron\n * @var P guarda el perimetro del triangulo\n * @var semip Guarda el semiperimetro\n * @var area1 Valor del area calculado con formula de heron.\n * @code\n * double area1 = sqrt(semip*(semip-this->lado1)*(semip-this->lado2)*(semip-this->lado3));\n * @endcode\n */\nvoid Triangulo::Area() {\n \n double p = this->lado1 + this->lado2 + this->lado3 ; \n double semip = p/2 ; \n double area1 = sqrt(semip*(semip-this->lado1)*(semip-this->lado2)*(semip-this->lado3));\n if (isnan(area1)) {\n cout << \"No se puede calcular el area del triangulo con los valores ingresados utilizando la formula de Heron\" << endl;\n }\n this->area = area1;\n \n \n}\n/**\n * @brief Calcula el perimetro\n * @var per guarda el perimetro del triangulo.\n */\nvoid Triangulo::Perimetro() {\n double per = this->lado1+this->lado2+this->lado3 ;\n this->perimetro = per;\n}\n/**\n * @brief Muestra los atributos de cada triangulo (nombre, color, lados).\n * @return Informacion\n */\nvoid * Triangulo::operator ~() {\n std::cout << \"El nombre del triangulo es: \" << this->nombre << std::endl;\n std::cout << \"El color de \" << this->nombre << \" es \" << this->color << std::endl;\n std::cout << \"La longitud del los lados son en orden: \" << \" \" << this->lado1 << \" \" << this->lado2 << \" \" << this->lado3 << std::endl;\n \n}\n/**\n * @brief Muestra los resultados de area y perimetro\n * @return Informacion\n */\nvoid * Triangulo::operator !() {\n Triangulo::Area();\n Triangulo::Perimetro();\n std::cout << \"El area del triangulo es: \" << this->area << std::endl;\n std::cout << \"El perimetro es: \" << this->perimetro << std::endl;\n \n}\n\nTriangulo::Triangulo(const Triangulo& orig) {\n}\n\nTriangulo::~Triangulo() {\n}\n\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5384615659713745, "avg_line_length": 18.5, "blob_id": "96e1d8c053d62bc34fc45e5ec48ee614287daae0", "content_id": "8ec8407382a7c5b8a73fdfb11c3fd517a5fbdf07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 78, "license_type": "no_license", "max_line_length": 56, "num_lines": 4, "path": "/Lab 0/C++/html/search/files_0.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['suma_2ecpp',['suma.cpp',['../suma_8cpp.html',1,'']]]\n];\n" }, { "alpha_fraction": 0.5461538434028625, "alphanum_fraction": 0.7230769395828247, "avg_line_length": 31.5, "blob_id": "40f1b40609dbeb1dd81f8cc4329a692c444df37f", "content_id": "70656f59edbc6ff42acb58507aee3e8bf606a6cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 130, "license_type": "no_license", "max_line_length": 108, "num_lines": 4, "path": "/Lab 5/html/search/functions_0.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['barajar',['barajar',['../classpila_de_cartas.html#a16bac9885441ef926ba74ee6322a9663',1,'pilaDeCartas']]]\n];\n" }, { "alpha_fraction": 0.5185185074806213, "alphanum_fraction": 0.7083333134651184, "avg_line_length": 42.20000076293945, "blob_id": "4c19601ab791fee42714177d7a174c6f6492db6c", "content_id": "b4f11ef1508ca9f53293db33070276e4502c0d16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 216, "license_type": "no_license", "max_line_length": 102, "num_lines": 5, "path": "/Lab 5/html/search/functions_8.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['partida',['partida',['../classmesa.html#a5d2a4f9b46a8d8b9c1335d3fffaef33c',1,'mesa']]],\n ['play',['play',['../classpila_de_cartas.html#a9071896c634ec2a18fa384b57981a55a',1,'pilaDeCartas']]]\n];\n" }, { "alpha_fraction": 0.4954128563404083, "alphanum_fraction": 0.6788991093635559, "avg_line_length": 26.25, "blob_id": "c2890d95f4151aed0f16fabda7e46ef054cbf9c7", "content_id": "dd1c6e6671bcb7dfbe54842ec6bf051a55061db0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 109, "license_type": "no_license", "max_line_length": 87, "num_lines": 4, "path": "/Lab 5/html/search/all_f.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['value',['value',['../class_card.html#a5503f267af005285cdfeaa5633cd41bf',1,'Card']]]\n];\n" }, { "alpha_fraction": 0.6590213775634766, "alphanum_fraction": 0.6651375889778137, "avg_line_length": 21.55172348022461, "blob_id": "09feda76a33632b156eccb3fe05e3917ea1c9efd", "content_id": "3835c52b73aa727eb3be13d9d620891de15b52e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 654, "license_type": "no_license", "max_line_length": 114, "num_lines": 29, "path": "/Lab 0/Py/suma.py", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport sys\n\n## @package sumar.py\n# Programa que calcula la suma de argumentos. \n#\n# Programa el cual calcula la suma de los argumentos ingresados a la hora de correr este. \n\n\n\n## Funcion para calcular el resultado de la suma de los argumentos ingresados a la hora de correr # el programa. \n## @var sum \n# Guarda el resultado de la suma de los numeros de los argumentos en la fila argv.\ndef main():\n\t\n\tsum = 0\n\tfor i in range(1, len(sys.argv)):\n\t\tsum += float(sys.argv[i])\n\tprint sum \n# @code \n# \n#\tsum = 0\n#\tfor i in range(1, len(sys.argv)):\n#\t\tsum += float(sys.argv[i])\n#\tprint sum \n# @endcode\n# \nif __name__==\"__main__\":\n\tmain()\n" }, { "alpha_fraction": 0.48148149251937866, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 26, "blob_id": "84f8f50adc3b64341a4f29d3d1c870f15aad6c85", "content_id": "c7369afeeb06387f8487050d4c7a20a71bd05040", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 108, "license_type": "no_license", "max_line_length": 86, "num_lines": 4, "path": "/Lab 0/C/html/search/functions_1.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['sumar',['sumar',['../suma_8c.html#acda09b8c72ceee96283ce32e936a8f62',1,'suma.c']]]\n];\n" }, { "alpha_fraction": 0.5849802494049072, "alphanum_fraction": 0.5849802494049072, "avg_line_length": 15.866666793823242, "blob_id": "4f4930c35f3d4250cb83e1f24818146a1d58ce23", "content_id": "cadce98fc43d05e7ced70470c37935501ac943f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 253, "license_type": "no_license", "max_line_length": 31, "num_lines": 15, "path": "/Lab 0/Makefile", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "compilar: \n\tgcc C/suma.c -o suma.c.o\n\tg++ C++/suma.cpp -o suma.cpp.o\n\tchmod +x Py/suma.py\n\t\nclean: \n\trm suma.c.o suma.cpp.o\n\t\nejecutar:\n\techo \"El de C\"\n\t./suma.c.o $(ARG)\n\techo \"El de c++\"\n\t./suma.cpp.o $(ARG) \n\techo \"El de python\"\n\t./Py/suma.py $(ARG)\n" }, { "alpha_fraction": 0.5806451439857483, "alphanum_fraction": 0.6129032373428345, "avg_line_length": 22.25, "blob_id": "511bd82b0c9905c2fef270f49579bf8856d1782a", "content_id": "aee0dc52da32ddd93b1d0b452c967a0e0d37ad97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 93, "license_type": "no_license", "max_line_length": 71, "num_lines": 4, "path": "/Proyecto I/Ms/html/search/files_0.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['mergesort_2ecpp',['mergesort.cpp',['../mergesort_8cpp.html',1,'']]]\n];\n" }, { "alpha_fraction": 0.5968379378318787, "alphanum_fraction": 0.6067193746566772, "avg_line_length": 16.379310607910156, "blob_id": "4ba8cfd348fed27c2fd937b5b078f926384adae2", "content_id": "e778a85528da8da30d80197256ca974e46947f5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 506, "license_type": "no_license", "max_line_length": 53, "num_lines": 29, "path": "/Lab 2/Cuadrado.h", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "\n/** \n * @File: Cuadrado.h\n * @author: jose\n *\n * @date September 6, 2016\n * @param lado guarda el lado de cada cuadrado creado\n * \n * \n */\n#include \"Figura.h\"\n#ifndef CUADRADO_H\n#define CUADRADO_H\n\nclass Cuadrado : public Figura {\npublic:\n Cuadrado();\n Cuadrado(std::string , std::string); \n Cuadrado(const Cuadrado& orig);\n double lado;\n void Area();\n void Perimetro();\n void * operator ~();\n void * operator !();\n virtual ~Cuadrado();\nprivate:\n\n};\n\n#endif /* CUADRADO_H */\n\n" }, { "alpha_fraction": 0.6587947607040405, "alphanum_fraction": 0.670195460319519, "avg_line_length": 23.058822631835938, "blob_id": "f835a604e39621eee8b74458a8d4634805d8a60f", "content_id": "f788a6fa4fb58bd43a9fe5749cc4335b27f78946", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1228, "license_type": "no_license", "max_line_length": 113, "num_lines": 51, "path": "/Lab 0/C++/suma.cpp", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "/**\n* @file suma.c\n* @author Jose Alberto\n* @date 19 Aug 2016 \n* @brief Programa para sumar argumentos flotantes ingresados. \n*\n* Metodo el cual suma los argumentos flotantes ingresados a la hora de correr el programa, luego \n* retorna el resultado de dicha suma de argumentos. \n*/ \n#include <stdio.h>\n#include <iostream>\n\nusing namespace std;\nfloat sumar(int a, char **b) {\n\t/** \n* @brief Funcion para sumar argumentos\n* @code \n* for (int i=1;i<a;i++) {\n*\t\tfloat num;\n*\t\tsscanf(b[i], \"%f\", &num);\n*\t\tsuma+=num; \n*\t}\n*\treturn suma;\n*\n* @endcode\n* @param num Variable para guardar temporalmente cada argumento ingresado para sumarse.\n* @param suma Variable la cual recibe y guarda el resultado de la suma de la fila de argumentos * ingresados. \n* @return Funcion devuelve el resultado de la suma \n*/\n\tfloat suma=0.0;\n\tfor(int i=1;i<a;i++) {\n\t\tfloat num;\n\t\tsscanf(b[i], \"%f\", &num);\n\t\tsuma+=num;\n\t}\n\treturn suma;\n}\nint main(int argc, char **argv){\n/** \n* @brief Funcion principal que corre el programa. \n* @code \n*float result= sumar(argc, argv);\n*\tprintf(\"%.6f\\n\",result);\n*\treturn 0;\n* @endcode\n* @return Devuelve un 0 para mostrar que todo se corrio bien.\n*/\n\tfloat result = sumar(argc , argv);\n\tcout<<result<<endl;\n\treturn 0;\n}\n\n" }, { "alpha_fraction": 0.5680271983146667, "alphanum_fraction": 0.5867347121238708, "avg_line_length": 13.625, "blob_id": "1482a2b91321be8eb8f3617d3958f97f86aca019", "content_id": "18cc2ccef8c1d48710b55cdf581bbf6b50319f9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 588, "license_type": "no_license", "max_line_length": 41, "num_lines": 40, "path": "/Lab 2/Triangulo.h", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "\n\n/* \n * @File: Triangulo.h\n * @author: jose\n *\n * @date September 6, 2016\n * @param lado1 \n * @param lado2\n * @param lado3\n */\n\n#ifndef TRIANGULO_H\n#define TRIANGULO_H\n#include \"Figura.h\"\n\n\n\nclass Triangulo : public Figura {\npublic:\n \n \n Triangulo();\n Triangulo(const Triangulo& orig);\n \n Triangulo(std::string , std::string);\n \n void obtenerLados();\n double lado1; \n double lado2;\n double lado3;\n void Area();\n void Perimetro();\n void * operator ~();\n void * operator !();\n\n virtual ~Triangulo();\nprivate:\n\n};\n\n#endif /* TRIANGULO_H */\n\n" }, { "alpha_fraction": 0.6033607125282288, "alphanum_fraction": 0.6225087642669678, "avg_line_length": 23.834951400756836, "blob_id": "04520cfd8b2aa975e7262e5c9981711b10583796", "content_id": "4dbadea9a43a2c59b313d0c2a6a9bea51fc22bb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2560, "license_type": "no_license", "max_line_length": 95, "num_lines": 103, "path": "/Lab 3/src/Fraccion.cpp", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "/* \n * @File: Triangulo.cpp\n * @author: jose\n * \n * @date September 6, 2016\n * \n */\n#include \"Fraccion.h\"\n\n\n/**\n * @brief Me crea un objeto tipo fraccion.\n * Me crea una fraccion con los numeros ingresados por el usuario\n * \n * @param D Es un puntero de tipo int de tamaño dos para guardar el denominador y el numerador.\n * \n */\nFraccion::Fraccion() {\n frac = new int(2);\n int in;\n std::cout << \"Ingrese el numerador: \" << std::endl;\n std::cin >> in;\n frac[1] = in;\n std::cout << \"Ingrese el denominador: \" << std::endl;\n std::cin >> in;\n frac[2] = in;\n}\n/**\n * @brief Me crea un objeto tipo fraccion.\n * Constructor en el cual el usuario ingresa el numerador y denominador de manera directa.\n * @param a Numerador de la fraccion\n * @param b Denominador de la fraccion\n */\nFraccion::Fraccion(int a, int b) {\n frac = new int(2);\n frac[1] = a; \n frac[2] = b;\n \n}\n/**\n * @brief Se suma ambas fracciones.\n * @param other La otra fraccion a sumarse con la primera.\n */\nFraccion Fraccion::operator +(const Fraccion& other) {\n Fraccion result(0,0);\n result.frac[1] = other.frac[2]*this->frac[1] + this->frac[2]*other.frac[1]; \n result.frac[2] = this->frac[2]*other.frac[2];\n return result;\n ~result;\n return result;\n \n}\n /**\n * @brief Me resta ambas fracciones.\n * @param other La otra fraccion a restarse con la primera.\n */\nFraccion Fraccion::operator -(const Fraccion& other) {\n Fraccion result(0,0);\n result.frac[1] = other.frac[2]*this->frac[1] - this->frac[2]*other.frac[1]; \n result.frac[2] = this->frac[2]*other.frac[2];\n ~result;\n return result;\n }\n/**\n * @brief Me multiplica ambas fracciones\n * @param other La otra fraccion a multiplicarse con la primera\n */\nFraccion Fraccion::operator *(const Fraccion& other) {\n Fraccion result(0,0);\n result.frac[1] = other.frac[1]*this->frac[1];\n result.frac[2] = other.frac[2]*this->frac[2];\n ~result;\n return result;\n }\n /**\n * @brief Me divide ambas fracciones\n * @param other La otra fraccion a dividirse con la primera\n */\nFraccion Fraccion::operator /(const Fraccion& other) {\n Fraccion result(0,0);\n result.frac[1] = this->frac[1]*other.frac[2];\n result.frac[2] = this->frac[2]*other.frac[1];\n ~result;\n return result;\n \n }\n /**\n * @brief Sobrecarga que muestra la fraccion deseada.\n */\n void Fraccion::operator ~() {\n std::cout << this->frac[1] << \"/\" << this->frac[2];\n \n }\n\n \n \nFraccion::Fraccion(const Fraccion& orig) {\n}\n\nFraccion::~Fraccion() {\n delete this->frac;\n \n}\n\n" }, { "alpha_fraction": 0.6170212626457214, "alphanum_fraction": 0.6276595592498779, "avg_line_length": 22.5, "blob_id": "3d5b6a773fa07cd28dfeb10a17dead5bc57c076d", "content_id": "6dee27d13053c3748cfc3c38428b8cc9bceb9115", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 94, "license_type": "no_license", "max_line_length": 72, "num_lines": 4, "path": "/Lab 5/html/search/classes_4.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['piladecartas',['pilaDeCartas',['../classpila_de_cartas.html',1,'']]]\n];\n" }, { "alpha_fraction": 0.2631579041481018, "alphanum_fraction": 0.6315789222717285, "avg_line_length": 18, "blob_id": "1731ff7a4c0b3ef321a2d0e8be810bd661386a34", "content_id": "8b7e404940caae2b9737db8bd468680d1a0ba17b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 19, "license_type": "no_license", "max_line_length": 18, "num_lines": 1, "path": "/README.md", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "# IE-0217-II-16-G2\n" }, { "alpha_fraction": 0.5955414175987244, "alphanum_fraction": 0.6082802414894104, "avg_line_length": 13.857142448425293, "blob_id": "0a0402ab758a411fdf0e9c7d92ab5a14defa8c15", "content_id": "21ccd7b687aad59d091fd4c98d054aec0a605279", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 314, "license_type": "no_license", "max_line_length": 33, "num_lines": 21, "path": "/Lab 3/src/main.cpp", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "\n#include <cstdlib>\n#include \"Fraccion.h\"\n#include \"Matrix.h\"\n#include \"Calculadora.h\"\n#include \"Poly.h\"\nusing namespace std;\n\n/*\n * \n */\nint main(int argc, char** argv) {\n Matrix a;\n Matrix b;\n Calculadora<Matrix> calc1;\n Calculadora<Fraccion> calc2;\n calc1.add(a,b);\n \n \n \n return 0;\n}\n\n" }, { "alpha_fraction": 0.5602338910102844, "alphanum_fraction": 0.5660818815231323, "avg_line_length": 14.545454978942871, "blob_id": "64d3ab16e0b652065332ee6bb892fa0d061d4851", "content_id": "827389fa97a83854453f16585dd59bd41aadd53b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 855, "license_type": "no_license", "max_line_length": 63, "num_lines": 55, "path": "/Lab 5/queue.h", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "#include \"ListaConArreglo.h\"\n\ntemplate <typename T>\n\nclass queue: public ListaConArreglo<T> {\npublic:\n\tint front;\n\tint back;\n\tqueue() {\n\t\tfront = this->tam;\n\t\tback = this->ultimo;\n\t}\n\tvoid enqueue(T in) {\n\t\tListaConArreglo<T>::agregar(in);\n\t\tback++;\n\t} \n\tT dequeue() {\n\t\tif (this->back != -1) {\n\t\tthis->back--;\n\t\treturn ListaConArreglo<T>::eliminar(this->data[this->front]);\n\t\t\n\t\t}\n\t\telse {\n\t\t\tstd::cout << \"Queue vacio\" << std::endl;\n\t\t}\n\t}\n\tint size() {\n\t\treturn this->back - this->front;\n\t}\n\tbool isEmpty() {\n\t\tint j = 1;\n\n\t\tfor (int i = this->front; i<this->back; i++){\n\t\t\tif (this->data[j] != 0) {\n\t\t\t\tj=0;\n\t\t\t}\n\t\t}\n\t\tif (j==1) {\n\t\t\treturn true;\n\t\t}\n\t\telse {\n\t\t\treturn false;\n\t\t}\n\t}\n\tvoid nuevo() {\n\t\tListaConArreglo<T>::clear();\n\t}\n\n\tvoid imp() {\n\t\tListaConArreglo<T>::imprimir();\n\t}\n\tvoid operator=( queue other) {\n\tthis->data = other.data;\t\n\t}\n};\n" }, { "alpha_fraction": 0.5234375, "alphanum_fraction": 0.71875, "avg_line_length": 31, "blob_id": "d7e5628e17c754fe784554ab5b5ef50232e5da5a", "content_id": "a74fa3f59ce2d220790165cf622e3cbbaf7d1ec8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 128, "license_type": "no_license", "max_line_length": 106, "num_lines": 4, "path": "/Proyecto I/Qs/html/search/functions_1.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['imprimir',['imprimir',['../quicksort_8cpp.html#ac50541a527e434941a6f8550799dfb1b',1,'quicksort.cpp']]]\n];\n" }, { "alpha_fraction": 0.7168141603469849, "alphanum_fraction": 0.7168141603469849, "avg_line_length": 15.142857551574707, "blob_id": "986a72f36a79f51f8099e96fb3c3fb65004ae4be", "content_id": "422200ffa42af1543484229028b2b60f5dbf9f57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 226, "license_type": "no_license", "max_line_length": 51, "num_lines": 14, "path": "/Proyecto I/Makefile", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "compilar :\n\tg++ Qs/main.cpp -Wall -o Quicksort\n\tg++ Ms/main.cpp -Wall -o Mergesort\n\nclean :\n\trm Quicksort Mergesort\nfullclean : \n\trm Quicksort Mergesort quickSort.txt mergesort.txt\n\nQuick :\n\t./Quicksort\n\nMerge : \n\t./Mergesort\n" }, { "alpha_fraction": 0.6095505356788635, "alphanum_fraction": 0.6095505356788635, "avg_line_length": 16.700000762939453, "blob_id": "7e6743c5bcf3497dacea65e6a27ce130750af184", "content_id": "1e1296a4d61e2aec622907aaee93a7021c564a2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 356, "license_type": "no_license", "max_line_length": 39, "num_lines": 20, "path": "/Lab 2/Circulo.h", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "\n#include \"Figura.h\"\n#ifndef CIRCULO_H\n#define CIRCULO_H\n\nclass Circulo : public Figura{\npublic:\n Circulo();\n Circulo(std::string , std::string);\n Circulo(const Circulo& orig);\n void Perimetro();\n void Area();\n double radio; \n void * operator ~();\n void * operator !();\n virtual ~Circulo();\nprivate:\n\n};\n\n#endif /* CIRCULO_H */\n\n" }, { "alpha_fraction": 0.5051334500312805, "alphanum_fraction": 0.7063655257225037, "avg_line_length": 80.16666412353516, "blob_id": "e0fd33f0f746ee704019ad565568cd28e6b1318e", "content_id": "80231f7924ed1939945ab0adff1d1f551631fb42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 487, "license_type": "no_license", "max_line_length": 263, "num_lines": 6, "path": "/Lab 5/html/search/all_a.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['operator_2b_2b',['operator++',['../casino_8cpp.html#a1c1cb2dfe465711b6f6e059d2e8271b1',1,'operator++(Card::Rango &amp;value):&#160;casino.cpp'],['../casino_8cpp.html#aaa6df93d21f0065856c75e5ce9841709',1,'operator++(Card::Color &amp;suit):&#160;casino.cpp']]],\n ['operator_3d_3d',['operator==',['../class_card.html#af54ed83aa53a465a952001710a79d6d1',1,'Card']]],\n ['ordener',['ordener',['../casino_8cpp.html#a8f4f11e8f1fdf2b22f9fac43c01259db',1,'casino.cpp']]]\n];\n" }, { "alpha_fraction": 0.6288343667984009, "alphanum_fraction": 0.6441717743873596, "avg_line_length": 17.08333396911621, "blob_id": "46cf6b7e1cb093664cfafdd2e81de8a2258db460", "content_id": "f20224276f5f912952c3c2c6c54ea4b23a141c4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 652, "license_type": "no_license", "max_line_length": 79, "num_lines": 36, "path": "/Lab 2/Figura.h", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\n\n/* \n * File: Figura.h\n * Author: jose\n *\n * Created on September 6, 2016, 2:29 PM\n */\n\n#ifndef FIGURA_H\n#define FIGURA_H\n#include <iostream>\n#include <string.h>\n#include <cmath>\n\nclass Figura {\npublic:\n Figura();\n Figura(const Figura& orig);\n virtual ~Figura();\n std::string nombre; \n std::string color; \n double area;\n double perimetro;\n \n virtual void Area() = 0;\n virtual void Perimetro() = 0;\nprivate:\n\n};\n\n#endif /* FIGURA_H */\n\n" }, { "alpha_fraction": 0.5812807679176331, "alphanum_fraction": 0.6798029541969299, "avg_line_length": 39.599998474121094, "blob_id": "683d4285f3ba88cf3c0f5321834748f8abe44d82", "content_id": "b694b49d7cd1a76232ca14dad0d91219b10533b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 203, "license_type": "no_license", "max_line_length": 109, "num_lines": 5, "path": "/Proyecto I/Qs/html/search/all_2.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['quicksort',['quickSort',['../quicksort_8cpp.html#aeaf35c0b7c773f1a343b7af86baabb3b',1,'quicksort.cpp']]],\n ['quicksort_2ecpp',['quicksort.cpp',['../quicksort_8cpp.html',1,'']]]\n];\n" }, { "alpha_fraction": 0.579734206199646, "alphanum_fraction": 0.5847176313400269, "avg_line_length": 14.435897827148438, "blob_id": "4f1d7841b3d16ac5b972cc9cda00ff10085b2710", "content_id": "d84fa03de4933114eda2b1a6866c3a74a45a6c39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 602, "license_type": "no_license", "max_line_length": 57, "num_lines": 39, "path": "/Lab 5/stack.h", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "#include \"ListaConArreglo.h\"\n\ntemplate <typename T>\n\nclass stack: public ListaConArreglo<T> {\npublic:\n\tstack() {\n\n\t}\n\tvoid pop() {\n\t\tListaConArreglo<T>::eliminar(this->data[this->ultimo]);\n\t}\n\tvoid push(T a) {\n\t\tListaConArreglo<T>::agregar(a);\n\t}\n\tvoid imp() {\n\t\tListaConArreglo<T>::imprimir();\n\t}\n\tbool isEmpty() {\n\t\tif (this->tam == 0) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\tint size() {\n\t\treturn this->tam;\n\t}\n\tvoid clean() {\n\t\tfor (int i = 0; i < this->tam ; i++) {\n\t\tthis->data[i] = 0;\n\t}\n\t}\n\tvoid nuevo() {\n\t\t//stack::ListaConArreglo();\n\t}\n\tT top() {\n\t\treturn this->data[this->ultimo];\n\t} \n};\n" }, { "alpha_fraction": 0.5487179756164551, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 38, "blob_id": "2a55981e4ae772f0048a877438a259f071466a7b", "content_id": "65fec13351246a9016fdcfa6ed8c9520ef8da959", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 195, "license_type": "no_license", "max_line_length": 101, "num_lines": 5, "path": "/Proyecto I/Ms/html/search/all_2.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['merge',['merge',['../mergesort_8cpp.html#a11d3bcfd90f8bd0e9a365650a5fb929f',1,'mergesort.cpp']]],\n ['mergesort_2ecpp',['mergesort.cpp',['../mergesort_8cpp.html',1,'']]]\n];\n" }, { "alpha_fraction": 0.6694915294647217, "alphanum_fraction": 0.6694915294647217, "avg_line_length": 20.363636016845703, "blob_id": "b0872c54312f9761b15fec6a81c11eaa4c8bf135", "content_id": "43ce020080871ced37f5450d41022081262a3539", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 472, "license_type": "no_license", "max_line_length": 46, "num_lines": 22, "path": "/Lab 3/src/Fraccion.h", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "\n#ifndef FRACCION_H\n#define FRACCION_H\n#include<iostream>\n#include<cstdlib>\nclass Fraccion {\npublic:\n Fraccion();\n Fraccion(int , int);\n int *frac;\n Fraccion(const Fraccion& orig);\n Fraccion operator+(const Fraccion& other);\n Fraccion operator-(const Fraccion& other);\n Fraccion operator*(const Fraccion& other);\n Fraccion operator/(const Fraccion& other);\n void operator~();\n \n virtual ~Fraccion();\nprivate:\n\n};\n\n#endif /* FRACCION_H */\n\n" }, { "alpha_fraction": 0.3731818199157715, "alphanum_fraction": 0.3872727155685425, "avg_line_length": 16, "blob_id": "a1a0f8b0b9a278b609b36824ea6cc9cafbf49250", "content_id": "e690e4845dca8d4dda78954306c0d0595f1f629d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2200, "license_type": "no_license", "max_line_length": 50, "num_lines": 122, "path": "/Lab 5/ListaConArreglo.h", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "\r\n#ifndef LISTACONARREGLO_H\r\n#define LISTACONARREGLO_H\r\n#include <iostream>\r\n#include \"Lista.h\"\r\n\r\n\r\ntemplate <typename T>\r\n\r\nclass ListaConArreglo : public Lista<T> {\r\npublic:\r\n ListaConArreglo(){\r\n data = 0;\r\n tam = 0;\r\n ultimo = -1;\r\n }\r\n \r\n ListaConArreglo(int N) {\r\n this->data = new T[N];\r\n tam = N;\r\n ultimo = tam - 1;\r\n }\r\n ListaConArreglo(const ListaConArreglo& orig) {\r\n\r\n }\r\n ~ListaConArreglo() {\r\n\r\n }\r\n\r\n\r\n void agregar(T e) {\r\n if (data == 0) {\r\n data = new T[1];\r\n tam = 1;\r\n ultimo = 0;\r\n data[0] = e;\r\n } else {\r\n if (ultimo == tam - 1) {\r\n T* temp = new T[tam * 2];\r\n for (int i = 0; i < tam; i++) {\r\n temp[i] = data[i];\r\n }\r\n ultimo++;\r\n tam++;\r\n temp[ultimo] = e;\r\n delete data; // ojo con lss deletes\r\n data = temp;\r\n } else {\r\n ultimo++;\r\n tam++;\r\n data[ultimo] = e;\r\n }\r\n }\r\n }\r\n \r\n T eliminar(T e) {\r\n int k = buscar(e);\r\n\tT* temp = new T[1];\r\n\ttemp[0] = data[0];\r\n\r\n eliminarK(k);\r\n\treturn temp[0];\r\n\r\n }\r\n void eliminarK(int k) {\r\n for (int i = k; i < tam - 1; i++) {\r\n data[i] = data[i + 1];\r\n }\r\n tam--;\r\n ultimo--;\r\n }\r\n\r\n int buscar(T e) {\r\n for (int i = 0; i < tam; i++) {\r\n if (data[i] == e) {\r\n return i;\r\n }\r\n\r\n }\r\n return -1;\r\n } \r\n\r\n T siguienteK(int k) {\r\n if (k + 1 < tam) {\r\n return data[k + 1];\r\n } else {\r\n // return -1;\r\n }\r\n\r\n }\r\n T anteriorK(int k) {\r\n if (k - 1 >= 0) {\r\n return data[k - 1];\r\n } else {\r\n //return -1;\r\n }\r\n }\r\n\r\n T recuperar(int k) {\r\n return data[k];\r\n }\r\n\r\n void imprimir() {\r\n for (int i = 0; i < tam; i++) {\r\n std::cout << data[i] << \"\\t\";\r\n }\r\n std::cout << std::endl;\r\n }\r\n\r\n void clear() {\r\n \tdata = 0;\r\n\ttam = 0;\r\n\tultimo = -1;\r\n }\r\n int tam;\r\n int ultimo;\r\n T* data;\r\nprivate:\r\n \r\n //almacenar los elementos\r\n};\r\n\r\n#endif /* LISTACONARREGLO_H */\r\n\r\n" }, { "alpha_fraction": 0.4433962404727936, "alphanum_fraction": 0.6603773832321167, "avg_line_length": 25.5, "blob_id": "d894564128f4591996c5adfbf3693258411f2df5", "content_id": "726c87d8e830338626e3e8427939c442bfcc6f36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 106, "license_type": "no_license", "max_line_length": 84, "num_lines": 4, "path": "/Lab 0/C/html/search/all_0.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['main',['main',['../suma_8c.html#a3c04138a5bfe5d72780bb7e82a18e627',1,'suma.c']]]\n];\n" }, { "alpha_fraction": 0.6279934048652649, "alphanum_fraction": 0.6304706931114197, "avg_line_length": 26.17977523803711, "blob_id": "51f60757d084fc74398b2afb81ad2b34e40bc4db", "content_id": "114eecbd3833936a184017f061c16a53491e2df5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2422, "license_type": "no_license", "max_line_length": 124, "num_lines": 89, "path": "/Lab 2/Cuadrado.cpp", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "\n\n/* \n * @File: Cuadrado.cpp\n * @author: jose\n * \n * @date September 6, 2016\n * \n */\n\n#include \"Cuadrado.h\"\n/**\n * @brief Me crea un cuadrado con un lado ingresado por el usuario.\n * El constructor me genera un nombre y color genericos dado que en este caso no se le especifico algun nombre o color\n * @param l variable temporal para guardar el lado.\n */\nCuadrado::Cuadrado() {\n this->color = \"Blanco\";\n this->nombre = \"Salomon :D\";\n double l;\n std::cout << \"Ingrese el largo de lado del cuadrado:\" << std::endl;\n std::cin >> l;\n this->lado = l;\n}\n/**\n * @brief Genera un cuadrado con nombre y color ingresado por el usuario con una longitud del lado ingresado por el usuario.\n * \n * @param a Guarda el nombre temporalmente \n * @param b Guarda el color temporalmente\n * @code\n * this->color = b; \n * this->nombre = a;\n * @endcode\n */\nCuadrado::Cuadrado(std::string a, std::string b) {\n this->color = b; \n this->nombre = a;\n double l;\n std::cout << \"Ingrese el largo de lado del cuadrado:\" << std::endl;\n std::cin >> l;\n this->lado = l;\n}\n\nCuadrado::Cuadrado(const Cuadrado& orig) {\n}\n\n/**\n * @brief Funcion para calcular el area del cuadrado\n * @code\n * double area = this->lado * this->lado ; \n * @endcode\n * @param area Variable temporal del metodo para el area del cuadrado\n */\nvoid Cuadrado::Area() {\n double area = this->lado * this->lado ; \n this->area = area; \n}\n\n/**\n *@brief Funcion para calcular el perimetro del cuadrado\n * @param Per guarda el resultado del calculo del perimetro.\n * \n */\nvoid Cuadrado::Perimetro() {\n double Per = this->lado * 4;\n this->perimetro = Per;\n}\n/**\n * @brief Muestra las propiedades del cuadrado\n * @return No retorna nada ademas de imprimir la informacion\n */\nvoid * Cuadrado::operator ~() {\n std::cout << \"El nombre del cuadrado es:\" << this->nombre << std::endl;\n std::cout << \"El color de \" << this->nombre << \"es \" << this->color << std::endl;\n std::cout << \"La longitud del lado es: \" << this->lado << std::endl;\n \n}\n/**\n * @brief Muestra el resultado del calculo de area y perimetro.\n * @return No retorna nada ademas de imprimir la informacion.\n */\nvoid * Cuadrado::operator !() {\n Cuadrado::Area();\n Cuadrado::Perimetro();\n std::cout << \"El area del cuadrado es: \" << this->area << std::endl;\n std::cout << \"El perimetro es: \" << this->perimetro << std::endl;\n \n}\n\nCuadrado::~Cuadrado() {\n}\n\n" }, { "alpha_fraction": 0.5409836173057556, "alphanum_fraction": 0.7213114500045776, "avg_line_length": 29.5, "blob_id": "1265d2d78b66a933c2f09123bd645b0c1882713d", "content_id": "52733301d71e6f842c20535f3d23ddaed519a012", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 122, "license_type": "no_license", "max_line_length": 100, "num_lines": 4, "path": "/Lab 5/html/search/all_6.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['ingresarmesa',['ingresarmesa',['../classmesa.html#ad43a9ce086745fbc0615cf24c493d102',1,'mesa']]]\n];\n" }, { "alpha_fraction": 0.5061007142066956, "alphanum_fraction": 0.5176868438720703, "avg_line_length": 24.531414031982422, "blob_id": "b1ab541b2f953a83c5ab2c37b79d521991c8fbab", "content_id": "bed0545be0e9b9434db349561858cec3469cd6f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9754, "license_type": "no_license", "max_line_length": 182, "num_lines": 382, "path": "/Lab 5/casino.cpp", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <string>\n#include <stdexcept>\n#include <sstream>\n#include <vector>\n#include <algorithm>\n#include <ctime>\n#include \"stack.h\"\n#include \"queue.h\"\n#include <random>\n#include <chrono>\n#include <list>\n/**\n@file casino.cpp\n@author Jose Alberto Barrantes B50881 Alejandro Cedeño\n\"date 1 de Noviembre del 2016\"\n\n*/\n\n\n/**\nClase que representa los colores y los valores de una carta utilizando enums. Esto facilita el manejo de impresion del color y el valor de una carta. \n*/\nclass Card\n{\npublic:\n enum Rango {\n Ace = 1, Two, Three, Four, Five, Six, Seven,\n Eight, Nine, Ten, Jack, Queen, King, RangoEnd\n };\n enum Color { Spades, Hearts, Diamonds, Clubs, ColorEnd };\n\n Card() {\n\n }\n\n Card( Rango value, Color suit )\n : m_value(value), m_suit(suit)\n {\n\n }\n\n/**\nFuncion para obtener el valor de una carta.\n*/\n Rango value() const { return m_value; }\n /**\n Funcion para obtener el color de una carta.*/\n Color suit() const { return m_suit; }\n\n friend std::ostream& operator<<( std::ostream &os, const Card &card )\n {\n return os << card.cRangos[card.m_value] << card.cColors[card.m_suit];\n return os << card.sRangos[card.m_value] << \" of \" << card.sColors[card.m_suit];\n }\n /**\n Funcion para saber si dos cartas son iguales.*/\n bool operator==(Card& a) {\n if(this->m_value == a.m_value && this->m_suit == a.m_suit ) {\n return true;\n }\n else {\n return false; \n }\n \n }\n\nprivate:\n static const std::string sRangos[14];\n static const std::string sColors[4];\n static const char cRangos[14];\n static const char cColors[4];\n Rango m_value;\n Color m_suit;\n};\n\nconst std::string Card::sRangos[14] = {\n \"\\0\", \"Ace\", \"Dos\", \"Tres\", \"Cuatro\", \"Cinco\", \"Seis\", \"Siete\",\n \"Echo\", \"Nueve\", \"Diez\", \"J\", \"Q\", \"K\"\n};\nconst std::string Card::sColors[4] = { \"Espada\", \"Corazones\", \"Diamante\", \"Trebol\" };\nconst char Card::cRangos[14] = {\n '\\0', 'A', '2', '3', '4', '5', '6', '7',\n '8', '9', 'T', 'J', 'Q', 'K'\n};\nconst char Card::cColors[4] = { 'E', 'C', 'D', 'T' };\n\n/**\nFuncion utlizada para cuando se desea incrementar el valor de una carta.*/\nCard::Rango& operator++( Card::Rango &value )\n{\n return value = Card::Rango( static_cast<int>(value) + 1 );\n}\n/**Funcion para \"incrementar\" el color de una carta.*/\nCard::Color& operator++( Card::Color &suit )\n{\n return suit = Card::Color( static_cast<int>(suit) + 1 );\n}\n\n\n/**\nClase pilaDeCartas la cual crea una pila con 52 cartas cada una con sus propiedades color y valor, las guarda en un queue donde solo se puede accesar al valor de arriba de la pila.*/\nclass pilaDeCartas : public Card {\npublic: \n std::vector<Card> pila;\n queue<Card> pile;\n pilaDeCartas() {\n for( Card::Color suit = Card::Spades; suit < Card::ColorEnd; ++suit )\n for( Card::Rango value = Card::Ace; value < Card::RangoEnd; ++value ) {\n pila.push_back( Card(value, suit) );\n pile.enqueue(Card(value,suit));\n }\n }\n /**Aleatoriza la baraja*/\n void barajar() { \n std::srand (std::time(NULL));\n unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n\n shuffle (pila.begin(), pila.end(), std::default_random_engine(seed));\n shuffle (&pile.data[0] , &pile.data[pile.tam] , std::default_random_engine(seed));\n //std::random_shuffle(pila.begin(),pila.end());\n }\n /**Saca una carta*/\n Card play() {\n barajar();\n return pile.dequeue();\n pila.pop_back();\n }\n /**Rellena la pila si es un nuevo juego.*/\n void refill() {\n pile.nuevo();\n for( Card::Color suit = Card::Spades; suit < Card::ColorEnd; ++suit )\n for( Card::Rango value = Card::Ace; value < Card::RangoEnd; ++value ) {\n pile.enqueue(Card(value,suit));\n }\n }\n /**Retorna el valor de la carta sacada.*/\n int draw() {\n barajar();\n return pile.dequeue().value();\n }\n\n};\n\n/**\nClase para representar a cada jugador, cada uno de ellos tiene una cantidad de juegos jugados.\nLos turnos tomados y su prioridad.*/\nclass jugador {\npublic:\n int prioridad; \n int turno;\n char id;\n int gamesplayed = 1;\n\n jugador() {\n turno = 0;\n }\n jugador(char a) {\n turno = 0;\n id = a;\n\n }\n int mano;\n /**Suma el valor de la cartada obtenida a la mano del jugador.*/\n void getCard(int val) {\n mano += val;\n turno ++;\n std::cout << \"Mano Actual: \" << mano << ' ' << \"Player \"<< id << ' ' << \"Game : \" << gamesplayed<< std::endl;\n }\n\n void newgame() {\n gamesplayed++;\n turno = 0;\n mano = 0;\n }\nprivate: \n \n};\n\n/**\nClase mesa que tiene su propia baraja de cartas, cada mesa tiene un vector de jugadores de tamaño maximo 3.*/\nclass mesa : public pilaDeCartas {\npublic:\n std::vector<jugador> ingame;\n\n //queue<jugador> players;\n int capacity;\n int id;\n int eliminado;\n bool gaem = true;\n int partidas;\n\n mesa() {\n capacity = 3; \n ingame.reserve(3);\n id = 1;\n }\n mesa(int num) {\n id = num;\n capacity = 3;\n ingame.reserve(3);\n //std::cout << ingame.size() << std::endl;\n }\n /**Ingresa un jugador a una mesa si hay campo.*/\n void ingresarmesa( jugador Jin) {\n if(capacity > 0) {\n // game.agregar(Jin);\n ingame.push_back(Jin);\n capacity--;\n\n }\n }\n /**Saca un jugador de la mesa.*/\n void elimplayer(int k) {\n ingame.erase(ingame.begin()+k); \n capacity++;\n }\n /**Encuentra el ganador de Blackjack.*/\n void findwinner() {\n int temp;\n for(int i = 0 ; i < ingame.size() ; i++) {\n if(ingame[i].mano > temp && ingame[i].mano <= 21) {\n temp = ingame[i].mano;\n\n }\n }\n std::cout << \"Mesa \" << this->id <<\" Jugadores actuales: \" << 3 - capacity << std::endl;\n std::cout << \"Win Score: \" << temp << std::endl;\n for (int k = 0 ; k < ingame.size() ; k++) {\n if(ingame[k].mano > temp || ingame[k].mano < temp || ingame[k].mano != temp) {\n std::cout << \"Player: \" << ingame[k].id << \" Eliminated.\" << std::endl;\n ingame.erase(ingame.begin()+k); \n capacity++;\n } \n if(ingame[k].mano == temp) {\n std::cout << \"Player: \" << ingame[k].id << \"Wins \" <<std::endl;\n ingame[k].newgame();\n }\n\n }\n temp = 0;\n }\n /**Simula una partida hasta que el final del turno donde algun jugador no pida mas cartas.*/\n void partida() {\n while(gaem) {\n for (int i = 0 ; i < ingame.size() ; i++) {\n if(ingame[i].turno == 0) {\n for (int j = 0 ; j < ingame.size() ; j++) {\n ingame[j].getCard(draw());\n ingame[j].getCard(draw());\n if(ingame[j].mano >= 19) {\n gaem=false;\n }\n }\n \n }\n if((ingame[i].turno >= 1) && (ingame[i].mano < 19)) { \n ingame[i].getCard(draw());\n }\n if (ingame[i].mano >= 19 ) {\n gaem = false;\n }\n }\n }\n findwinner();\n refill();\n gaem = true;\n }\n\n /**Corre el juego mientras hayan jugadores.*/\n void correrJuego() {\n // std::cout << \"Mesa \"<< \"Partida \" << partidas <<\"Espacios Disponibles: \"<<capacity << std::endl;\n while (capacity != 3) {\n\n \n partida();\n // partidas++;\n } if (capacity == 3) {\n ingame.clear();\n }\n\n }\n\n};\n\n/**\nFuncion utlizada para llenar una mesa con jugadores.*/\nvoid filltables(std::vector<jugador>& a, mesa& tables) {\n if(tables.capacity > 0) {\n for(int k = 0; k< a.size()+1; k++) {\n tables.ingresarmesa(a[k]);\n a.erase(a.begin()+k);\n }\n }\n}\n\n/**La idea es ordenar el string de entrada al correr el programa segun la prioridad 2:1:05.*/\nqueue<char> ordener(std::string in) {\n\tint Tra=0;\n\tint Des=0;\n\tint Eje=0;\n\tint i=0;\n\tqueue<char> orden;\n\tint tam = in.size();\n\twhile(tam > 0) {\n\t\t\tif(Eje<2 && in[i]=='E') {\n\t\t\t\torden.enqueue(in[i]);\n\t\t\t\tstd::cout << in[i] << std::endl;\n\t\t\t\tEje++;\n\t\t\t\ti++;\n\t\t\t\ttam--;\n\t\t\t\tif(i==tam) {\n\t\t\t\t\ti=0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if( Eje/2 == 1 && in[i]=='T' || Eje==0 && in[i]=='T' ) {\n\t\t\t\torden.enqueue(in[i]);\n\t\t\t\tstd::cout << in[i] << std::endl;\n\t\t\t\tTra++;\n\t\t\t\tEje=0;\n\t\t\t\ti++;\n\t\t\t\ttam--;\n\t\t\t\tif(i==tam) {\n\t\t\t\t\ti=0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(Eje%2 == 0 && Tra%2==0 && in[i]=='D') {\n\t\t\t\torden.enqueue(in[i]);\n\t\t\t\tDes++;\n\t\t\t\tTra=0;\n\t\t\t\ti++;\n\t\t\t\ttam--;\n\t\t\t\tif(i==tam) {\n\t\t\t\t\ti=0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tEje=0;\n\t\t\t\tTra=0;\n\t\t\t\tDes=0;\n\t\t\t\ti++;\n\n\t\t\t}\n\t\t\n\t}\n\t\n\treturn orden;\n}\n/**Me crea un jugador con id de E, T, D dependiendo si es un Ejecutivo, Trabajador o Desempleados.*/\nstd::vector<jugador> crearJugadores(queue<char> lista) {\n\tstd::vector<jugador> out;\n\tfor(int i = 0 ; i<lista.size() ; i++) {\n\t\tjugador j(lista.data[i]);\n\t\tout.push_back(j);\n\t}\n\treturn out;\n}\n\nint main(int argc, char** argv) {\n std::vector<jugador> a;\n mesa table1;\n mesa table2(2);\n mesa table3(3);\n queue<char> fila;\n std::string file = argv[1];\n int size = file.length();\n a = crearJugadores(ordener(file));\n filltables(a,table1);\n if (table1.capacity==0) {\n \tfilltables(a, table2);\n }\n if(table2.capacity==0) {\n \tfilltables(a,table3);\n }\n table1.correrJuego();\n table2.correrJuego();\n table3.correrJuego();\n\t\n\n\n\n}\n" }, { "alpha_fraction": 0.5234375, "alphanum_fraction": 0.71875, "avg_line_length": 31, "blob_id": "eff5316d9ee77ed6533c7c76eebf5b786232d7f6", "content_id": "b8cd0bbcde21e284033c21d5e0046de9aa626691", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 128, "license_type": "no_license", "max_line_length": 106, "num_lines": 4, "path": "/Proyecto I/Ms/html/search/functions_1.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['imprimir',['imprimir',['../mergesort_8cpp.html#ac50541a527e434941a6f8550799dfb1b',1,'mergesort.cpp']]]\n];\n" }, { "alpha_fraction": 0.5409836173057556, "alphanum_fraction": 0.7049180269241333, "avg_line_length": 29.5, "blob_id": "cf0e233b76915be85bda6b982e04c2b52bb7eda5", "content_id": "ddb57472981329da7d3b44747bd195ee666128bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 122, "license_type": "no_license", "max_line_length": 100, "num_lines": 4, "path": "/Proyecto I/Ms/html/search/functions_2.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['merge',['merge',['../mergesort_8cpp.html#a11d3bcfd90f8bd0e9a365650a5fb929f',1,'mergesort.cpp']]]\n];\n" }, { "alpha_fraction": 0.5531914830207825, "alphanum_fraction": 0.567375898361206, "avg_line_length": 15.5625, "blob_id": "aa22d0c84e329cac0fab9e309bab24921f85c8c1", "content_id": "a9f8bbb64d2135fe2ed3b1e5462e8612ce53aa6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 564, "license_type": "no_license", "max_line_length": 39, "num_lines": 32, "path": "/Lab 5/Lista.h", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "#ifndef LISTA_H\r\n#define LISTA_H\r\n\r\ntemplate <typename data>\r\n\r\nclass Lista { //lista de doubles\r\npublic:\r\n Lista() {\r\n }\r\n Lista(const Lista& orig) {\r\n\r\n }\r\n virtual ~Lista() {\r\n\r\n }\r\n\r\n virtual void agregar(data e) = 0;\r\n virtual data eliminar(data e) = 0;\r\n virtual void eliminarK(int k) = 0;\r\n\r\n virtual int buscar(data e) = 0;\r\n\r\n virtual data siguienteK(int k) = 0;\r\n virtual data anteriorK(int k) = 0;\r\n\r\n virtual data recuperar(int k) = 0;\r\n virtual void imprimir() = 0;\r\nprivate:\r\n\r\n};\r\n\r\n#endif /* LISTA_H */\r\n\r\n" }, { "alpha_fraction": 0.3333333432674408, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 23, "blob_id": "9543e940a1dd870679b343bd4857e214f9e604cf", "content_id": "bc1c96332f5f60178d73d5998395448c939c9cb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 24, "license_type": "no_license", "max_line_length": 23, "num_lines": 1, "path": "/Lab 2/README.md", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "# IE-0217-II-16-Lab2-G2\n" }, { "alpha_fraction": 0.5522273182868958, "alphanum_fraction": 0.561955988407135, "avg_line_length": 27.08633041381836, "blob_id": "d811ba19694b79038d5f0ae9a7d527e5b1c42e0a", "content_id": "4bc84c1d86d37ccc042b64bf289f66f81b36cecb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3909, "license_type": "no_license", "max_line_length": 199, "num_lines": 139, "path": "/Proyecto I/Ms/mergesort.cpp", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "\n/** \n * @file mergesort.cpp\n * @author Jose Alberto Barrantes B50881 Alejandro Cedeño B41672\n * \n */\n\n#include <cstdlib>\n#include \"head.h\"\nusing namespace std;\n\n/**\n * @brief Funcion la cual recibe el arreglo y por medio de dos contadores a cada lado del arreglo al terminar su ejecucion deja el arreglo original a ordenado. \n * Funcion recibe un arreglo a el cual por medio de dos contadores uno a la izquierda y otro a la derecha se recorre el arreglo por ambos lados revisando que los valores\n * del lado izquierdo deben ser menores a los del lado derecho. Luego cuando ambos contadores de juntan se revisa si la variable ini la cual simboliza la cantidad de elementos que ya fueron\n * menores al lado derecho es mayor al valor mid; si esto sucede significa que todos los elementos del lado derecho fueron menores a los del izquier y solo faltan copiar los valores de ini hasta end.\n * Faltan copiar el resto de elementos sobre el arreglo result, de forma similar si ini es menor a mid.\n * \n * @param a Arreglo a ordenar.\n * @param beg Indice de inicio del arreglo.\n * @param end Indice de final del arreglo.\n * @param mid Indice punto medio del arreglo \n * @return 0 para decir que todo salio bien.\n */\nint * merge (int a[], int beg, int end, int mid) {\n int* result = new int[end+1-beg];\n int mitad = mid + 1;\n int i = 0;\n int ini = beg;\n while ((ini<=mid) && (mitad<=end)) {\n \n if (a[ini]<=a[mitad]) {\n result[i] = a[ini];\n ini++;\n }\n else {\n result[i] = a[mitad];\n mitad++;\n }\n i++;\n }\n if(ini>mid) \n { \n for(int k = mitad;k<=end;k++) \n { \n result[i]=a[k]; \n i++; \n } \n } \n else \n { \n for(int k = ini;k<=mid;k++) \n { \n result[i]=a[k]; \n i++; \n } \n } \n for(int z=0;z<=end-beg;z++) \n { \n a[z+beg]=result[z]; \n } \n delete result;\n return 0;\n \n}\n/**\n * Funcion para imprimir el arreglo.\n * @param p Arreglo \n * @param size Tamaño de este\n */\nvoid imprimir(int p[], int size) {\n cout << \"[\";\n for (int i = 0; i<size-1; i++) {\n \n cout << p[i] << \" \" << \",\";\n }\n cout <<p[size-1];\n cout << \"]\" << endl;\n \n}\n/**\n * @brief Funcion la llama la funcion sort sobre ambas mitades del arreglo de forma recursiva hasta tener un arreglo de tamaño 1.\n * @param a Arreglo a ordenar\n * @param beg Indice de inicio del arreglo (usualmente 0)\n * @param end Indice de final\n * @return \n */\nint * sort (int a[], int beg, int end) {\n int mid;\n if (beg<end) {\n mid = (beg+end)/2;\n sort(a,beg,mid);\n sort(a,mid+1,end);\n return merge(a,beg,end,mid);\n \n }\n else {\n return 0;\n }\n}\n/**\n * Funcion utlizada para obtener el tiempo de procesamiento en milisegundos.\n * @param clock1 Tiempo inicial\n * @param clock2 Tiempo final\n * @return returna la diferencia de final-inicial.\n */\ndouble get_CPU_time_usage(clock_t clock1,clock_t clock2)\n{\n double diffticks=clock1-clock2;\n double diffms=(diffticks*1000)/CLOCKS_PER_SEC;\n return diffms;\n}\n\nint main(int argc, char** argv) {\n \n srand(time(NULL));\n ofstream data;\n data.open(\"mergesort.txt\", ios::app);\n int tam;\n cout << \"-----------------------mergesort------------------\" << endl;\n cout << \"Tamaño del arreglo: \" << endl;\n cin >> tam;\n int a[tam];\n for (int i = 0; i<tam; i++) {\n a[i] = rand() % tam;\n }\n cout << \"Arreglo aleatorio --------\" << endl;\n imprimir(a,tam);\n clock_t begin = clock();\n sort(a,0,tam-1);\n clock_t end = clock();\n double time = get_CPU_time_usage(begin,end);\n data << tam << \"\\t\";\n data << -time << \"\\t\\n\";\n cout << \"CPU time in ms:\" << -time << endl;\n cout << \"Arreglo ordenado ----------\" << endl;\n imprimir(a,tam);\n data.close();\n return 0;\n}\n\n" }, { "alpha_fraction": 0.5562655329704285, "alphanum_fraction": 0.5662052035331726, "avg_line_length": 27.724489212036133, "blob_id": "57417c5b3c1bfc9502ec13c41d87e66e07c0443f", "content_id": "a1ca89260e1284d7f3ca5fb75e7fdf182cd3ef0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2819, "license_type": "no_license", "max_line_length": 207, "num_lines": 98, "path": "/Proyecto I/Qs/quicksort.cpp", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "\n/**\n * @file quicksort.cpp\n * @author Jose Alberto Barrantes B50881 Alejando Cedeño B41672\n */\n\n#include <cstdlib>\n#include \"head.h\"\nusing namespace std;\n\n/**\n * Funcion quicksort la cual recive un arreglo, su indice derecho y izquierdo. Luego dependiendo de la implementacion calcula un valor pivot para comparar los valores del arreglo.\n * Con dos ciclos while se recurre el arreglo, se asume que los valores del lado derecho son mayores al pivot y del lado derecho menores; si esto no se cumple se cambiar los elementos.\n * Luego si al recorrer ambos ciclos las variables i y j no son mayores o menores a right o left dependiendo del caso significa que el arreglo no esta ordenado por ende se llama quicksort de manera recursiva\n * sobre ambos lados del arreglo. \n * @param arg Arreglo a ordenar. \n * @param left Indice de la izquierda\n * @param right Indice de la derecha\n */\nvoid quickSort (int arg[], int left, int right) {\n int tmp;\n int i = left;\n int j = right;\n int pivot = arg[(left+right)/2];\n while (i<=j) {\n while (arg[i]<pivot) {\n i++;\n }\n while (arg[j]>pivot) {\n j--;\n }\n if (i<=j) {\n tmp = arg[i];\n arg[i] = arg[j];\n arg[j] = tmp;\n i++;\n j--;\n }\n }\n if (left < j) {\n quickSort(arg, left, j);\n }\n if (i < right) {\n quickSort(arg, i, right);\n }\n}\n/**\n * Funcion para calcular el tiempo del procesador\n * @param clock1 Tiempo inicial\n * @param clock2 Tiempo final\n * @return Diferencia entre final-inicial en milisegundos. \n */\ndouble get_CPU_time_usage(clock_t clock1,clock_t clock2)\n{\n double diffticks=clock1-clock2;\n double diffms=(diffticks*1000)/CLOCKS_PER_SEC;\n return diffms;\n}\n/**\n * Funcion para imprimir algun arreglo p.\n * @param p Arreglo a imprimir\n * @param size Tamaño de este.\n */\nvoid imprimir(int p[], int size) {\n cout << \"[\";\n for (int i = 0; i<size; i++) {\n cout<< p[i] << \" \" << \",\";\n }\n cout<< p[size-1];\n cout << \"]\"<< endl;\n}\n\nint main(int argc, char** argv) {\n\n int tam;\n cout << \"---------------------------quicksort-------------------\" << endl;\n cout << \"Tamaño del arreglo: \" << endl;\n cin >> tam;\n int a[tam];\n ofstream data;\n data.open(\"quickSort.txt\", ios::app);\n srand(time(NULL));\n for (int i = 0; i<tam; i++) {\n a[i] = rand() %tam+2;\n }\n cout << \"Arreglo sin ordenar -------\" << endl;\n imprimir(a,tam);\n clock_t begin = clock();\n quickSort(a , 0 , tam-1);\n clock_t end = clock(); \n double time = get_CPU_time_usage(begin,end);\n data << tam << \"\\t\" ;\n data << -time << \"\\t\\n\";\n cout << \"Arreglo ordenado------------\" << endl;\n imprimir(a,tam);\n cout << \"CPU time \" << -time << \" ms \" << endl;\n data.close();\n return 0;\n}\n\n" }, { "alpha_fraction": 0.5249999761581421, "alphanum_fraction": 0.5625, "avg_line_length": 19, "blob_id": "7d7aaafbf0b6fffdb66d3e093c1d345ded879a4a", "content_id": "ef94c827d193042633671c34ddfcee593e8875a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 80, "license_type": "no_license", "max_line_length": 58, "num_lines": 4, "path": "/Lab 0/Py/html/search/all_0.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['py',['py',['../namespacesumar_1_1py.html',1,'sumar']]]\n];\n" }, { "alpha_fraction": 0.390625, "alphanum_fraction": 0.484375, "avg_line_length": 24.600000381469727, "blob_id": "15fcdb96e140daec3157b9d840d369cc3ebc770a", "content_id": "ce3f8b8d89a37f716d7e60168dcdf812a85d08f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 128, "license_type": "no_license", "max_line_length": 55, "num_lines": 5, "path": "/Lab 1/html/search/all_2.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['lab1_2ecc',['Lab1.cc',['../_lab1_8cc.html',1,'']]],\n ['lab1_2eh',['lab1.h',['../lab1_8h.html',1,'']]]\n];\n" }, { "alpha_fraction": 0.508474588394165, "alphanum_fraction": 0.7118644118309021, "avg_line_length": 28.5, "blob_id": "70a330a75e10ff83e2fdc4f1b427593e43c10520", "content_id": "74e00fdbba73c2445121de09df0e82b66b819535", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 118, "license_type": "no_license", "max_line_length": 96, "num_lines": 4, "path": "/Lab 5/html/search/functions_3.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['elimplayer',['elimplayer',['../classmesa.html#a534cd4d5323a56a8524976b9fb93859b',1,'mesa']]]\n];\n" }, { "alpha_fraction": 0.46086955070495605, "alphanum_fraction": 0.695652186870575, "avg_line_length": 27.75, "blob_id": "cdf1168a5809889f522b0a359a4470c367e471b1", "content_id": "fd46b1c259b9b05f5adffe279b41e64ad2206fac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 115, "license_type": "no_license", "max_line_length": 93, "num_lines": 4, "path": "/Lab 2/html/search/functions_0.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['area',['Area',['../class_cuadrado.html#a3d1411d7a4cd8734938092727009d702',1,'Cuadrado']]]\n];\n" }, { "alpha_fraction": 0.6440251469612122, "alphanum_fraction": 0.6566037535667419, "avg_line_length": 20.45945930480957, "blob_id": "6d9657644ea4424f0433c1031966bb4d4f880387", "content_id": "a48a96054daaf9024897b91fb21de0959ef47662", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 795, "license_type": "no_license", "max_line_length": 79, "num_lines": 37, "path": "/Lab 3/src/Matrix.h", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\n\n/* \n * File: Matrix.h\n * Author: jose\n *\n * Created on September 14, 2016, 2:02 PM\n */\n\n#ifndef MATRIX_H\n#define MATRIX_H\n#include<iostream>\n#include<cstdlib>\n#include<stdexcept>\nclass Matrix {\npublic:\n Matrix();\n Matrix(int , int ,int );\n Matrix(const Matrix& orig);\n virtual ~Matrix();\n Matrix(int , int);\n Matrix operator+(const Matrix &other); \n Matrix operator*(const Matrix& other);\n Matrix operator-(const Matrix& other);\n Matrix operator/(const Matrix& other);\n void operator~();\nprivate:\n int columnas;\n int filas1;\n double** mat; \n};\n\n#endif /* MATRIX_H */\n\n" }, { "alpha_fraction": 0.4648241102695465, "alphanum_fraction": 0.478463739156723, "avg_line_length": 24.31818199157715, "blob_id": "11b6f3e2534e27c5800df27ca51917f6adc08a34", "content_id": "a08af0aae194341b2212f0764a530fc9c73b6f10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2786, "license_type": "no_license", "max_line_length": 83, "num_lines": 110, "path": "/Proyecto2/main.cpp", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\n\n/* \n * File: main.cpp\n * Author: jose\n *\n * Created on November 19, 2016, 9:36 PM\n */\n\n#include <cstdlib>\n#include \"Cadena.h\"\n#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <vector>\n#include <iomanip>\nusing namespace std;\n\n/*\n * \n */\nconst std::string Cadena::letras[4] = { \"A\" , \"C\" , \"G\" , \"T\" };\n\ndouble get_CPU_time_usage(clock_t clock1,clock_t clock2)\n{\n double diffticks=clock1-clock2;\n double diffms=(diffticks*1000)/CLOCKS_PER_SEC;\n return diffms;\n}\n\n\n\nint main(int argc, char** argv) {\n string fileIn;\n string outFile;\n if(argc>1) {\n fileIn = argv[1];\n }\n if(argc>2) {\n outFile = argv[2];\n }\n ifstream file(fileIn);\n if(file.is_open())\n {\n string myArray[100];\n string jeje;\n istream_iterator<std::string> in{ file }, end;\n int count = std::distance(in, end);\n file.clear();\n file.seekg(0, ios::beg);\n cout << count << endl;\n for(int i = 0; i < count; ++i)\n {\n getline(file , myArray[i]); \n }\n \n vector<Cadena> list;\n Cadena out[count];\n for(int k = 0; k<count ; ++k) {\n Cadena in(myArray[k]);\n cout << myArray[k] << endl;\n list.push_back(in);\n out[k] = in;\n } \n Cadena sum(myArray[0].length());\n for(int j = 0; j < count ; j++) {\n sum.add(out[j]);\n }\n \n \n ofstream data; \n data.open(\"Resultados.txt\", ios::app);\n data << \"La cadena mas larga en comun: \";\n clock_t begin = clock();\n sum.findPVM(count);\n \n data << sum.motif();\n data << \"\\n\";\n data << \"Cadena mas probable: \";\n data << sum.cadenaComun();\n data << \"\\n\";\n data << \"La cadena degenerada: \";\n data << sum.cadenaDegenerada();\n clock_t fin = clock();\n data << \"\\n\";\n double** exit = sum.matrizPesos();\n double time = get_CPU_time_usage(begin,fin);\n data << \"Tiempo de ejecucion: \" << \"\\t\";\n data << -time << \"\\t\\n\"; \n data << \"\\n\";\n data << \"Matriz de Pesos de las cadenas: \" << \"\\n\";\n data <<\"\\t\" << \"A\" << \"\\t\" << \"C\" << \"\\t\" << \"G\" << \"\\t\" << \"T\" << \"\\t\\n\";\n \n for(int w = 0; w <myArray[0].length()-1 ; w++ ){\n data << w+1 << \" |\" << \"\\t\";\n for(int z =0 ; z<4 ; z++) {\n std::cout << std::fixed;\n std::cout << std::setprecision(2);\n data << exit[w][z] << \"\\t\";\n }\n data << \"\\t\\n\";\n }\n }\n \n return 0;\n}\n\n" }, { "alpha_fraction": 0.6126657128334045, "alphanum_fraction": 0.6318114995956421, "avg_line_length": 18.371429443359375, "blob_id": "cdd9262419e4cdece50249c1e48cbfb5f6976ad5", "content_id": "56597e028cc3d96c6ce7dff5b2e618f388aac126", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 679, "license_type": "no_license", "max_line_length": 79, "num_lines": 35, "path": "/Lab 3/src/Poly.h", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\n\n/* \n * File: Poly.h\n * Author: jose\n *\n * Created on September 19, 2016, 2:04 PM\n */\n#include<iostream>\n#ifndef POLY_H\n#define POLY_H\n\nclass Poly {\npublic:\n Poly();\n Poly(int);\n Poly(const Poly& orig);\n virtual ~Poly();\n Poly operator+(const Poly& other);\n Poly operator-(const Poly& other);\n Poly operator*(const Poly& other);\n Poly operator!();\n void operator~();\n int obtenerGrado();\nprivate:\n \n int arg[1000];\n int degree;\n};\n\n#endif /* POLY_H */\n\n" }, { "alpha_fraction": 0.5056179761886597, "alphanum_fraction": 0.5393258333206177, "avg_line_length": 21.25, "blob_id": "7fa7e0f85a1175eeeea6bdb23d003c019f47a2a4", "content_id": "24d328480c18dac04b28cf293318faa0232ae165", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 89, "license_type": "no_license", "max_line_length": 67, "num_lines": 4, "path": "/Lab 1/html/search/files_0.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['arnaaa_2ecpp',['ARNaAA.cpp',['../_a_r_na_a_a_8cpp.html',1,'']]]\n];\n" }, { "alpha_fraction": 0.28728365898132324, "alphanum_fraction": 0.30158013105392456, "avg_line_length": 28.53333282470703, "blob_id": "69e5a6c2ea848586b9d3f489743fe42dbd66bbca", "content_id": "a2013e6d6d9e22502289c4b1985a13d87ffd4479", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6646, "license_type": "no_license", "max_line_length": 129, "num_lines": 225, "path": "/Lab 1/ARNaAA.cpp", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "/**\n* @file ARNaAA.cpp \n* @author Jose Alberto Barrantes\n* @date 28 Aug 2016.\n* @brief funciones utilizadas para obtener la cadena de aminoacidos a partir de una de ARN. \n* Por el medio de dos funciones Lab1.cc obtiene la cadena de ARN y primero obtiene su equivalente en aminoacidos \n* con la ayuda de la funcion ARNaAA. \n* Luego n cantidad de aminoacidos son impresos con la funcion imprimirArregloDeChar.\n* \n*/\n#include <iostream>\nusing namespace std;\n\n/**\n * @brief Funcion para imprimir n terminos del arreglo de aminoacidos.\n * Funcion para imprimir n cantidad de aminoacidos contenidos en \n * el arreglo obtenido de la funcion ARNaAA.\n * @code\n * int i;\n cout << '|' ;\n for (i=0; i<n; i++) {\n cout << a[i];\n }\n cout << '|' << endl;\n * @endcode\n * @param n cantidad de aminoacidos a imprimir en la consola; ingresado por el usuario. \n * \n */\n\nvoid imprimirArregloDeChar (char* a, int n) {\n int i;\n cout << '|' ;\n for (i=0; i<n; i++) {\n cout << a[i];\n }\n cout << '|' << endl;\n}\n/** \n *@brief Funcion que recive un arreglo y su longitud. \n * Funcion la cual parsea la cadena de ARN ingresada por el usuario y por medio de comparacion llena un arreglo de salida de los \n * aminoacidos includios en la cadena de ARN. \n *@code \n * char * re = new char [a];\n int i;\n int nextAA;\n \n for (i=3 ; i<(a-3) ;i+=3) {\n if (RNA[i]=='U') {\n if (RNA[i+1]=='U') {\n if (RNA[i+2]=='U' || RNA[i+2]=='C') {\n * .\n * .\n * .\n * \n return re;\n delete re;\n }\n * @endcode\n * @param re[out] Puntero del tamaño de la cadena de ARN. \n * @param mextAA contador externo para agregar aminoacidos al arreglo \"re\". \n * \n * \n */\nchar* ARNaAA(char * RNA, int a) { \n char * re = new char [a];\n int i;\n int nextAA;\n \n for (i=3 ; i<(a-3) ;i+=3) {\n if (RNA[i]=='U') {\n if (RNA[i+1]=='U') {\n if (RNA[i+2]=='U' || RNA[i+2]=='C') {\n re[nextAA] = 'F';\n \n nextAA++;\n }\n if (RNA[i+2]=='A' || RNA[i+2]=='G') {\n \n re[nextAA] = 'L'; \n nextAA++;\n }\n }\n if (RNA[i+1]=='C') {\n if (RNA[i+2]=='U' || RNA[i+2]=='C' || RNA[i+2]=='A' || RNA[i+2]=='G') {\n \n re[nextAA] = 'S'; \n nextAA++;\n }\n \n }\n if (RNA[i+1]=='A') {\n if (RNA[i+2]=='U' || RNA[i+2]=='C') {\n \n re[nextAA] = 'Y'; \n nextAA++;\n }\n }\n if (RNA[i+1]=='G') {\n if (RNA[i+2]=='U' || RNA[i+2]=='C') {\n \n re[nextAA] = 'C'; \n nextAA++;\n }\n if (RNA[i+2]=='G') {\n \n re[nextAA] = 'W'; \n nextAA++;\n }\n }\n }\n if (RNA[i]=='C') {\n if (RNA[i+1]=='U') {\n if (RNA[i+2]=='U' || RNA[i+2]=='C' || RNA[i+2]=='A' || RNA[i+2]=='G') {\n \n re[nextAA] = 'L'; \n nextAA++;\n }\n\n }\n if (RNA[i+1]=='C') {\n if (RNA[i+2]=='U' || RNA[i+2]=='C' || RNA[i+2]=='A' || RNA[i+2]=='G') {\n \n re[nextAA] = 'P'; \n nextAA++;\n }\n }\n if (RNA[i+1]=='A') {\n if (RNA[i+2]=='U' || RNA[i+2]=='C') {\n \n re[nextAA] = 'H'; \n nextAA++;\n }\n if (RNA[i+2]=='A' || RNA[i+2]=='G') {\n \n re[nextAA] = 'Q'; \n nextAA++;\n }\n \n }\n if (RNA[i+1]=='G') {\n if (RNA[i+2]=='U' || RNA[i+2]=='C' || RNA[i+2]=='A' || RNA[i+2]=='G') {\n \n re[nextAA] = 'R'; \n nextAA++;\n }\n }\n }\n if (RNA[i]=='A') {\n if (RNA[i+1]=='U') {\n if (RNA[i+2]=='U' || RNA[i+2]=='C' || RNA[i+2]=='A') {\n \n re[nextAA] = 'I'; \n nextAA++;\n }\n if (RNA[i+2]=='G') {\n \n re[nextAA] = 'M'; \n nextAA++;\n }\n }\n if (RNA[i+1]=='C') {\n if(RNA[i+2]=='U' || RNA[i+2]=='C' || RNA[i+2]=='A' || RNA[i+2]=='G') {\n \n re[nextAA] = 'T'; \n nextAA++;\n }\n }\n if (RNA[i+1]=='A') {\n if (RNA[i+2]=='U' || RNA[i+2]=='C') {\n re[nextAA] = 'N'; \n nextAA++;\n }\n if (RNA[i+2]=='A' || RNA[i+2]=='G') {\n re[nextAA] = 'K'; \n nextAA++;\n }\n }\n if (RNA[i+1]=='G') {\n if (RNA[i+2]=='U' || RNA[i+2]=='C') {\n re[nextAA] = 'S'; \n nextAA++;\n }\n if (RNA[i+2]=='A' || RNA[i+2]=='G') {\n re[nextAA] = 'R'; \n nextAA++;\n }\n }\n }\n if (RNA[i]=='G') {\n if (RNA[i+1]=='U') {\n if (RNA[i+2]=='U' || RNA[i+2]=='C' || RNA[i+2]=='A' || RNA[i+2]=='G') {\n re[nextAA] = 'V'; \n nextAA++;\n }\n \n }\n if (RNA[i+1]=='C') {\n if (RNA[i+2]=='U' || RNA[i+2]=='C' || RNA[i+2]=='A' || RNA[i+2]=='G') {\n re[nextAA] = 'A'; \n nextAA++;\n }\n }\n if (RNA[i+1]=='A') {\n if (RNA[i+2]=='U' || RNA[i+2]=='C') {\n re[nextAA] = 'D'; \n nextAA++;\n }\n if (RNA[i+2]=='A' || RNA[i+2]=='G') {\n re[nextAA] = 'E'; \n nextAA++;\n }\n }\n if (RNA[i+1]=='G') {\n if (RNA[i+2]=='U' || RNA[i+2]=='C' || RNA[i+2]=='A' || RNA[i+2]=='G') {\n re[nextAA] = 'G'; \n nextAA++;\n }\n }\n }\n \n }\n \n return re;\n delete re;\n}\n" }, { "alpha_fraction": 0.5350467562675476, "alphanum_fraction": 0.5887850522994995, "avg_line_length": 52.5, "blob_id": "1e54aa7d882d7de44d25d023202e022bece8dac9", "content_id": "e4ad5e8017a6d093bda11e98c82f3bc9331920da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 428, "license_type": "no_license", "max_line_length": 112, "num_lines": 8, "path": "/Lab 5/html/search/classes_2.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['lista',['Lista',['../class_lista.html',1,'']]],\n ['lista_3c_20card_20_3e',['Lista&lt; Card &gt;',['../class_lista.html',1,'']]],\n ['lista_3c_20t_20_3e',['Lista&lt; T &gt;',['../class_lista.html',1,'']]],\n ['listaconarreglo',['ListaConArreglo',['../class_lista_con_arreglo.html',1,'']]],\n ['listaconarreglo_3c_20card_20_3e',['ListaConArreglo&lt; Card &gt;',['../class_lista_con_arreglo.html',1,'']]]\n];\n" }, { "alpha_fraction": 0.4126679599285126, "alphanum_fraction": 0.44337812066078186, "avg_line_length": 18.22222137451172, "blob_id": "419665015e213ceca8dc0345b41ca0c872de0c4b", "content_id": "cf3f7620053d4986a262ef336049a3bdf8eb7288", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 521, "license_type": "no_license", "max_line_length": 44, "num_lines": 27, "path": "/Lab 3/src/Calculadora.h", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "\n#ifndef CALCULADORA_H\n#define CALCULADORA_H\ntemplate <typename data>\nclass Calculadora {\n public:\n data add(data& d1, const data& d2) {\n return d1+d2;\n \n }\n data sub(data& d1, const data& d2) {\n return d1-d2;\n }\n \n data mul(data& d1, const data& d2) {\n return d1*d2;\n }\n \n data div(data& d1, const data& d2) {\n return d1/d2;\n \n }\n \n \n};\n\n\n#endif /* CALCULADORA_H */\n\n" }, { "alpha_fraction": 0.4934210479259491, "alphanum_fraction": 0.5460526347160339, "avg_line_length": 29.399999618530273, "blob_id": "1a282974e326bb98b5fd26b63fba46557b1af526", "content_id": "707625ea968a0d140ee97a72704636f3f5184629", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 152, "license_type": "no_license", "max_line_length": 79, "num_lines": 5, "path": "/Lab 5/html/search/classes_5.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['queue',['queue',['../classqueue.html',1,'']]],\n ['queue_3c_20card_20_3e',['queue&lt; Card &gt;',['../classqueue.html',1,'']]]\n];\n" }, { "alpha_fraction": 0.6606683731079102, "alphanum_fraction": 0.663239061832428, "avg_line_length": 15.8695650100708, "blob_id": "5966ca8018e373e331baed2defa1355416697998", "content_id": "df66adfe0f5a61f0fc6e8a10e482f7a013f5d455", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 389, "license_type": "no_license", "max_line_length": 79, "num_lines": 23, "path": "/Lab 1/lab1.h", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "/**\n * @file lab1.h\n * @author Jose Alberto Barrantes \n * @brief Header file, con los include's y funciones necesarias en el programa.\n * @param \n * @param \n */\n#ifndef _welcome_H\n#define\t_welcome_H\n#include <iostream>\n#include <string.h>\n#include <stdexcept>\n#include \"ARNaAA.cpp\"\n\nusing namespace std;\n\nvoid imprimirArregloDeChar(char * , int);\nchar * ARNaAA (char *, int);\n\n\n\n\n#endif\t/* _welcome_H */\n\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.6785714030265808, "avg_line_length": 27, "blob_id": "dabbbbda41dcc79f6f49c01bb3bfd91e68996b1f", "content_id": "e3a170b70ccdb54dd32fdadc339fc345502348d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 112, "license_type": "no_license", "max_line_length": 90, "num_lines": 4, "path": "/Lab 0/C++/html/search/functions_1.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['sumar',['sumar',['../suma_8cpp.html#acda09b8c72ceee96283ce32e936a8f62',1,'suma.cpp']]]\n];\n" }, { "alpha_fraction": 0.5390199422836304, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 90.83333587646484, "blob_id": "8d884deff29a028ebe0fdb08e5315f14f6c8ed95", "content_id": "10b0ef93b1915d6158c8ec5a4e0da221882ff933", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 551, "license_type": "no_license", "max_line_length": 208, "num_lines": 6, "path": "/Lab 2/html/search/functions_2.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['obtenerlados',['obtenerLados',['../class_triangulo.html#a1174be9286bedca30ef95806c52bdc2d',1,'Triangulo']]],\n ['operator_21',['operator!',['../class_cuadrado.html#af911d1931dba68c5ed410852569f365b',1,'Cuadrado::operator!()'],['../class_triangulo.html#ab234082ba67e5dd0636b05e24884c470',1,'Triangulo::operator!()']]],\n ['operator_7e',['operator~',['../class_cuadrado.html#a8600ccace0a61a8ba7dd0933bd344b33',1,'Cuadrado::operator~()'],['../class_triangulo.html#a7a8a19fd43cb3181e672b004b4ce83d5',1,'Triangulo::operator~()']]]\n];\n" }, { "alpha_fraction": 0.6194196343421936, "alphanum_fraction": 0.6328125, "avg_line_length": 18.88888931274414, "blob_id": "dc0baa45ee36a243298d4dfa472b57d725ba0d8f", "content_id": "c5abcf066187d1607685f905756e13a0808f368a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 896, "license_type": "no_license", "max_line_length": 79, "num_lines": 45, "path": "/Proyecto2/Cadena.h", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\n\n/* \n * File: Cadena.h\n * Author: jose\n *\n * Created on November 19, 2016, 9:37 PM\n */\n\n#ifndef CADENA_H\n#define CADENA_H\n#include <string>\n#include <iostream>\n#include <time.h>\nclass Cadena {\npublic:\n Cadena();\n int longitud;\n std::string ADN;\n Cadena(int);\n Cadena(std::string);\n Cadena(const Cadena& orig);\n virtual ~Cadena();\n void findPVM(int);\n double** PVM;\n double** MP = 0x0;\n Cadena& operator+=( Cadena other);\n void add( Cadena& other);\n void imprimir();\n std::string motif();\n double ** matrizPesos();\n std::string cadenaComun();\n std::string cadenaDegenerada();\n \nprivate:\n static const std::string letras[4];\n\n};\n\n\n#endif /* CADENA_H */\n\n" }, { "alpha_fraction": 0.5095447897911072, "alphanum_fraction": 0.5183553695678711, "avg_line_length": 15.975000381469727, "blob_id": "0921574db4b4add4ff492f0b8b5e5b7f8980c54e", "content_id": "d14e67d92ab20ff0169021820a40cab4f42b64c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 681, "license_type": "no_license", "max_line_length": 95, "num_lines": 40, "path": "/Lab 2/main.cpp", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "#include \"Figura.h\"\n#include \"Triangulo.h\"\n#include \"Circulo.h\"\n#include \"Cuadrado.h\"\n\nusing namespace std;\n\n/**\n * @file main.cpp\n * @author Jose Alberto Barrantes \n * @date 9 Sep 2016.\n * @brief Main donde se encuentran las pruebas de la clase figura y sus subclases por herencia.\n * \n * \n * \n * \n */\nint main(int argc, char** argv) {\n \n Triangulo* a = new Triangulo(\"Pato\" , \"negro\"); \n ~(*a);\n \n !(*a);\n /*Circulo* b = new Circulo();\n Cuadrado* c = new Cuadrado();\n Triangulo* d = new Triangulo();\n Triangulo x;\n ~(*d);\n !(*d);\n ~(*b) ;\n !(*b);\n ~(*c);\n !(*c); */\n \n return 0;\n delete a;\n //delete b;\n //delete c;\n //delete d;\n}\n\n\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6571428775787354, "avg_line_length": 15, "blob_id": "48dd5b29592c28a6492a75c0f5a14edc9524b3d5", "content_id": "19ae9fca5fc20267f672860b3401d960984215fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 385, "license_type": "no_license", "max_line_length": 79, "num_lines": 24, "path": "/Lab 2/Figura.cpp", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\n\n/* \n * File: Figura.cpp\n * Author: jose\n * \n * Created on September 6, 2016, 2:29 PM\n */\n\n#include \"Figura.h\"\n\nFigura::Figura() {\n}\n\n\nFigura::Figura(const Figura& orig) {\n}\n\nFigura::~Figura() {\n}\n\n" }, { "alpha_fraction": 0.4859813153743744, "alphanum_fraction": 0.672897219657898, "avg_line_length": 25.75, "blob_id": "c810fd5000b7339e759fad16a0de91f3fc2a5380", "content_id": "0d3a80bda8af274515c0e7ac44ddd6cc6c59b535", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 107, "license_type": "no_license", "max_line_length": 85, "num_lines": 4, "path": "/Lab 5/html/search/functions_a.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['suit',['suit',['../class_card.html#ae2a16729f2c4b12afeea5e0524c4a540',1,'Card']]]\n];\n" }, { "alpha_fraction": 0.4810126721858978, "alphanum_fraction": 0.6139240264892578, "avg_line_length": 30.600000381469727, "blob_id": "200c01ca2c6a58609a1cd3223802dc26e90493ef", "content_id": "5afc9a15207b2caad1ac1bebce50406ef286d942", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 158, "license_type": "no_license", "max_line_length": 85, "num_lines": 5, "path": "/Lab 5/html/search/all_e.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['stack',['stack',['../classstack.html',1,'']]],\n ['suit',['suit',['../class_card.html#ae2a16729f2c4b12afeea5e0524c4a540',1,'Card']]]\n];\n" }, { "alpha_fraction": 0.6864407062530518, "alphanum_fraction": 0.6864407062530518, "avg_line_length": 12, "blob_id": "892feaf3066f0b2abc15eb94464305be0af342d7", "content_id": "37c3928dfe324b5b5d3580596c2de8eb9f106996", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 118, "license_type": "no_license", "max_line_length": 46, "num_lines": 9, "path": "/Lab 3/src/Makefile", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "compilar:\t\n\tg++ Fraccion.cpp Poly.cpp Matrix.cpp main.cpp\n\nclean: \n\trm a.out\n\nejecutar:\n\techo \"Calculadora\"\n\t./a.out\n\n" }, { "alpha_fraction": 0.5335608720779419, "alphanum_fraction": 0.5421565175056458, "avg_line_length": 29.89453125, "blob_id": "a667817a9145c7ef8a6cf5cd67c423b962310b8c", "content_id": "d222515d3b5eec3178266000b637d59f714268be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7915, "license_type": "no_license", "max_line_length": 152, "num_lines": 256, "path": "/Lab 3/src/Matrix.cpp", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "\n/* \n * @File: Matrix.cpp\n * @Author: jose\n * \n * @date September 14, 2016, 2:02 PM\n */\n\n#include \"Matrix.h\"\nusing namespace std;\n/**\n * @brief Me crea una matriz de tamaño ingresado por el usuario y llena sus entradas.\n * Me crea una matriz de tamaño definido por el usuario y luego la llena utilizando dos ciclos \"for\" que recorre filas y columnas.\n * @code\n * for (i=0; i < this->size; i++ ) {\n mat[i]= new double[this->size];\n for (j=0; j < this->size; j++) {\n cout << \"ingrese el numero de la casilla: \" << \"[\" << i << \"]\" <<\"[\" <<j<<\"]\" << endl; \n cin >> in;\n mat[i][j] = in;\n }\n }\n * @endcode\n * @param mat Es de tipo double** el cual contiene los datos de cada matriz. Es llenada en el constructor\n * @param size Es la dimension de la matriz, solo forma matrices cuadradas. \n */\nMatrix::Matrix() {\n int a;\n cout << \"Ingrese dimension de las filas\" << endl;\n cin >> a;\n this->filas1 = a;\n int b;\n cout << \"Dimension de las columnas: \" << endl;\n cin >> b;\n this->columnas = b;\n mat = new double*[this->columnas];\n double in; \n int i;\n int j;\n for (i=0; i < this->filas1; i++ ) {\n mat[i]= new double[this->filas1];\n for (j=0; j < this->columnas; j++) {\n cout << \"ingrese el numero de la casilla: \" << \"[\" << i << \"]\" <<\"[\" <<j<<\"]\" << endl; \n cout << \"Si ingresa algo que no sea un numero el programa se cerrara.\" << endl;\n cin >> in;\n mat[i][j] = in;\n }\n }\n \n \n \n}\n/**\n * @brief Constructor utilizado para crear las matrices utilizadas para los resultados de las operaciones.\n * Me crea una matriz nula (puros ceros) de cierta dimension en sus columnas y filas. \n * @param a Parametro utilizado para diferenciar los constructores\n * @param b Dimension de las filas\n * @param c Dimension de las columnas\n */\nMatrix::Matrix(int a, int b, int c) {\n int i;\n int j;\n this->filas1 = b;\n this->columnas = c;\n mat = new double*[this->filas1];\n for (i=0; i < this->filas1; i++ ) {\n mat[i]= new double[this->columnas];\n for (j=0; j < this->columnas; j++) {\n mat[i][j] = 0;\n }\n }\n \n}\n\n/**\n * @brief Me crea una matriz de tamaño definido internamente por el usuario y llena sus entradas.\n * Me crea una matriz de tamaño definido por el usuario y luego la llena utilizando dos ciclos \"for\" que recorre filas y columnas.\n * @code\n * for (i=0; i < this->size; i++ ) {\n mat[i]= new double[this->size];\n for (j=0; j < this->size; j++) {\n cout << \"ingrese el numero de la casilla: \" << \"[\" << i << \"]\" <<\"[\" <<j<<\"]\" << endl; \n cin >> in;\n mat[i][j] = in;\n }\n }\n * @endcode\n * @param mat Es de tipo double** el cual contiene los datos de cada matriz. Es llenada en el constructor\n * @param size Es la dimension de la matriz, solo forma matrices cuadradas.\n * @param a Dimension dado al constructor al inicio para la matriz.\n */\nMatrix::Matrix(int a , int b) {\n this->filas1 = a;\n mat = new double*[this->filas1];\n this->columnas = b;\n double in; \n int i;\n int j;\n for (i=0; i < this->filas1; i++ ) {\n mat[i]= new double[this->columnas];\n for (j=0; j < this->columnas; j++) {\n cout << \"ingrese el numero de la casilla: \" << \"[\" << i << \"]\" <<\"[\" <<j<<\"]\" << endl; \n cin >> in;\n mat[i][j] = in;\n }\n }\n \n}\n/**\n * @brief Imprime las matriz con este operador.\n */\nvoid Matrix::operator ~() {\n int i; \n int j;\n cout << \"Resultado: \" << endl;\n for (i=0; i < this->filas1 ; i++) {\n cout << \"|\";\n for (j=0; j < this->columnas ; j++) {\n cout << this->mat[i][j] << \" \" ;\n }\n cout << \"|\" << endl;\n cout << endl;\n }\n}\n/**\n * @brief Me sume cada entrada de this->mat con other.mat y me imprime el resultado de la suma de estas.\n * @code\n * Matrix result(0, this->filas1, this->columnas);\n int i;\n int j;\n if (this->filas1 == other.filas1 && this->columnas == other.columnas) {\n for (i=0; i < this->filas1; i++ ) {\n for (j=0; j < this->columnas; j++) {\n result.mat[i][j]= this->mat[i][j]+other.mat[i][j]; \n }\n }\n }\n * @endcode\n * @param other Matriz a sumarse con la original.\n */\nMatrix Matrix::operator +(const Matrix &other) {\n Matrix result(0, this->filas1, this->columnas);\n int i;\n int j;\n if (this->filas1 == other.filas1 && this->columnas == other.columnas) {\n for (i=0; i < this->filas1; i++ ) {\n for (j=0; j < this->columnas; j++) {\n result.mat[i][j]= this->mat[i][j]+other.mat[i][j]; \n }\n }\n }\n else {\n throw invalid_argument(\"No se puede sumar matrices si no tiene la misma cantidad de filas al igual que columnas.\");\n }\n cout << \"Suma:\" << endl;\n ~result;\n return result;\n \n}\n/**\n * @brief Me resta cada entrada de this->mat con other.mat y me imprime el resultado de la resta de estas.\n * \n * @param other Matriz a restarse con la original.\n */\nMatrix Matrix::operator -(const Matrix& other) {\n Matrix result(0, this->filas1, this->columnas);\n int i;\n int j;\n if (this->filas1 == other.filas1 && this->columnas == other.columnas) {\n for (i=0; i < this->columnas; i++ ) {\n for (j=0; j < this->columnas; j++) {\n result.mat[i][j]= this->mat[i][j]-other.mat[i][j]; \n }\n }\n }\n else {\n throw invalid_argument(\"No se puede restar matrices si no tiene la misma cantidad de filas al igual que columnas.\");\n }\n cout << \"Resta\" << endl;\n ~result;\n return result;\n \n}\n\n/**\n * @brief Me multiplica las matrices y me imprime el resultado de estas.\n * @param other Matriz a multiplicarse con la primera (la multiplicacion de matrices no permuta).\n * @code\n * int i;\n int j;\n int k;\n double ** result = new double*[this->size];\n for(i=0; i<this->size; ++i){\n result[i] = new double[this->size];\n for(j=0; j<this->size; ++j) {\n for(k=0; k<this->size; ++k) {\n result[i][j]+=this->mat[i][k]*other.mat[k][j];\n }\n }\n }\n Matrix::imprimir(result);\n delete result;\n * @endcode\n */\nMatrix Matrix::operator *(const Matrix& other) {\n Matrix result(0, this->filas1, other.columnas);\n int i;\n int j;\n int k;\n if (this->columnas == other.filas1) {\n for(i=0; i<this->filas1; ++i){\n for(j=0; j<other.columnas; ++j) {\n for(k=0; k<this->columnas; ++k) {\n result.mat[i][j]+=this->mat[i][k]*other.mat[k][j];\n }\n }\n }\n \n }\n else {\n throw invalid_argument(\"Las matrices no se pueden multiplicar ya que no cumplen columnas de la primera matriz igual a filas de la segunda\");\n }\n cout << \"Multiplicar\" << endl;\n ~result;\n \n return result;\n \n}\n/**\n * @brief Me divide la entrada de cada matriz con la entrada de la otra matriz si no tienen la misma cantidad de columnas y filas el programa se detiene\n * @param other Matriz a dividir con la primera (la division no permuta).\n */\nMatrix Matrix::operator /(const Matrix& other) {\n Matrix result(0, this->filas1 , this->columnas);\n int i;\n int j;\n if (this->filas1 == other.filas1 && this->columnas == other.columnas) {\n for (i=0; i < this->columnas; i++ ) {\n for (j=0; j < this->columnas; j++) {\n result.mat[i][j]= this->mat[i][j]/other.mat[i][j]; \n }\n }\n cout << \"Division\" << endl;\n ~result;\n return result;\n }\n else {\n throw invalid_argument(\"No se puede dividir matrices si no tiene la misma cantidad de filas al igual que columnas.\");\n }\n}\n\nMatrix::Matrix(const Matrix& orig) {\n}\n\nMatrix::~Matrix() {\n delete mat;\n}\n\n" }, { "alpha_fraction": 0.6058632135391235, "alphanum_fraction": 0.7459283471107483, "avg_line_length": 75.75, "blob_id": "4d2a7dca3eb78a56f78f10992f7fb61fc27065a7", "content_id": "39b38e2f2b13c7ba6379a27916e73f1106cafef4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 307, "license_type": "no_license", "max_line_length": 285, "num_lines": 4, "path": "/Lab 1/html/search/all_1.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['imprimirarreglodechar',['imprimirArregloDeChar',['../_a_r_na_a_a_8cpp.html#a936edfd96c1e058d6ffdd91cd9f1fd2a',1,'imprimirArregloDeChar(char *a, int n):&#160;ARNaAA.cpp'],['../lab1_8h.html#ab18ae1dcdbbde9965371ef3d9a89950b',1,'imprimirArregloDeChar(char *, int):&#160;ARNaAA.cpp']]]\n];\n" }, { "alpha_fraction": 0.6143601536750793, "alphanum_fraction": 0.6276780366897583, "avg_line_length": 28.27118682861328, "blob_id": "96729a756467de2a1d7872c74acf90f1fd30ec3f", "content_id": "256e565c6d0dc6e52a4115c8815bed74a756836d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1728, "license_type": "no_license", "max_line_length": 109, "num_lines": 59, "path": "/Lab 1/Lab1.cc", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "/**\n* @file Lab1.cc\n* @author Jose Alberto Barrantes\n* @date 28 Aug 2016.\n* @brief Programa para obtener la cadena de aminoacidos a partir de una de RNA. \n* Por el medio de dos funciones la cadena ARN obtiene su equivalente en aminoacidos \n* con la ayuda de la funcion ARNaAA. \n* Luego n cantidad de aminoacidos son impresos con la funcion imprimirArregloDeChar.\n*\n*/\n#include \"lab1.h\"\n\n/**\n* Funcion principal que revisa si la cadena de ARN es multiplo de 3 para correr el programa o no. \n* @code \n* \n int i;\n int j;\n int aaAImprimir;\n cout << \"\" << endl;\n int longitud = strlen(argv[1]);\n if (longitud % 3 == 0) {\n cout << \"Numero de Aminoacidos a imprimir: \" ;\n cin >> aaAImprimir;\n cout << endl;\n imprimirArregloDeChar(ARNaAA(argv[1] , strlen(argv[1])), aaAImprimir ); \n }\n else {\n throw invalid_argument(\"Cadena de multiplo diferente de tres\");\n }\n \n return 0;\n * @endcode\n * @param longitud[in] Se utiliza para hacer entero la funcion strlen(). Luego se revisa si es multiplo de 3.\n * @param argc\n * @param argv\n * @param aaImprimir[in] Cantidad de aminoacidos a imprimir del total traducido de la cadena ARN original. \n * @return Devuelve un 0 en funcion de señal que todo salio bien.\n */\nint main(int argc, char**argv) {\n \n int i;\n int j;\n int aaAImprimir;\n cout << \"\" << endl;\n int longitud = strlen(argv[1]);\n if (longitud % 3 == 0) {\n cout << \"Numero de Aminoacidos a imprimir: \" ;\n cin >> aaAImprimir;\n cout << endl;\n imprimirArregloDeChar(ARNaAA(argv[1] , strlen(argv[1])), aaAImprimir ); \n }\n else {\n throw invalid_argument(\"Cadena de multiplo diferente de tres\");\n }\n \n return 0;\n \n}\n" }, { "alpha_fraction": 0.5089285969734192, "alphanum_fraction": 0.71875, "avg_line_length": 43.79999923706055, "blob_id": "73b8042adb60b283c86e5229af0763e35b2b5c89", "content_id": "ccc9c5960efd91df86c5021e6b791d44b58933a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 224, "license_type": "no_license", "max_line_length": 105, "num_lines": 5, "path": "/Lab 5/html/search/all_4.js", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "var searchData=\n[\n ['filltables',['filltables',['../casino_8cpp.html#abd64006b774edcaec7215c836b6009bf',1,'casino.cpp']]],\n ['findwinner',['findwinner',['../classmesa.html#a56a722015043f6f45102e48ba3236e18',1,'mesa']]]\n];\n" }, { "alpha_fraction": 0.6086956262588501, "alphanum_fraction": 0.6376811861991882, "avg_line_length": 16, "blob_id": "f5fc879365d1af6d014308abafb47a80d4e266ee", "content_id": "3cf462faea726b90bfc9878be462ff666b5525b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 69, "license_type": "no_license", "max_line_length": 38, "num_lines": 4, "path": "/Lab 5/Makefile", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "compilar:\n\tg++ -std=c++11 casino.cpp -o casino \nclean: \n\trm casino\n\n" }, { "alpha_fraction": 0.4881248474121094, "alphanum_fraction": 0.5023750066757202, "avg_line_length": 21.66153907775879, "blob_id": "4cb30b0f55252db5fda505787d3a28021be76e02", "content_id": "50ccdd9e35c3a65643e712648ed48638f3c8eb94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4421, "license_type": "no_license", "max_line_length": 96, "num_lines": 195, "path": "/Lab 3/src/Poly.cpp", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "\n/* \n * @File: Matrix.cpp\n * @Author: jose\n * \n * @date September 14, 2016, 2:02 PM\n */\n#include \"Poly.h\"\nusing namespace std;\n/**\n * @brief Me llena el arreglo this->arg con ceros. \n * Me crea un polinomio vacio de grado 1000.\n */\nPoly::Poly() {\n for (int i = 0; i<1000 ; i++) {\n arg[i] = 0;\n }\n\n}\n/**\n * @brief Me llena un polinomio con grado ingresado por el usuario en el constructor.\n * @code\n * degree = a+1;\n int add;\n for (int i = 0; i<degree; i++) {\n std::cout << \"Ingrese coeficiente : \" << i << \" \" <<std::endl;\n std::cin >> add;\n arg[i] = add;\n }\n * @endcode\n * @param a Grado a llenar el polinomio.\n */\nPoly::Poly(int a) {\n degree = a+1;\n int add;\n for (int i = 0; i<degree; i++) {\n std::cout << \"Ingrese coeficiente : \" << i << \" \" <<std::endl;\n std::cin >> add;\n arg[i] = add;\n }\n}\n/**\n * @brief Me suma dos polinomios.\n * @code\n * Poly result;\n for (int i = 0; i<=this->degree; i ++) {\n result.arg[i] += this->arg[i];\n }\n for (int j = 0; j<=other.degree; j++) {\n result.arg[j] += other.arg[j];\n }\n * @endcode\n * \n * @param other Polinomio a sumar con el primero\n * @return Polinomio de resultado. \n */\nPoly Poly::operator +(const Poly& other) {\n Poly result;\n for (int i = 0; i<=this->degree; i ++) {\n result.arg[i] += this->arg[i];\n }\n for (int j = 0; j<=other.degree; j++) {\n result.arg[j] += other.arg[j];\n }\n result.degree = result.obtenerGrado();\n ~result;\n return result;\n}\n/**\n * @brief Me imprime un polinomio de algun degree (grado).\n * @code\n * for (int i=0; i<999; i++)\n {\n if (arg[i] != 0 ) { \n cout << this->arg[i];\n if (i != 0)\n cout << \"x^\" << i ;\n \n if (i != this->degree)\n cout << \" + \";\n }\n }\n * @endcode\n */\nvoid Poly::operator ~() {\n for (int i=0; i<999; i++)\n {\n if (arg[i] != 0 ) { \n cout << this->arg[i];\n if (i != 0)\n cout << \"x^\" << i ;\n \n if (i != this->degree)\n cout << \" + \";\n }\n }\n cout << endl;\n \n}\n/**\n * @brief Me resta dos polinomios\n * @code\n * Poly result;\n for (int i = 0; i<=this->degree; i ++) {\n result.arg[i] += this->arg[i];\n }\n for (int j = 0; j<=other.degree; j++) {\n result.arg[j] -= other.arg[j];\n }\n * @endcode\n * \n * @param other Polinimio a restar al primero\n * @return Polinomio respuesta\n */\nPoly Poly::operator -(const Poly& other) {\n Poly result;\n for (int i = 0; i<=this->degree; i ++) {\n result.arg[i] += this->arg[i];\n }\n for (int j = 0; j<=other.degree; j++) {\n result.arg[j] -= other.arg[j];\n }\n result.degree = result.obtenerGrado();\n ~result;\n return result;\n}\n/**\n * @brief Me multiplica dos polinomios\n * @code\n * Poly result;\n for (int i = 0; i<= this->degree; i++)\n for (int j = 0; j<=other.degree; j++) {\n result.arg[i+j] += (this->arg[i] * other.arg[j]); \n }\n * @endcode\n * @param other Polinomio a multiplicar\n * @return Polinomio respuesta\n */\nPoly Poly::operator *(const Poly& other) {\n Poly result;\n for (int i = 0; i<= this->degree; i++)\n for (int j = 0; j<=other.degree; j++) {\n result.arg[i+j] += (this->arg[i] * other.arg[j]); \n }\n result.degree = result.obtenerGrado();\n ~result;\n return result;\n}\n/**\n * @brief Me obtiene el grado efectivo de un polinomio. Dato utilizado puramente para impresion.\n * @code\n * int grad = 0;\n for (int i = 0; i<=999; i++) {\n if (this->arg[i]!=0) {\n grad = i; \n }\n }\n return grad;\n * @endcode\n * @return Entero que muestra el grado efectivo de un polinomio.\n */\nint Poly::obtenerGrado() {\n int grad = 0;\n for (int i = 0; i<=999; i++) {\n if (this->arg[i]!=0) {\n grad = i; \n }\n }\n return grad;\n}\n/**\n * @brief Me obtiene la derivada de un polinomio.\n * @code \n * Poly result;\n for (int i = 1; i <= this->degree; i++) {\n result.arg[i-1] = this->arg[i]*i; \n }\n * @endcode\n * \n * @return Me devuelve el polinomio derivado de algun polinomio\n */\nPoly Poly::operator !() {\n Poly result;\n for (int i = 1; i <= this->degree; i++) {\n result.arg[i-1] = this->arg[i]*i; \n }\n result.degree = result.obtenerGrado();\n ~result;\n return result;\n}\n\nPoly::Poly(const Poly& orig) {\n}\n\nPoly::~Poly() {\n}\n\n" }, { "alpha_fraction": 0.6507537961006165, "alphanum_fraction": 0.6633166074752808, "avg_line_length": 22.860000610351562, "blob_id": "6fb6ca931ba8a621b98c1f41e21ed9dff1d714b0", "content_id": "f61f89326aa8f663d0872cd528023af28c7ea971", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1194, "license_type": "no_license", "max_line_length": 113, "num_lines": 50, "path": "/Lab 0/C/suma.c", "repo_name": "CursosIE/IE-0217-II-16-G2", "src_encoding": "UTF-8", "text": "/**\n* @file suma.c\n* @author Jose Alberto\n* @date 19 Aug 2016 \n* @brief Programa para sumar argumentos flotantes ingresados. \n*\n* Metodo el cual suma los argumentos flotantes ingresados a la hora de correr el programa, luego \n* retorna el resultado de dicha suma de argumentos. \n*/ \n#include <stdio.h>\n\nfloat sumar (int a, char **b) {\n/** \n* @brief Funcion para sumar argumentos\n* @code \n* for (int i=1;i<a;i++) {\n*\t\tfloat num;\n*\t\tsscanf(b[i], \"%f\", &num);\n*\t\tsuma+=num; \n*\t}\n*\treturn suma;\n*\n* @endcode\n* @param num Variable para guardar temporalmente cada argumento ingresado para sumarse.\n* @param suma Variable la cual recibe y guarda el resultado de la suma de la fila de argumentos * ingresados. \n* @return Funcion devuelve el resultado de la suma \n*/\n\tfloat suma=0.0;\n\tfor (int i=1;i<a;i++) {\n\t\tfloat num;\n\t\tsscanf(b[i], \"%f\", &num);\n\t\tsuma+=num; \n\t}\n\treturn suma;\n}\n\nint main(int argc, char **argv) {\n/** \n* @brief Funcion principal que corre el programa. \n* @code \n*float result= sumar(argc, argv);\n*\tprintf(\"%.6f\\n\",result);\n*\treturn 0;\n* @endcode\n* @return Devuelve un 0 para mostrar que todo se corrio bien.\n*/\n\tfloat result= sumar(argc, argv);\n\tprintf(\"%.6f\\n\",result);\n\treturn 0;\n}\n\n" } ]
86
strahman/django-niftyurls
https://github.com/strahman/django-niftyurls
417c64f0867c0d79f9fc5d2836b33c22fdcbb00b
addaa58afb0fea432b2c9eabdc44c3b71b38b475
8e34f694591d48ff34c490f6f40fff2119a5ae4c
refs/heads/master
2020-04-05T23:36:20.704455
2011-11-16T09:27:52
2011-11-16T09:27:52
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7873563170433044, "alphanum_fraction": 0.8045976758003235, "avg_line_length": 33.79999923706055, "blob_id": "c9e6ceec95d26efbf22630b7c08948cb49f5a588", "content_id": "44abefcea8addb89ea44fa3602bc255fe3d6f707", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 174, "license_type": "permissive", "max_line_length": 58, "num_lines": 5, "path": "/demo_project/views.py", "repo_name": "strahman/django-niftyurls", "src_encoding": "UTF-8", "text": "from django.http import Http404, HttpResponse\nfrom django.views.generic.simple import direct_to_template\n\ndef home(request):\n\treturn direct_to_template(request, 'home.html')\n" }, { "alpha_fraction": 0.6437378525733948, "alphanum_fraction": 0.6482803225517273, "avg_line_length": 30.4489803314209, "blob_id": "2189d234e0cba29ac261736c77bc93bdcb1be297", "content_id": "18fba6a71c13b1815f7d4a587f2de98a45e349ce", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3082, "license_type": "permissive", "max_line_length": 107, "num_lines": 98, "path": "/niftyurls/templatetags/niftyurls_tags.py", "repo_name": "strahman/django-niftyurls", "src_encoding": "UTF-8", "text": "import re, sys\n\nfrom django.contrib.sites.models import RequestSite\nfrom django.contrib.sites.models import Site\nfrom django import template\n\nfrom niftyurls.models import Feed\nfrom niftyurls.settings import NIFTYURLS_SETTINGS, NIFTYURLS_JS, \\\n NIFTYURLS_CSS, NIFTYURLS_MEDIA\n\nregister = template.Library()\n\ndef replace( string, args ): \n search = args.split(args[0])[1]\n replace = args.split(args[0])[2]\n return re.sub( search, replace, string )\n\nregister.filter('replace', replace)\n\ndef get_site(context):\n domain = RequestSite(context['request']).domain.replace('www.', '')\n try:\n current_site = Site.objects.get(domain=domain)\n except Site.DoesNotExist:\n current_site = Site.objects.get(domain='example.com')\n return current_site\n\ndef get_settings(context):\n domain = RequestSite(context['request']).domain.replace('www.', '')\n if not context.render_context.get(domain):\n settings = dict(NIFTYURLS_SETTINGS).get('example.com', {})\n settings.update(dict(NIFTYURLS_SETTINGS).get(domain, {}))\n context.render_context[domain] = settings\n\n return context.render_context.get(domain)\n\ndef niftyurls_content(context):\n settings = get_settings(context)\n current_site = get_site(context)\n \n feeds = Feed.objects.filter(sites=current_site)\n \"\"\" filter feeds with less than N entries \"\"\"\n feeds = filter(lambda feed: feed.entry_set.count()>4, feeds)\n \n rows_settings = settings.get('rows', 3)\n \n feeds_per_row = []\n start = 0\n \"\"\"\n 3,2 means 3 rows, 3 columns on the first row, 2 columns on the second row \n \"\"\"\n columns = rows_settings.split(',')\n while len(columns) < len(feeds):\n columns.append(columns[-1]) # repeat the last number of columns\n\n for col in columns:\n end = start+int(col)\n feeds_per_row.append(feeds[start:end])\n start = end\n \n extra_context = {\n 'rows':feeds_per_row,\n 'current_site': current_site,\n 'NIFTYURLS_MEDIA': NIFTYURLS_MEDIA,\n } \n context.update(extra_context)\n return context\n\ndef niftyurls_media(args):\n context = {}\n \n if 'js' in args:\n context.update(dict(js_files=list(NIFTYURLS_JS)))\n if 'css' in args:\n context.update(dict(css_files=list(NIFTYURLS_CSS)))\n \n return context\n\ndef niftyurls_settings(parser, token):\n try:\n tag_name, arg = token.split_contents()\n except ValueError:\n raise template.TemplateSyntaxError, \"%r tag requires a single argument\" % token.contents.split()[0]\n\n return NiftySettings(arg)\n\nclass NiftySettings(template.Node):\n def __init__(self, arg):\n self.arg = arg\n\n def render(self, context):\n settings = get_settings(context)\n return settings.get(self.arg, None)\n \n \nregister.inclusion_tag('niftyurls/content.html', takes_context = True)(niftyurls_content)\nregister.inclusion_tag('niftyurls/media.html')(niftyurls_media)\nregister.tag('niftyurls_settings', niftyurls_settings)\n" }, { "alpha_fraction": 0.6130726337432861, "alphanum_fraction": 0.6268332600593567, "avg_line_length": 53.787879943847656, "blob_id": "5e67bf5c2bc1bba33045dc7ff6e759c5867200aa", "content_id": "5a87864013446c8231c1f65933e0075993c766d4", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 5523, "license_type": "permissive", "max_line_length": 646, "num_lines": 99, "path": "/niftyurls/media/niftyurls/fontresizer/fontResizer.html", "repo_name": "strahman/django-niftyurls", "src_encoding": "UTF-8", "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n<title>fontResizer Example</title>\r\n<style type=\"text/css\">\r\n.bold { font-weight: 900; }\r\n.boldDef { font-weight: 900; color: #CD0000; }\r\na { outline: none; }\r\n.ON { font-weight: 900; color: #F00; }\r\n.DISABLED { cursor: default; color: #CCC; }\r\n</style>\r\n<script src=\"jquery-1.4.min.js\" type=\"text/javascript\" language=\"javascript\"></script>\r\n<script src=\"jquery.fontResizer-2.0.js\" type=\"text/javascript\" language=\"javascript\"></script>\r\n<script type=\"text/javascript\" language=\"javascript\">\r\n$(document).ready(function() {\r\n\t$('#content p, .resizeMe, .resizeSpan').fontResizer({minFont:10,maxFont:20,increment:1});\r\n});\r\n</script>\r\n\r\n</head>\r\n<body>\r\n<h1>jquery.fontResizer-2.0.js</h1>\r\n<hr />\r\n<div class=\"adjustFont\">\r\n <div>\r\n <a class=\"increaseClickItem\" href=\"\">Up Font</a>\r\n <a class=\"decreaseClickItem\" href=\"\">Down Font</a>\r\n </div>\r\n <div>\r\n <a class=\"setFontSize\" title=\"10\" href=\"\">10px</a>\r\n <a class=\"setFontSize\" title=\"15\" href=\"\">15px</a>\r\n <a class=\"setFontSize\" title=\"20\" href=\"\">20px</a>\r\n </div>\r\n</div>\r\n\r\n<div id=\"content\">\r\n <h2>Font can be changed incrementally or to specific sizes.</h2>\r\n <h3 class=\"boldDef\">Items marked in red are DEFAULTS which can be adjusted easily.</h3>\r\n <ul>\r\n <li>For incremental changes:\r\n <ul>\r\n <li>Any element with class name <span class=\"increaseClickItem bold\">increaseClickItem</span> will increase the font size.</li>\r\n <li>Any element with class name <span class=\"decreaseClickItem bold\">decreaseClickItem</span> will decrease the font size.</li>\r\n <li>The Default <span class=\"boldDef\">increment</span> value is <span class=\"boldDef\">2</span>. <em>See below for example of ways to change the options.</em></li>\r\n </ul>\r\n </li>\r\n </ul>\r\n <p>When the <span class=\"boldDef\">minFont</span> or <span class=\"boldDef\">maxFont</span> values are reached, class <span class=\"boldDef\">DISABLED</span> will be passed to <span class=\"bold\">increaseClickItem / decreaseClickItem</span> classes, respectively. The same is true if the <span class=\"boldDef\">fontResizer</span> cookie returns a value that matches <span class=\"boldDef\">minFont</span> or <span class=\"boldDef\">maxFont</span>.</p>\r\n <ul>\r\n <li>For specific changes:\r\n <ul>\r\n <li>Any element with class name <span class=\"setFontSize bold\" title=\"18\">setFontSize</span> will set the font size.</li>\r\n <li>The size to be set is determined via the <em class=\"bold\">title</em> attribute which needs to be passed when the class is set.</li>\r\n <li>Example: <span class=\"bold\">&lt;a class=\"setFontSize\" title=\"20\"&gt;</span> will set font size to 20.</li>\r\n </ul>\r\n </li>\r\n </ul>\r\n <p>When an element with class <span class=\"bold\">setFontSize</span> is clicked, class <span class=\"boldDef\">ON</span> will be passed to it. When another element with class <span class=\"bold\">setFontSize</span> is clicked, <span class=\"boldDef\">ON</span> will be removed from the previous element. This also occurs when <span class=\"bold\">increaseClickItem / decreaseClickItem</span> elements are clicked and reach a value that matches a <span class=\"bold\">setFontSize</span> elements value. The same is true if the <span class=\"boldDef\">fontResizer</span> cookie returns a value that matches a <span class=\"bold\">setFontSize</span> value.</p>\r\n</div>\r\n<div class=\"resizeMe\">\r\n <p>General Defaults are as follows:</p>\r\n <ul>\r\n <li>sizeType: 'px'</li>\r\n <li>minFont: 12</li>\r\n <li>maxFont: 16</li>\r\n <li>fontSet: 14</li>\r\n <li>setFontOn: 'ON'</li>\r\n <li>increment: 2</li>\r\n <li>incrementDisable: 'DISABLED'</li>\r\n </ul>\r\n <p>Cookie Defaults are as follows:</p>\r\n <ul>\r\n <li>cookieName: 'fontResizer'</li>\r\n <li>cookieExpire: cExpireDate\r\n <ul>\r\n\t\t\t\t<li>cExpireDate is set to the Month/Day the cookie is set, one year from it's creation.</li>\r\n </ul>\r\n <p>Variables used for cExpireDate: (override as needed for alternate cookie expiration or create new)<br />\r\n var date = new Date();<br />\r\n var currYear = date.getFullYear();<br />\r\n var currMonth = date.getMonth();<br />\r\n var currDay = date.getDate();<br />\r\n var cExpire = new Date(currYear + 1, currMonth, currDay);<br />\r\n var cExpireDate = cExpire.toUTCString();<br />\r\n </p>\r\n </li>\r\n <li>cookiePath: '/'</li>\r\n </ul>\r\n</div>\r\n<p>Implementation consists of calling the <span class=\"bold\">fontResizer</span> function on a comma-seperated list of elements:<br />\r\n <span class=\"bold\">Example:<br />\r\n $(document).ready(function() {<br />\r\n &nbsp;&nbsp;&nbsp;&nbsp;$('#content p, .resizeMe, .resizeSpan').fontResizer({minFont:10,maxFont:20,increment:1});<br />\r\n });\r\n </span><br />\r\n <span class=\"resizeSpan\"><em>Note that Default Overrides (<span class=\"bold\">OPTIONS</span>) are passed as params within curly braces. Pay close attention to quote inclusion. When in doubt refer to the Default lists above.</em></span></p>\r\n</body>\r\n</html>\r\n" }, { "alpha_fraction": 0.5557098388671875, "alphanum_fraction": 0.5584866404533386, "avg_line_length": 32.5, "blob_id": "f112b55b0518047078dda514c3097766ecac9499", "content_id": "c428653109fccd8df45829b84f2035460b3cc894", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2881, "license_type": "permissive", "max_line_length": 90, "num_lines": 86, "path": "/niftyurls/fetch_feed.py", "repo_name": "strahman/django-niftyurls", "src_encoding": "UTF-8", "text": "import socket\nsocket.setdefaulttimeout(60)\nimport datetime, time, urllib2, urlparse #, sys, json, zlib, signal\nimport feedparser\n\nclass NiftyUrlsException(Exception):\n pass\n\nclass FetchFeed(object):\n def __init__(self, link, page_url=None):\n self.link = link\n self.page_url = page_url # useful for deciding on getting the real url or not\n self.page_url_parsed = urlparse.urlparse(self.page_url)\n\n def get_item_summary(self, item):\n summary = ''\n if hasattr(item, \"summary\"):\n summary = item.summary\n elif hasattr(item, \"content\"):\n summary = item.content[0].value\n elif hasattr(item, \"description\"):\n summary = item.description\n return summary\n \n def get_item_pubdate(self, item):\n pubdate = None\n attrs = ['updated_parsed', 'published_parsed', 'date_parsed', \n 'created_parsed']\n \n for attr in attrs:\n if hasattr(item, attr):\n pubdate = getattr(item, attr)\n break\n \n if pubdate:\n try:\n ts = time.mktime(pubdate)\n return datetime.datetime.fromtimestamp(ts)\n except TypeError:\n pass\n \n return datetime.datetime.now()\n \n def get_final_url(self, entry):\n entry_link_parsed = urlparse.urlparse(entry.link)\n if entry_link_parsed.hostname!=self.page_url_parsed.hostname:\n u = urllib2.urlopen(entry.link)\n entry_link = u.geturl() # get the real url\n u.close()\n else:\n entry_link = entry.link\n return entry_link\n \n def sanitize_item(self, entry):\n #entry_link = self.get_final_url(entry)\n entry_link = entry.link\n return {\n 'title': entry.title,\n 'link': entry_link,\n 'description': self.get_item_summary(entry), \n 'guid': entry.get(\"id\", entry.link),\n 'pubdate': self.get_item_pubdate(entry),\n }\n\n def fetch_feed(self):\n self.data = feedparser.parse(self.link)\n if 'bozo' in self.data and self.data.bozo:\n raise NiftyUrlsException('Error fetching %s' % self.link)\n return True\n\n \"\"\"\n def fetch_feed(self):\n def timeout(signum, frame):\n raise NiftyUrlsException('Timeout fetching %s' % self.link)\n signal.signal(signal.SIGALRM, timeout)\n signal.alarm(65) # timeout in X seconds, in case that socket timeout isn't working\n try:\n self.data = feedparser.parse(self.link)\n if 'bozo' in self.data and self.data.bozo:\n raise NiftyUrlsException('Error fetching %s' % self.link)\n except Exception as e:\n signal.alarm(0)\n raise(e)\n \n return True\n \"\"\"\n" }, { "alpha_fraction": 0.7248908281326294, "alphanum_fraction": 0.7248908281326294, "avg_line_length": 27.625, "blob_id": "5e69257712cd76a6b777fc29abf7da69c782fc50", "content_id": "65b796f8f73d5b13df0492c7d09573b6d4a5395f", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 458, "license_type": "permissive", "max_line_length": 48, "num_lines": 16, "path": "/niftyurls/admin.py", "repo_name": "strahman/django-niftyurls", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom models import Source, Feed, Entry, MetaData\n\nclass FeedAdmin(admin.ModelAdmin):\n #prepopulated_fields = {\"slug\": (\"title\",)}\n pass\n\nclass EntryAdmin(admin.ModelAdmin):\n #date_hierarchy = 'date'\n list_display = ('title', 'feed')\n search_fields = ['title', 'description']\n\nadmin.site.register(Source)\nadmin.site.register(Feed, FeedAdmin)\nadmin.site.register(Entry, EntryAdmin)\nadmin.site.register(MetaData)\n" }, { "alpha_fraction": 0.6235359907150269, "alphanum_fraction": 0.6285554766654968, "avg_line_length": 25.776119232177734, "blob_id": "c22059166a26957fbf33f4fe5f0acb4663ec977e", "content_id": "22deb412f8ac86200ecb3246e006fc3f055d0f25", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1793, "license_type": "permissive", "max_line_length": 92, "num_lines": 67, "path": "/niftyurls/media/niftyurls/js/niftyurls.js", "repo_name": "strahman/django-niftyurls", "src_encoding": "UTF-8", "text": "$(document).ready(function() {\n\n/* next/prev links */\nfunction switchUL(hidenode, shownode, event, context) {\n\tvar wrapper = $(context).parent().parent();\n\t$(hidenode, wrapper).fadeOut('fast', function() {\n\t\t$(hidenode, wrapper).removeClass('active');\n\t\t$(hidenode, wrapper).css('display', 'none');\n\t\t$(shownode, wrapper).fadeIn();\n\t\t$(shownode, wrapper).addClass('active');\n\t})\n\tevent.preventDefault();\n};\n$(\"a.forward\").click(function(event) {\n\tevent.preventDefault();\n\tswitchUL('.page1', '.page2', event, this)\n});\n$(\"a.backward\").click(function(event) {\n\tevent.preventDefault();\n\tswitchUL('.page2', '.page1', event, this)\n});\n/* pop link */\n$('a.anchor_pop').click(function(event) {\n\tevent.preventDefault();\n\tvar unit = $(this).parents('.unit')\n\tvar active_view = $(\".active\", unit).clone();\n\tactive_view.addClass('view_pop')\n\t\n\tvar clone = $('#niftyclone');\n\tclone.hide();\n\t$('*', clone).remove();\n\tclone.append(active_view);\n\t$('*', clone).removeClass('hidden');\n\t\n\t$.facebox({ div: '#niftyclone' })\n});\n/* page link */\n$('a.anchor_page').click(function(event) {\n\tevent.preventDefault();\n\tvar unit = $(this).parents('.unit')\n\tvar active_view = $(\".active\", unit).clone();\n\tactive_view.addClass('view_page');\n\t\n\tvar backlink = '<a href=\"javascript:void(0);\" class=\"anchor_back red\">Exit View</a><hr />';\n\t\n\tvar clone = $('#niftyclone');\n\tclone.hide();\n\t$('*', clone).remove();\n\tclone.append(backlink);\n\tclone.append(active_view);\n\tclone.append(backlink);\n\t$('.anchor_back', clone).click(function() {\n\t\tclone.fadeOut('fast');\n\t\t$('*', clone).remove();\n\t\t$('#niftyurls').fadeIn('fast');\n\t});\n\t$('#niftyurls').fadeOut('fast');\n\tclone.fadeIn('fast');\n\t$('*', clone).removeClass('hidden');\n});\n\n/* cufon actions */\nCufon.replace('h2.niftyurls', {\n\tfontFamily : 'Museo 500'\n});\nCufon.now();\n});" }, { "alpha_fraction": 0.5753575563430786, "alphanum_fraction": 0.5841584205627441, "avg_line_length": 27.40625, "blob_id": "97fc9d7e8c32ce73ab4a1d22d5d6818981581207", "content_id": "893324d030f05803531b9652f365a5fda61889c5", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 909, "license_type": "permissive", "max_line_length": 54, "num_lines": 32, "path": "/setup.py", "repo_name": "strahman/django-niftyurls", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom distutils.core import setup, find_packages\n\nsetup(\n name='django-niftyurls',\n version='1.0.0-alpha',\n description='A popurls style Django application.',\n author='Florentin Sardan',\n author_email='[email protected]',\n long_description=open('README.md', 'r').read(),\n url='http://www.betterprogramming.com/',\n\tpackages=find_packages(exclude=('demo_project')),\n packages=[\n 'niftyurls',\n ],\n\tinstall_requires = [\n 'Django>=1.2.1',\n 'PIL',\n 'feedparser',\n ],\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: Utilities'\n ],\n)\n" }, { "alpha_fraction": 0.7650363445281982, "alphanum_fraction": 0.7732980847358704, "avg_line_length": 62.04166793823242, "blob_id": "e3dd6d1ea8220ff92beb0d7f643dd7a2c4a8b2ff", "content_id": "e1a09e603b59e67a06b7cfb597ad20da9808b599", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3026, "license_type": "permissive", "max_line_length": 420, "num_lines": 48, "path": "/README.md", "repo_name": "strahman/django-niftyurls", "src_encoding": "UTF-8", "text": "#Hello and welcome\n\nNiftyurls is a popurls-style script built entirely with Django.\n\n#View some examples\n\n* [JavascriptNews][www.JavascriptNews.com]\n* [PythonDaddy][www.PythonDaddy.com]\n\n#Excerpt from the popurls site:\n\n> \"... is the dashboard for the latest web-buzz, a single page that encapsulates up-to-the-minute headlines from the most popular sites on the internet.\"\n\n#Unique features\n\n* Powered by Django\n* No tooltips by default, there are better ways of reading the text\n* Read the news in a Facebook-style lightbox (\"pop\" layout)\n* Read the news in a clean page (\"page\" layout)\n* Easy editable feed settings, titles, urls, positions in the page\n* Javascript assisted by jQuery\n* Grid templates provided by Yui3 Grids\n* Fast text replacement with Cufon\n\n#Wish list\n\n* remember visitor's last viewed links, mark new/old links\n* show new links only\n* videos support\n* admin interface for feed configuration, more config options\n* multiple domain support\n* site search with database support\n* usability improvements\n* user accounts, openid support\n* code comments, svn support\n\n#Installation (linux, localhost)\n\n1. Make sure you have the following Python packages available: Django - http://pypi.python.org/pypi/Django/ Pil - http://pypi.python.org/pypi/PIL/ Feedparser - http://pypi.python.org/pypi/feedparser/ You may install these with the \"pip\" tool (http://pypi.python.org/pypi/pip/) $ pip install \"django>=1.3\" $ pip install pil $ pip install feedparser\n2. Add \"niftyurls\" to the INSTALLED_APPS tuple. The Niftyurls application depends on the following Django packages: 'django.contrib.staticfiles' 'django.contrib.admin' To make sure every app is enabled, add the following line to your project's \"settings.py\" file: INSTALLED_APPS += ('django.contrib.staticfiles', 'django.contrib.admin', 'niftyurls', )\n3. Synchronize the database $ python manage.py syncdb\n4. To add the \"niftyurls\" in your templates, use the following:\n{% load niftyurls_tags %} {% niftyurls_media \"js,css\" %} {% niftyurls_content %}\n\n5. Please check the available Niftyurls settings in niftyurls/settings.py You may add custom values to NIFTYURLS_SETTINGS (please see niftyurls/settings.py) and retrive them inside your templates with: {% niftyurls_settings title %} {% niftyurls_settings h1 %}\n6. Add some feeds in the admin interface http://127.0.0.1:8000/admin/niftyurls/feed/add/ Here are some feed urls examples: - http://feeds.delicious.com/v2/rss/popular/python?count=15 - http://www.reddit.com/.rss\n7. Run the following command so that fresh entries are added to the database. $ python manage.py niftyurls_feeds\n8. Niftyurls templatetags depend on the existing of the \"request\" inside the templates, in case of errors verify that you have passed the \"RequestContext\" to the templates. http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext Make sure the TEMPLATE_CONTEXT_PROCESSORS contains the following: ('django.core.context_processors.request', 'django.contrib.auth.context_processors.auth',)\n" }, { "alpha_fraction": 0.6779179573059082, "alphanum_fraction": 0.6832807660102844, "avg_line_length": 34.233333587646484, "blob_id": "231493df3eb0588953256fbbd01b74c58264efe7", "content_id": "6986ce45ca1cd5f512175421158c9ca884ab5542", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3170, "license_type": "permissive", "max_line_length": 92, "num_lines": 90, "path": "/niftyurls/models.py", "repo_name": "strahman/django-niftyurls", "src_encoding": "UTF-8", "text": "import datetime\nfrom django.utils.translation import ugettext as _\nfrom django.db import models\nfrom django.contrib.sites.models import Site\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import generic\nfrom django.contrib.auth.models import User\nfrom django.template.defaultfilters import slugify\n\nclass BasicModel(models.Model):\n is_published = models.BooleanField(default=True, help_text=_('This object is enabled.'))\n is_featured = models.BooleanField(default=False, help_text=_('This object is special.'))\n created = models.DateTimeField(auto_now_add=True, db_index=True)\n modified = models.DateTimeField(auto_now=True, db_index=True)\n\n class Meta(object):\n abstract = True\n\n \nclass Source(BasicModel):\n \"\"\"\n A source is a general news source, like CNN, who may provide multiple feeds.\n \"\"\"\n title = models.CharField(max_length=255)\n #slug = models.SlugField(max_length=255, editable=False)\n link = models.URLField()\n description = models.TextField(blank=True)\n logo = models.ImageField(blank=True, upload_to='images/logos')\n \n class Meta(object):\n ordering = ('title',)\n \n def save(self, *args, **kwargs):\n self.slug = slugify(self.title)\n super(Feed, self).save(*args, **kwargs)\n \n def __unicode__(self):\n return u'%s' % self.title\n\n\nclass Feed(BasicModel):\n \"\"\"\n A feed is the actual RSS/Atom feed that will be downloaded. It has a\n many-to-many relationship to categories through the FeedCategoryRelationship\n model, which allows white-lists to be applied to the feed before articles\n will be added to the category.\n \"\"\"\n title = models.CharField(max_length=255)\n link = models.URLField(unique=True)\n page_url = models.URLField(blank=True, null=True)\n description = models.TextField()\n pubdate = models.DateTimeField(blank=True, null=True)\n source = models.ForeignKey(Source, blank=True, null=True)\n sites = models.ManyToManyField(Site)\n last_downloaded = models.DateTimeField(auto_now=True)\n \n class Meta(object):\n ordering = ('title',)\n \n def __unicode__(self):\n return u'%s - %s' % (self.source.title, self.title)\n\nclass Entry(BasicModel):\n guid = models.CharField(max_length=255, blank=True, editable=False, db_index=True)\n title = models.CharField(max_length=255)\n link = models.URLField()\n description = models.TextField()\n pubdate = models.DateTimeField(blank=True, null=True)\n feed = models.ForeignKey(Feed) #, related_name='entries'\n \n class Meta(object):\n ordering = ('-is_published', '-pubdate', 'title')\n \n def __unicode__(self):\n return u'%s' % self.title\n \n def get_absolute_url(self):\n return self.link\n\n\nclass MetaData(models.Model):\n key = models.CharField(max_length=50)\n value = models.TextField()\n\n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n content_object = generic.GenericForeignKey('content_type', 'object_id')\n \n def __unicode__(self):\n return u'key:%s, object_id:%d' % (self.key, self.object_id)" }, { "alpha_fraction": 0.5779448747634888, "alphanum_fraction": 0.5847117900848389, "avg_line_length": 41, "blob_id": "a7ed28a6156c670c9178cdb799190c55cc8f5f79", "content_id": "10d94a5a6d6980e434f21db194fcb77bc4eb74dc", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3990, "license_type": "permissive", "max_line_length": 148, "num_lines": 95, "path": "/niftyurls/management/commands/niftyurls_feeds.py", "repo_name": "strahman/django-niftyurls", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nimport signal, datetime, logging, os, sys, time, json, base64 #zlib, bz2,\nfrom optparse import make_option\nfrom django.core.management.base import BaseCommand\nfrom django.contrib.contenttypes.models import ContentType\nfrom niftyurls.fetch_feed import FetchFeed\nfrom niftyurls.models import Feed, Entry, MetaData\nfrom niftyurls.settings import NIFTYURLS_LIMIT_POSTS\n\ndef alarm_handler(signum, frame):\n print 'Signal handler called with signal', signum\n signal.alarm(0)\n sys.exit(0)\n\nsignal.signal(signal.SIGALRM, alarm_handler)\nsignal.alarm(60*30) # run for maximul 30 minutes\n#connection.connection.text_factory = lambda x: unicode(x, \"utf-8\", \"ignore\")\n\nclass Command(BaseCommand):\n help = \"Can be run as a cronjob or directly to download RSS feeds.\"\n option_list = BaseCommand.option_list + (\n make_option(\n '--verbose', action='store_true', dest='verbose', default=True,\n help='Log output to console.'\n ),\n make_option(\n '--limit', action='store', dest='limit', default=300,\n help='Feed limit'\n ),\n )\n def handle(self, **options):\n \"\"\"\n Update the database with articles\n \"\"\"\n # delete extra posts \n for feed in Feed.objects.values('id'):\n excluded_entries = Entry.objects.filter(feed=feed['id']).order_by('-created', '-id')[:NIFTYURLS_LIMIT_POSTS]\n Entry.objects.filter(feed=feed['id']).exclude(pk__in=excluded_entries).delete()\n \n verbose = options.get('verbose', True)\n logging.basicConfig(\n filename='news_log.log',\n level=logging.INFO,\n format='%(asctime)s %(levelname)-8s %(message)s',\n )\n \n if verbose:\n console = logging.StreamHandler()\n console.setLevel(logging.INFO)\n formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')\n console.setFormatter(formatter)\n logging.getLogger('').addHandler(console)\n\n logging.info('Download starting')\n #total_start = time.time()\n #new_articles = 0\n \n entry_type = ContentType.objects.get(app_label=\"niftyurls\", model=\"entry\")\n dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None\n \n from django.db import connection\n connection.connection.text_factory = str\n \n for feed in Feed.objects.filter(is_published=True).order_by(\"last_downloaded\")[0:options.get('limit')]: #.filter(slug='hackernews')\n logging.info(\"Processing feed: %s\" % (feed.title))\n start = time.time()\n logging.info(\"Downloading: %s\" % feed.link)\n try:\n fetch = FetchFeed(feed.link, feed.page_url)\n fetch.fetch_feed()\n except: #NiftyUrlsException\n logging.error(\"Error occurred processing %s\" % feed.link)\n \n for entry in fetch.data.entries:\n try:\n entry = fetch.sanitize_item(entry)\n except:\n continue\n entry_obj, created = Entry.objects.get_or_create(guid=entry['guid'], feed=feed, defaults=entry)\n try:\n #zlib.compress\n #base64.standard_b64encode\n metadata_value = json.dumps(entry.items(), default=dthandler)\n #MetaData.objects.get_or_create(content_type=entry_type, object_id=entry_obj.pk, key='entry', defaults={'value':metadata_value})\n except Exception as ex:\n #raise ex\n pass\n feed.last_downloaded = datetime.datetime.now()\n feed.save()\n \n end = time.time()\n logging.info(\"This feed processing took %fs\" % (end - start))\n time.sleep(2) # wait a bit, don't lock the database\n \n #total_end = time.time()\n" }, { "alpha_fraction": 0.658556342124939, "alphanum_fraction": 0.6747769713401794, "avg_line_length": 50.375, "blob_id": "7571596c122ca6a1c3b8b7c47e520b89a17acb78", "content_id": "ce45c54016e18bbe1012c01d60c9e1f38364436c", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1233, "license_type": "permissive", "max_line_length": 186, "num_lines": 24, "path": "/niftyurls/settings.py", "repo_name": "strahman/django-niftyurls", "src_encoding": "UTF-8", "text": "import os\nfrom django.conf import settings\n\ntemp_settings = {'example.com': {'rows': '3', 'title': 'Welcome', 'h1': 'Hello'}}\ntemp_settings.update(getattr(settings, 'NIFTYURLS_SETTINGS', {}))\n\nNIFTYURLS_MEDIA = getattr(settings, 'NIFTYURLS_MEDIA', \n os.path.join(settings.MEDIA_URL, 'niftyurls')+\"/\")\nNIFTYURLS_SETTINGS = temp_settings\nNIFTYURLS_LIMIT_POSTS = getattr(settings, 'NIFTYURLS_LIMIT_POSTS', 40) # keep maximum 40 articles in db\n\ndefault_js = ['http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js',\n 'http://cufon.shoqolate.com/js/cufon-yui.js',\n NIFTYURLS_MEDIA+'niftyurls/fonts/Museo.font.js',\n NIFTYURLS_MEDIA+'niftyurls/facebox/facebox.js',\n NIFTYURLS_MEDIA+'niftyurls/js/niftyurls.js',\n]\ndefault_css = ['http://yui.yahooapis.com/combo?3.3.0/build/cssreset/reset-min.css&3.3.0/build/cssfonts/fonts-min.css&3.3.0/build/cssgrids/grids-min.css&3.3.0/build/cssbase/base-min.css',\n NIFTYURLS_MEDIA+'niftyurls/css/style.css',\n NIFTYURLS_MEDIA+'niftyurls/facebox/facebox.css',\n]\n\nNIFTYURLS_JS = getattr(settings, 'NIFTYURLS_JS', default_js)\nNIFTYURLS_CSS = getattr(settings, 'NIFTYURLS_CSS', default_css)\n" } ]
11
vineetred/crc
https://github.com/vineetred/crc
635a9c5dbdf5b13a2506fdf70be2c0260bb351ca
8373651c150ac1b3a6871c4c3205b031d6f26446
5085c0972fd0a8b8f5ac743630b412cf3d4e05b6
refs/heads/master
2020-03-31T02:04:16.430469
2018-10-11T07:06:24
2018-10-11T07:06:24
151,806,891
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5252960324287415, "alphanum_fraction": 0.5748116374015808, "avg_line_length": 27.15151596069336, "blob_id": "5161537f969a4877f0b368aaa843d6594ebea7ca", "content_id": "175df890bd04c560be16dde08aa74e867ddfc7f0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1858, "license_type": "permissive", "max_line_length": 62, "num_lines": 66, "path": "/receiver.py", "repo_name": "vineetred/crc", "src_encoding": "UTF-8", "text": "crc_32 = \"100000100110000010001110110110111\"\n\ntext = open('f_err.txt')\nfile_content= text.read()\n\ncount = 0\ntextOutput = open('f_detect.txt','w')\n\n\ndef checkRemainder(inputString, divisor):\n global flag\n crcAdded = list(inputString)\n # crcAdded = crcAdded + list('0'*(len(crc_32)-1))\n lenInput = len(inputString)\n lenDivisor = len(divisor)\n while '1' in crcAdded[:lenInput]:\n latestOne = findOne(crcAdded)\n for i in range(0, lenDivisor):\n if (divisor[i] == crcAdded[latestOne + i]):\n crcAdded[latestOne + i] = '0'\n else:\n crcAdded[latestOne + i] = '1'\n\n heyhey = ''.join(crcAdded)[lenInput:]\n \n for i in range(0, len(heyhey)):\n if(heyhey[i]=='1'):\n return '1'\n return '0'\n\n\n\ndef findOne(strrr):\n return strrr.index('1')\n\nunstuffedOutput1 = file_content.replace('01111110', '')\nunstuffedOutput2 = unstuffedOutput1.replace('111110','11111')\n\n\nfor i in range(0, len(unstuffedOutput2), (400+len(crc_32)-1)):\n frameString = unstuffedOutput2[i:i+(400+len(crc_32)-1)]\n try:\n flagReturn = checkRemainder(frameString, crc_32,)\n if(flagReturn == '1'):\n print (frameString)\n print (\"Error: \",flagReturn)\n textOutput.write(frameString)\n textOutput.write(\"\\n\")\n textOutput.write(flagReturn)\n textOutput.write(\"\\n\")\n \n\n elif(flagReturn == '0'):\n print (frameString)\n print (flagReturn)\n textOutput.write(frameString)\n textOutput.write(\"\\n\")\n textOutput.write(flagReturn)\n textOutput.write(\"\\n\")\n except:\n print (frameString)\n print ('1')\n textOutput.write(frameString)\n textOutput.write(\"\\n\")\n textOutput.write('1')\n textOutput.write(\"\\n\")\n" }, { "alpha_fraction": 0.5737287998199463, "alphanum_fraction": 0.6093220114707947, "avg_line_length": 30.052631378173828, "blob_id": "144f5d029505c3d4b7b42f2abd1e32473e261fbb", "content_id": "1c033fad6dd5e49aa9a3aa861f48db9ccfc2dc42", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2360, "license_type": "permissive", "max_line_length": 102, "num_lines": 76, "path": "/sender.py", "repo_name": "vineetred/crc", "src_encoding": "UTF-8", "text": "crc_32 = \"100000100110000010001110110110111\"\n#Opening the file\ntext = open('input.txt')\nfile_content= text.read()\n\n#Converting to binary\noutput= ' '.join(format(ord(x), '08b') for x in file_content) #This converts the\nmyfileStringBinary = output.replace(\" \", \"\")\n\n#Polynomial division\ndef remainder(inputString, divisor):\n crcAdded = list(inputString)\n crcAdded = crcAdded + list('0'*(len(crc_32)-1))\n lenInput = len(inputString)\n lenDivisor = len(divisor)\n while '1' in crcAdded[:lenInput]:\n latestOne = findOne(crcAdded)\n for i in range(0, lenDivisor):\n if (divisor[i] == crcAdded[latestOne + i]):\n crcAdded[latestOne + i] = '0'\n else:\n crcAdded[latestOne + i] = '1'\n\n heyhey = ''.join(crcAdded)[lenInput:]\n print(\"Heyhey: \",heyhey)\n return heyhey\n\ndef findOne(strrr):\n return strrr.index('1')\n\ndef assignment1(crcPadded):\n finalString = crcPadded\n\n standardOutput = \"\"\n stuffedOutput = \"\"\n decodedOutput = \"\"\n count = 0 #Counter to check for consecutive 1s\n seperate = '01111110' #Frame separatorprint(finalString + \"\\n\")\n for bit in finalString: \n standardOutput = bit #loading each bit into the the var\n \n if(count == 5):\n if(standardOutput=='1'):\n count = 1\n stuffedOutput = stuffedOutput + '0' + standardOutput #Putting an end to consecutive 1s\n \n elif(standardOutput == '0'):\n count = 0\n stuffedOutput = stuffedOutput + '0' + standardOutput\n\n elif(count<=4):\n if(standardOutput == '1'):\n count = count + 1\n stuffedOutput = stuffedOutput + standardOutput\n\n elif(standardOutput == '0'):\n count = 0\n stuffedOutput = stuffedOutput + standardOutput\n\n if(len(stuffedOutput)%400==0):\n stuffedOutput = stuffedOutput + seperate\n\n stuffedOutput = seperate + stuffedOutput #Adding the flag to the first frame\n return stuffedOutput\n\n\nhello = \"\"\n\nfor i in range(0,len(myfileStringBinary),400):\n frameString = myfileStringBinary[i:i+400]\n finalFrameString = frameString + remainder(frameString, crc_32)\n hello = hello + assignment1(finalFrameString)\nprint (hello)\n\nout = open('f_send.txt', 'w')\nout.write(hello)\n" }, { "alpha_fraction": 0.5481481552124023, "alphanum_fraction": 0.6136752367019653, "avg_line_length": 28.25, "blob_id": "be8d48471561f98b50954caf0c4e8766bb4ef66f", "content_id": "0327988e4e75d691168e94eb33bfb662483c71f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1755, "license_type": "permissive", "max_line_length": 112, "num_lines": 60, "path": "/playground.py", "repo_name": "vineetred/crc", "src_encoding": "UTF-8", "text": "\ndef findOne(strrr):\n return strrr.index('1')\n\n\n\ndef checkRemainder(inputString, divisor):\n global flag\n crcAdded = list(inputString)\n # crcAdded = crcAdded + list('0'*(len(crc_32)-1))\n lenInput = len(inputString)\n lenDivisor = len(divisor)\n while '1' in crcAdded[:lenInput]:\n latestOne = findOne(crcAdded)\n for i in range(0, lenDivisor):\n if (divisor[i] == crcAdded[latestOne + i]):\n crcAdded[latestOne + i] = '0'\n else:\n crcAdded[latestOne + i] = '1'\n\n heyhey = ''.join(crcAdded)[lenInput:]\n print(\"Remainder: \", heyhey)\n \n for i in range(0, len(heyhey)):\n if(heyhey[i]=='1'):\n return '1'\n return '0'\n\n\ndef remainder(inputString, divisor):\n crcAdded = list(inputString)\n crcAdded = crcAdded + list('0'*3)\n lenInput = len(inputString)\n lenDivisor = len(divisor)\n while '1' in crcAdded[:lenInput]:\n latestOne = findOne(crcAdded)\n for i in range(0, lenDivisor):\n if (divisor[i] == crcAdded[latestOne + i]):\n crcAdded[latestOne + i] = '0'\n else:\n crcAdded[latestOne + i] = '1'\n\n heyhey = ''.join(crcAdded)[lenInput:]\n return heyhey\n\n\n\nprint(remainder(\"01101000\",\"1011\"))\nprint(checkRemainder(\"0110100001100101011011000110110001101111011\",\"1011\"))\n\n\n# unstuffedOutput = stuffedOutput.replace('01111110', '')\n# unstuffedOutput = stuffedOutput.replace('111110','11111')\n\n# for i in range(0, len(unstuffedOutput), 400)):\n# truth = checkRemainder(unstuffedOutput[i:i+400],crc_32)\n# print(unstuffedOutput[i:i+400])\n# print(truth)\n\n\n# this is my rough work thing. the crc remainder for this input should have been 100. But i am getting 111. Chec" }, { "alpha_fraction": 0.7566666603088379, "alphanum_fraction": 0.7699999809265137, "avg_line_length": 29, "blob_id": "4ae930a451a8f9a6ac67f444b92896a4b8c99456", "content_id": "88993fd9351461e44d9418e427a1438814f3abed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 300, "license_type": "permissive", "max_line_length": 100, "num_lines": 10, "path": "/README.md", "repo_name": "vineetred/crc", "src_encoding": "UTF-8", "text": "# CRC Checking\n\nAprogram to implement CRC error detection technique. In particular, there are two components to it: \n\n1. CRC Encoding (Sender Side)\n2. CRC Decoding (Receiver Side)\n\nBoth of these are implemented using Python 3.6.\n\nAlso, on top of CRC, the program uses bit stuffing to transmit files.\n" } ]
4
anchalgithub/Project-103-
https://github.com/anchalgithub/Project-103-
2ac633a6bb5abbbce976f0cafb183eaf13cf8298
df99c8361da32876479e7f3c32dea2210dbddaba
bb722c4b5c4dd6ee7d12b6098bc0d95137e20d96
refs/heads/main
2023-03-28T20:06:55.856445
2021-03-31T13:24:08
2021-03-31T13:24:08
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6313645839691162, "alphanum_fraction": 0.6354379057884216, "avg_line_length": 32.64285659790039, "blob_id": "8b70a7ef9c6ff5e2642c4d5b99ae41d860908111", "content_id": "10258a2b5c98f9e99b2231799ddcad8f7f63f3eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 491, "license_type": "no_license", "max_line_length": 81, "num_lines": 14, "path": "/graph.py", "repo_name": "anchalgithub/Project-103-", "src_encoding": "UTF-8", "text": "#importing the visualizing library and creating graphs library.\r\nimport pandas as pd\r\nimport plotly.express as px\r\n\r\ndf=pd.read_csv(\"Covid.csv\")\r\n\r\n#Remember to make the x & y axis labels lowercase\r\n#because otherwise it is going to show an error due it not being in a data frame.\r\nfig=px.scatter(df, x=\"date\", \r\n y=\"cases\", \r\n color=\"country\", \r\n title=\"Covid-19 Cases in Different Countries\")\r\n#calling the function\r\nfig.show()\r\n\r\n\r\n\r\n" } ]
1
3toe/DojosWithTemplates
https://github.com/3toe/DojosWithTemplates
d5428299c3a0861763aa2edee3a5f064309ab7b3
1a78d0c80e8ab7a6be6237b476d20f5faead50f5
bf21b28b193d7f47dff164e5060f85f25d5ac200
refs/heads/main
2023-08-05T18:00:14.036611
2021-10-11T04:05:34
2021-10-11T04:05:34
415,773,946
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6524701714515686, "alphanum_fraction": 0.6797274351119995, "avg_line_length": 31.61111068725586, "blob_id": "ee0618e6d5f35136dd0e7f0128dc1761d2d2c30b", "content_id": "9b55bc41c4c15a40e881a28c1742861a28fcf3fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 587, "license_type": "no_license", "max_line_length": 84, "num_lines": 18, "path": "/dojo_ninjas_app/models.py", "repo_name": "3toe/DojosWithTemplates", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass Dojo(models.Model):\n name = models.CharField(max_length=255)\n city = models.CharField(max_length=255)\n state = models.CharField(max_length=2)\n desc = models.CharField(max_length=255, null=True)\n\n def __repr__(self):\n return f\"<{self.name} ({self.id})>\"\n\nclass Ninja(models.Model):\n dojo = models.ForeignKey(Dojo, related_name=\"ninjas\", on_delete = models.CASCADE)\n first_name = models.CharField(max_length=255)\n last_name = models.CharField(max_length=255)\n\n def __repr__(self):\n return f\"<{self.last_name} ({self.dojo})>\"\n" }, { "alpha_fraction": 0.8522727489471436, "alphanum_fraction": 0.8522727489471436, "avg_line_length": 88, "blob_id": "cca9d5ce7cd60121cf47aa8348ea6aab9551b822", "content_id": "987a97f25ae5451899ac8ac43bf41726a4e83873", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 88, "license_type": "no_license", "max_line_length": 88, "num_lines": 1, "path": "/readme.md", "repo_name": "3toe/DojosWithTemplates", "src_encoding": "UTF-8", "text": "A bootcamp project to tie together one-to-many relationship models with Django templates" }, { "alpha_fraction": 0.6331236958503723, "alphanum_fraction": 0.6331236958503723, "avg_line_length": 42.40909194946289, "blob_id": "563fc12befb98ade7b1028733de4a7fc08156a9e", "content_id": "8ac7d99985beea77e7e48b3eda4def78fc03de46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 954, "license_type": "no_license", "max_line_length": 151, "num_lines": 22, "path": "/dojo_ninjas_app/views.py", "repo_name": "3toe/DojosWithTemplates", "src_encoding": "UTF-8", "text": "from django.db import reset_queries\nfrom django.shortcuts import render, redirect\nfrom .models import Dojo, Ninja\n\ndef index(request):\n context = {\n \"Dojos\" : Dojo.objects.all(),\n \"Ninjas\" : Ninja.objects.all()\n }\n return render(request, \"index.html\", context)\n\ndef process(request):\n if \"DojoButton\" in request.POST:\n if request.POST['name'] == \"\" or request.POST['city'] == \"\" or request.POST['state'] == \"\":\n return redirect('/')\n Dojo.objects.create(name = request.POST['name'], city = request.POST['city'], state = request.POST['state'])\n return redirect('/')\n if \"NinjaButton\" in request.POST:\n if request.POST['sel_dojo'] == \"\" or request.POST['Fname'] == \"\" or request.POST['Lname'] == \"\":\n return redirect('/')\n Ninja.objects.create(dojo = Dojo.objects.get(id=request.POST['sel_dojo']), first_name = request.POST['Fname'], last_name = request.POST['Lname'])\n return redirect('/')" } ]
3
Andreibr1/Python-Calculator
https://github.com/Andreibr1/Python-Calculator
ca19eae20d92d71154975dc276bed2c7d78b9633
cb633eb70d3d788063594b757d99967531d15511
614b1746f5354a3808f2adcceb13bd0b71c16512
refs/heads/master
2022-11-10T17:53:10.167805
2020-07-01T18:30:41
2020-07-01T18:30:41
276,420,520
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6058981418609619, "alphanum_fraction": 0.627345860004425, "avg_line_length": 16, "blob_id": "f0c9001e9571e20bdef3d93bfdbb32b918dcdb0e", "content_id": "05a4ea28367d4bec0414f5bdcf98e41e2e396c2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 373, "license_type": "no_license", "max_line_length": 100, "num_lines": 22, "path": "/UI.py", "repo_name": "Andreibr1/Python-Calculator", "src_encoding": "UTF-8", "text": "from tkinter import *\n\n\nroot = Tk()\n\n\nnumbers = []\n\nstatement = \"\"\n\ndef AddDigit(num):\n global statement\n statement += str(num)\n\nScreenStatement = Label(root, text=statement).grid(row=0, columnspan=3)\n\nfor x in range(9):\n i = x % 3\n j = x // 3\n numbers.append(Button(root, text=str(x + 1)).grid(row=j + 1, column=i, command=AddDigit(x + 1)))\n\nroot.mainloop()" }, { "alpha_fraction": 0.4650748372077942, "alphanum_fraction": 0.47754812240600586, "avg_line_length": 21.27777862548828, "blob_id": "116363d7aea2772e48ea05ccb57bc4634787b46d", "content_id": "85048e845f82351b02354a605af8d67be1c70c88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2806, "license_type": "no_license", "max_line_length": 91, "num_lines": 126, "path": "/Calculator.py", "repo_name": "Andreibr1/Python-Calculator", "src_encoding": "UTF-8", "text": "def isFactorial(String):\n if(len(String) > 1 and String[len(String) - 1] == \"!\"):\n return True\n return False\n\ndef factorial(x):\n if x == 0:\n return 1\n else:\n return x * factorial(x - 1)\n\n\n\ndef evali(x, y, op):\n if op == \"+\":\n return x + y\n if op == \"-\":\n return y - x\n if op == \"*\":\n return y * x\n if op == \"^\":\n return y ** x\n if op == \"/\":\n return y / x\n return 0\n\ndef evalb(y, x, op):\n\tif(op == \">\"):\n\t\treturn x > y\n\tif(op == \"<\"):\n\t\t\treturn x < y\n\tif(op == \"<=\"):\n\t\treturn x <= y\n\tif(op == \">=\"):\n\t\treturn x >= y\n\tif(op == \"==\"):\n\t\treturn x == y\n\tif(op == \"!=\"):\n\t\treturn x != y\n\treturn False\n\t\t\ndef isBoolean(x):\n\tif x == (\">\") or x == (\"<\") or \\\n x == (\">=\") or x == (\"<=\") or x == (\"==\") or \\\n x == (\"!=\"):\n\t\treturn True\n\telse:\n\t\treturn False\n\n\ndef isDigit(x):\n try:\n int(x)\n return True\n except ValueError:\n return False\n\ndef priorityOP(x):\n \n if x == \"!\":\n return 2\n if x == \"^\":\n return 3\n if x == \"*\":\n return 4\n if x == \"/\":\n return 5\n if x == \"+\" or x == \"-\":\n return 6\n if x == \"==\" or x == \"!=\":\n return 7;\n return 8;\n\ndef claculate(statement):\n sarray = statement.split()\n if len(sarray) == 1:\n return sarray[0]\n \n for i, e in enumerate(sarray):\n if(isFactorial(e)):\n num = int(e[0, -1])\n num = str(factorial(num))\n sarray[i] = num\n \n maxIndex = 0\n priorityAtindex = 10\n operator = \"\"\n\n for i, e in enumerate(sarray):\n if i % 2 == 1 and priorityOP(sarray[i]) < priorityAtindex:\n maxIndex = i\n priorityAtindex = priorityOP(sarray[i])\n operator = sarray[i]\n if isBoolean(operator):\n temp = evalb(int(sarray[maxIndex + 1]), int(sarray[maxIndex - 1]), operator)\n return str(temp)\n else:\n x = evali(int(sarray[maxIndex + 1]), int(sarray[maxIndex - 1]), operator)\n sarray[maxIndex + 1] = None\n sarray[maxIndex - 1] = None\n sarray[maxIndex] = str(x)\n ret = \"\"\n\n for i, e in enumerate(sarray):\n if sarray[i] != None:\n ret += sarray[i] + \" \"\n return claculate(ret)\n \ndef compute(statement):\n if \"(\" not in statement:\n return claculate(statement)\n subCalculation = \"\"\n parenIndex = []\n\n for i, e in enumerate(statement):\n if statement[i] == \"(\":\n parenIndex.append(i)\n if statement[i] == \")\":\n z = parenIndex.pop()\n subCalculation = claculate(statement[z + 1 : i])\n statement = statement[0:z] + subCalculation + statement[i + 1 : len(statement)]\n break\n return compute(statement) \n\n\nprint(compute(\"2 + 4 * (2 - 1)\"))" } ]
2
SubNader/AWS2Hive
https://github.com/SubNader/AWS2Hive
bf06b7c37a7890c2de825de29806bbdf86385e92
20fc30af37ccb4aa6f68d1c95eede70a955b1362
fa46f3d053a4033555e01c73b82e79f26faf904b
refs/heads/master
2020-03-18T17:31:00.011367
2018-07-02T21:57:21
2018-07-02T21:57:21
135,033,100
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6269972324371338, "alphanum_fraction": 0.6358126997947693, "avg_line_length": 37.38298034667969, "blob_id": "768f5a692cc232de21729fd7485f1383988c8247", "content_id": "9c623ab350a63ca97c11d1c07948413828a9d5db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1815, "license_type": "no_license", "max_line_length": 131, "num_lines": 47, "path": "/aws2hive/etl.py", "repo_name": "SubNader/AWS2Hive", "src_encoding": "UTF-8", "text": "############################################################################################\n## Extract, transform and load script | Fetches data from Amazon S3 and loads it to Hive. ##\n############################################################################################\n\nimport boto3\nimport pathlib\n\ndef run_etl(hiveContext, bucket_name, path_prefix, dataset_dir, hive_table_name):\n\t\n\t# Get all target directory keys\n\ts3_client = boto3.resource('s3')\n\ts3_bucket = s3_client.Bucket(bucket_name)\n\ts3_objects = s3_bucket.objects.filter(Prefix=path_prefix+'/', Delimiter='/')\n\n\t# Select data files keys only\n\tdata_keys = []\n\tfor s3_object in s3_objects:\n\n\t\tif s3_object.key.endswith('.json'):\n\t\t\tdata_keys.append(s3_object.key)\n\t\n\t# Report the number of data files\n\tprint('Fetched the keys of %s data file(s).\\n' % len(data_keys))\n\n\t# Prepare output directory\n\tpathlib.Path(dataset_dir).mkdir(exist_ok=True) \n\n\t# Fetch data\n\tfor index, data_key in enumerate(data_keys):\n\n\t\t# Notify\n\t\toutput_file_name = '{}/part_{}.json'.format(dataset_dir,index+1)\n\t\tprint('Downloading part ({}/{})\\nKey: {}\\nSaving to: {}\\n'.format(index+1, len(data_keys), data_key, output_file_name))\n\t\t\n\t\t# Check if data file already exists\n\t\toutput_file_path = pathlib.Path(output_file_name)\n\t\t\n\t\t# Download data file if missing\n\t\tif not(output_file_path.is_file()):\n\t\t\ts3_bucket.download_file(data_key, output_file_name)\n\t\n\t# Save fetched data to Hive\n\tfetched_data = hiveContext.read.json(dataset_dir)\n\tfetched_data.createOrReplaceTempView('dataset_temp') \n\thql_statement = 'CREATE TABLE IF NOT EXISTS {} AS SELECT * FROM dataset_temp'.format(hive_table_name)\n\thiveContext.sql(hql_statement);\n\tprint('Fetched and loaded dataset to Hive.\\nTable name: {}\\nNumber of records: {}\\n'.format(hive_table_name,fetched_data.count()))\n\n\n\t\n\n\t\n\n\n\n\n" }, { "alpha_fraction": 0.5802469253540039, "alphanum_fraction": 0.586980938911438, "avg_line_length": 33.30769348144531, "blob_id": "a9054b3790b282fcbbcb48df8ab62a1ab3d5b54d", "content_id": "19869d09506ee4a37f21b21c9647d2b9c558fcd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 891, "license_type": "no_license", "max_line_length": 84, "num_lines": 26, "path": "/run.py", "repo_name": "SubNader/AWS2Hive", "src_encoding": "UTF-8", "text": "####################################################################################\n## Runner script | Handles arguments, creates contexts and runs the ETL process. ##\n####################################################################################\n\nimport sys\nfrom aws2hive import etl\nfrom pyspark import SparkContext, SparkConf\nfrom pyspark.sql import HiveContext\n\nif __name__ == '__main__':\n\n\t# Handle arguments\n\tbucket_name = sys.argv[1] \n\tpath_prefix = sys.argv[2]\n\tdataset_dir = sys.argv[3]\n\thive_table_name = sys.argv[4]\n\n\t# Create Spark and Hive contexts\n\tconf = SparkConf().setAppName('AWS2Hive ETL').setMaster('local[*]')\n\tsc = SparkContext(conf=conf)\n\thiveContext = HiveContext(sc)\n\n\t# Run the ETL process\n\tprint('Starting the ETL process..\\n')\n\tetl.run_etl(hiveContext, bucket_name, path_prefix, dataset_dir, hive_table_name)\n\tprint('The ETL process has been completed.\\n')" }, { "alpha_fraction": 0.6904347538948059, "alphanum_fraction": 0.695652186870575, "avg_line_length": 20.296297073364258, "blob_id": "a518c7985531f821f10302b3f37f063123a82582", "content_id": "bc88419f1c4cd062a5f60f38219c8e19464093f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 575, "license_type": "no_license", "max_line_length": 106, "num_lines": 27, "path": "/README.md", "repo_name": "SubNader/AWS2Hive", "src_encoding": "UTF-8", "text": "# AWS2Hive\nAWS to Hive data pipeline tools leveraging Apache Spark in Python\n\n---\n\n# Files included\n\n- ### Runner script\n\n **Script file:** run.py\n\n **Description:** Handles arguments, creates contexts and runs the ETL process.\n\n **Parameters list:**\n - Bucket name\n - Bucket prefix\n - Dataset save directory\n - Output Hive table name\n\n **Sample run command:** *python run.py some_bucket some_prefix data_dir aws_data_table > run_result.txt*\n\n\n- ### ETL script\n\n **Script file:** aws2hive/etl.py\n\n **Description:** Fetches data from Amazon S3 and loads it to Hive.\n" } ]
3
PI2-Estufa/iluminationServer
https://github.com/PI2-Estufa/iluminationServer
f6a3d7b13552b61947871ee36cd3838f85eb8b0b
1380c7652e62a51834781d1753e0988926587ed3
b63e66c436cb0b96c5fc1554922d99af6056f9dd
refs/heads/master
2022-12-11T08:35:10.606517
2018-06-29T16:07:48
2018-06-29T16:07:48
136,656,600
0
0
null
2018-06-08T19:06:57
2018-06-29T16:07:56
2022-12-08T02:12:28
Python
[ { "alpha_fraction": 0.7457627058029175, "alphanum_fraction": 0.7457627058029175, "avg_line_length": 27.2608699798584, "blob_id": "a8413dec38c63714873b5bc2013e8aa4e8cb074c", "content_id": "dffa48dc660885b55af91d6ed077f610e981f3fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 649, "license_type": "no_license", "max_line_length": 91, "num_lines": 23, "path": "/db.py", "repo_name": "PI2-Estufa/iluminationServer", "src_encoding": "UTF-8", "text": "import datetime\nimport os\nfrom sqlalchemy import create_engine, Column, Integer, Boolean, Unicode, Sequence, DateTime\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\n\nengine = create_engine(os.environ.get(\"POSTGRES_URL\"), echo=True)\nSession = sessionmaker(bind=engine)\nsession = Session()\n\nBase = declarative_base()\n\nclass Ilumination(Base):\n \n __tablename__ = 'ilumination'\n\n id = Column(Integer,\n Sequence('ilumination_id_seq'), primary_key=True)\n value = Column(Boolean)\n created_date = Column(DateTime, default=datetime.datetime.utcnow)\n\nBase.metadata.create_all(engine)" }, { "alpha_fraction": 0.6058700084686279, "alphanum_fraction": 0.6079664826393127, "avg_line_length": 21.714284896850586, "blob_id": "5da2a5fcecd942355569d9fb95eab553d8cce8fd", "content_id": "719b016121b5be8bb482853fb575d604d2ba09ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 477, "license_type": "no_license", "max_line_length": 47, "num_lines": 21, "path": "/ilumination_server.py", "repo_name": "PI2-Estufa/iluminationServer", "src_encoding": "UTF-8", "text": "from nameko.rpc import rpc\nimport db\nfrom db import Ilumination\nfrom psycopg2 import OperationalError\n\n\nclass IluminationServer():\n name = \"ilumination_server\"\n\n @rpc\n def receive_ilumination(self, ilumination):\n i = Ilumination()\n i.value = ilumination\n try:\n db.session.add(i)\n db.session.commit()\n except:\n db.session.rollback()\n finally:\n db.session.close()\n return ilumination\n" } ]
2
AklerQ/python_training
https://github.com/AklerQ/python_training
d75b31b86ca4a658b0dbc0d430ce7217ac37ee0f
38a3ac51cae12820a54cf10af26967cc045ed734
1cf1df217b510ea8295f533ddacabd11aa94d0c1
refs/heads/master
2021-01-17T07:53:40.577636
2017-05-01T23:15:54
2017-05-01T23:15:54
83,811,993
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5926715135574341, "alphanum_fraction": 0.6144013404846191, "avg_line_length": 56.26829147338867, "blob_id": "bb929effe16e20df76685091ea15d19f25819f78", "content_id": "b57a38408bb658b769a0e916303333a3ccdd981b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2347, "license_type": "permissive", "max_line_length": 120, "num_lines": 41, "path": "/data/contact_data.py", "repo_name": "AklerQ/python_training", "src_encoding": "UTF-8", "text": "from model.contact import Contact\nimport random\nimport string\n\n\ndef random_string(prefix, maxlen):\n symbols = string.ascii_letters + string.digits + \" \"*10\n return prefix + \"\".join([random.choice(symbols) for i in range(random.randrange(maxlen))])\n\n\ndef random_number(maxlen):\n symbols = string.digits + \")\" + \"(\" + \"-\" + \" \"\n return \"\".join([random.choice(symbols) for i in range(random.randrange(maxlen))])\n\n\ndef random_email(maxlen):\n symbols = string.ascii_lowercase + string.digits + \"_\" + \"-\"\n return \"\".join([random.choice(symbols) for i in range(random.randrange(maxlen))] + ['@'] + [random.choice(symbols)\n for i in range(random.randrange(maxlen))] + ['.', 'ru'])\n\n\ndef random_date(maxlen):\n return str(random.randrange(maxlen))\n\n\ntestdata = [Contact(firstname=\"\", middlename=\"\", lastname=\"\", nickname=\"\", companyname=\"\", address=\"\",\n homenumber=\"\", worknumber=\"\", email=\"\", email2=\"\",\n birth_date=\"//div[@id='content']/form/select[1]//option[1]\",\n birth_month=\"//div[@id='content']/form/select[2]//option[1]\", birth_year=\"\",\n anniversary_date=\"//div[@id='content']/form/select[3]//option[1]\",\n anniversary_month=\"//div[@id='content']/form/select[4]//option[1]\", notes=\"\",\n mobilenumber=\"\", secondarynumber=\"\")] + [\nContact(firstname=random_string(\"firstname\", 10), middlename=random_string(\"middlename\", 10), lastname=random_string\n(\"lastname\", 10), nickname=random_string(\"nickname\", 10), companyname=random_string(\"companyname\", 10), address=\nrandom_string(\"address\", 25), homenumber=random_number(9), mobilenumber=random_number(12), worknumber=random_number(12),\nemail=random_email(6), email2=random_email(7), email3=random_email(8),\nbirth_date=\"//div[@id='content']/form/select[1]//option[\"+random_date(32)+\"]\",\nbirth_month=\"//div[@id='content']/form/select[2]//option[\"+random_date(13)+\"]\", birth_year=random_number(4),\nanniversary_date=\"//div[@id='content']/form/select[3]//option[\"+random_date(32)+\"]\", notes=random_string(\"name\", 30),\nanniversary_month=\"//div[@id='content']/form/select[4]//option[\"+random_date(13)+\"]\", secondarynumber=random_number(12))\n for i in range(5)]" }, { "alpha_fraction": 0.6250776052474976, "alphanum_fraction": 0.6356300711631775, "avg_line_length": 49.34375, "blob_id": "e8e0146a3c61d6fc2b7c52954f202a410806fe10", "content_id": "c1ff9d298b9e1741c541d33cb94fba733a2e6e3f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1697, "license_type": "permissive", "max_line_length": 110, "num_lines": 32, "path": "/test/test_del_contact_from_group.py", "repo_name": "AklerQ/python_training", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom model.group import Group\nfrom model.contact import Contact\nfrom fixture.orm import ORMfixture\nimport random\n\ndb = ORMfixture(host=\"127.0.0.1\", name=\"addressbook\", user=\"root\", password=\"\")\n\n\ndef test_del_contact_from_group(app):\n # Проверка на наличие групп\n if len(db.get_group_list()) == 0:\n app.group.create(Group(name=\"For adds contact\", header=\"For adds contact\", footer=\"For adds contact\"))\n group_list = db.get_group_list()\n group = random.choice(group_list)\n # Проверка на наличие контактов в группе\n if len(db.get_contacts_in_group(group)) == 0:\n app.contact.create(Contact(firstname=\"Тест_добавления\", lastname=\"Тест_для_добавления\",\n birth_date=\"//div[@id='content']/form/select[1]//option[1]\",\n birth_month=\"//div[@id='content']/form/select[2]//option[1]\",\n anniversary_date=\"//div[@id='content']/form/select[3]//option[1]\",\n anniversary_month=\"//div[@id='content']/form/select[4]//option[1]\",\n new_group=\"//select[@name='new_group']/option[@value='%s']\" % group.id))\n app.navigation.open_group_page_by_id(group.id)\n contacts_list = db.get_contacts_in_group(group)\n contact = random.choice(contacts_list)\n app.contact.select_contact_by_id(contact.id)\n app.contact.delete_contact_from_group()\n app.navigation.open_group_page_by_id(group.id)\n # test validation\n assert contact in list(db.get_contacts_not_in_group(group))\n assert contact not in list(db.get_contacts_in_group(group))\n" }, { "alpha_fraction": 0.5272727012634277, "alphanum_fraction": 0.5477272868156433, "avg_line_length": 63.70588302612305, "blob_id": "aaf51b301bbb42eed1d2e6c5e99d59e0e7686367", "content_id": "f15645e2718a43f06b2355f1fd95c770c6af6473", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2315, "license_type": "permissive", "max_line_length": 123, "num_lines": 34, "path": "/test/test_edit_contact.py", "repo_name": "AklerQ/python_training", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom model.contact import Contact\nimport random\n\n\ndef test_edit_contact_by_index(app, db, check_ui):\n if app.contact.count_contacts() == 0:\n app.contact.create(Contact(firstname=\"For modify\", birth_date=\"//div[@id='content']/form/select[1]//option[1]\",\n birth_month=\"//div[@id='content']/form/select[2]//option[1]\",\n anniversary_date=\"//div[@id='content']/form/select[3]//option[1]\",\n anniversary_month=\"//div[@id='content']/form/select[4]//option[1]\"))\n old_contacts = db.get_contact_list()\n contact = random.choice(old_contacts)\n input_contact = Contact(firstname=\"Отредактирован\", middlename=\"Отредактирович\",\n lastname=\"Отредактированский\", nickname=\"Редактор\",\n companyname='ОАО \"Редакция и Мир\"', address=\"редакторский городок\",\n homenumber=\"567-22-04\", worknumber=\"45+6\", email=\"[email protected]\",\n notes=\"Здесь могла бы быть ваша реклама\", email2=\"\",\n birth_date=\"//div[@id='content']/form/select[1]//option[4]\",\n birth_month=\"//div[@id='content']/form/select[2]//option[5]\", birth_year=\"\",\n anniversary_date=\"//div[@id='content']/form/select[3]//option[6]\",\n anniversary_month=\"//div[@id='content']/form/select[4]//option[7]\",\n mobilenumber=\"12345678\", secondarynumber=\"(098)76543\")\n input_contact.id = contact.id\n app.contact.edit_contact_by_id(contact.id, input_contact)\n # Test validation\n new_contacts = db.get_contact_list()\n assert len(old_contacts) == len(new_contacts)\n idx = int(old_contacts.index(contact))\n old_contacts[idx] = input_contact\n assert old_contacts == new_contacts\n if check_ui:\n new_contacts = map(app.contact.clean, db.get_contact_list())\n assert sorted(new_contacts, key=Contact.id_or_max) == sorted(app.contact.get_contact_list(), key=Contact.id_or_max)\n" }, { "alpha_fraction": 0.6007761359214783, "alphanum_fraction": 0.6015037298202515, "avg_line_length": 33.64706039428711, "blob_id": "198afcaa089cd2adfdd5fbfd9866448ffeddeb41", "content_id": "a3e8db8e95047f442ca3a5b68577994f30a757e7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4123, "license_type": "permissive", "max_line_length": 95, "num_lines": 119, "path": "/fixture/group.py", "repo_name": "AklerQ/python_training", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom model.group import Group\n\n\nclass GroupHelper:\n\n def __init__(self, app):\n self.app = app\n\n def create(self, group):\n wd = self.app.wd\n self.app.navigation.open_groups_page()\n # init group creation\n wd.find_element_by_name(\"new\").click()\n # fill group form\n self.fill_group_fields(group)\n # submit group creation\n wd.find_element_by_name(\"submit\").click()\n self.app.navigation.return_to_groups_page()\n self.group_cache = None\n\n def delete_group_by_index(self, index):\n wd = self.app.wd\n self.app.navigation.open_groups_page()\n self.select_group_by_index(index)\n # submit deletion\n wd.find_element_by_name(\"delete\").click()\n self.app.navigation.return_to_groups_page()\n self.group_cache = None\n\n def delete_first_group(self):\n self.delete_group_by_index(0)\n\n def edit_group_by_index(self, index, input_group):\n wd = self.app.wd\n self.app.navigation.open_groups_page()\n self.select_group_by_index(index)\n # init group edition\n wd.find_element_by_name(\"edit\").click()\n # fill group form\n self.fill_group_fields(input_group)\n # submit group edition\n wd.find_element_by_name(\"update\").click()\n self.app.navigation.return_to_groups_page()\n self.group_cache = None\n\n def edit_first_group(self, input_group):\n self.edit_group_by_index(0, input_group)\n\n def select_first_group(self):\n wd = self.app.wd\n wd.find_element_by_name(\"selected[]\").click()\n\n def select_group_by_index(self, index):\n wd = self.app.wd\n wd.find_elements_by_name(\"selected[]\")[index].click()\n\n def fill_group_fields(self, input_group):\n self.change_field_value(\"group_name\", input_group.name)\n self.change_field_value(\"group_header\", input_group.header)\n self.change_field_value(\"group_footer\", input_group.footer)\n\n def change_field_value(self, field_name, text):\n wd = self.app.wd\n if text is not None:\n wd.find_element_by_name(field_name).click()\n wd.find_element_by_name(field_name).clear()\n wd.find_element_by_name(field_name).send_keys(text)\n\n def count_groups(self):\n wd = self.app.wd\n self.app.navigation.open_groups_page()\n return len(wd.find_elements_by_name(\"selected[]\"))\n\n group_cache = None\n\n def get_group_list(self):\n if self.group_cache is None:\n wd = self.app.wd\n self.app.navigation.open_groups_page()\n self.group_cache = []\n for element in wd.find_elements_by_css_selector(\"span.group\"):\n text = element.text\n id = element.find_element_by_name(\"selected[]\").get_attribute(\"value\")\n self.group_cache.append(Group(name=text, id=id))\n return list(self.group_cache)\n\n def delete_group_by_id(self, id):\n wd = self.app.wd\n self.app.navigation.open_groups_page()\n self.select_group_by_id(id)\n # submit deletion\n wd.find_element_by_name(\"delete\").click()\n self.app.navigation.return_to_groups_page()\n self.group_cache = None\n\n def select_group_by_id(self, id):\n wd = self.app.wd\n wd.find_element_by_css_selector(\"input[value='%s']\" % id).click()\n\n def select_group_by_id_for_add_to(self, id):\n wd = self.app.wd\n wd.find_element_by_xpath('//select[@name=\"to_group\"]/option[@value=\"%s\"]' % id).click()\n\n def clean(self, group):\n return Group(id=group.id, name=group.name.strip())\n\n def edit_group_by_id(self, id, input_group):\n wd = self.app.wd\n self.app.navigation.open_groups_page()\n self.select_group_by_id(id)\n # init group edition\n wd.find_element_by_name(\"edit\").click()\n # fill group form\n self.fill_group_fields(input_group)\n # submit group edition\n wd.find_element_by_name(\"update\").click()\n self.app.navigation.return_to_groups_page()\n self.group_cache = None\n" }, { "alpha_fraction": 0.6648168563842773, "alphanum_fraction": 0.6670366525650024, "avg_line_length": 41.904762268066406, "blob_id": "7a6b364c99400856935832d3f9823a641f7c20e2", "content_id": "9af1b283452242c14f5a53122e1bf5e5829b2cc9", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 901, "license_type": "permissive", "max_line_length": 113, "num_lines": 21, "path": "/test/test_edit_group.py", "repo_name": "AklerQ/python_training", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom model.group import Group\nimport random\n\n\ndef test_edit_first_group_footer(app, db, check_ui):\n if len(db.get_group_list()) == 0:\n app.group.create(Group(name=\"For modification\", header=\"For modification\", footer=\"For modification\"))\n old_groups = db.get_group_list()\n group = random.choice(old_groups)\n input_group = Group(name=\"Modify name\", header=\"Modify header\", footer=\"Modify footer\")\n app.group.edit_group_by_id(group.id, input_group)\n # Test validation\n new_groups = db.get_group_list()\n assert len(old_groups) == len(new_groups)\n idx = int(old_groups.index(group))\n old_groups[idx] = input_group\n assert old_groups == new_groups\n if check_ui:\n new_groups = map(app.group.clean, db.get_group_list())\n assert sorted(new_groups, key=Group.id_or_max) == sorted(app.group.get_group_list(), key=Group.id_or_max)\n" }, { "alpha_fraction": 0.6229090690612793, "alphanum_fraction": 0.626675546169281, "avg_line_length": 44.1349983215332, "blob_id": "97ffc932efbe0870dff54127734e5520f4ab17c5", "content_id": "f2a48b4c07cac62bd6f8faac40523c1d5eb9d29f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9187, "license_type": "permissive", "max_line_length": 128, "num_lines": 200, "path": "/fixture/contact.py", "repo_name": "AklerQ/python_training", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom model.contact import Contact\nimport re\n\nclass ContactHelper:\n\n def __init__(self, app):\n self.app = app\n\n def create(self, contact):\n wd = self.app.wd\n self.app.navigation.turn_to_home_page()\n # create new contact\n wd.find_element_by_link_text(\"add new\").click()\n # fill contact form\n self.fill_contact_fields(contact)\n # submit created contact\n wd.find_element_by_xpath(\"//div[@id='content']/form/input[21]\").click()\n self.app.navigation.return_to_home_page()\n self.contact_cache = None\n\n def fill_contact_fields(self, contact):\n wd = self.app.wd\n # fill personal data\n self.change_field_value(\"firstname\", contact.firstname)\n self.change_field_value(\"middlename\", contact.middlename)\n self.change_field_value(\"lastname\", contact.lastname)\n self.change_field_value(\"nickname\", contact.nickname)\n self.change_field_value(\"company\", contact.companyname)\n self.change_field_value(\"address\", contact.address)\n # fill communication data\n self.change_field_value(\"home\", contact.homenumber)\n self.change_field_value(\"mobile\", contact.mobilenumber)\n self.change_field_value(\"work\", contact.worknumber)\n self.change_field_value(\"email\", contact.email)\n self.change_field_value(\"email2\", contact.email2)\n self.change_field_value(\"phone2\", contact.secondarynumber)\n # fill dates\n if not wd.find_element_by_xpath(contact.birth_date).is_selected():\n wd.find_element_by_xpath(contact.birth_date).click()\n if not wd.find_element_by_xpath(contact.birth_month).is_selected():\n wd.find_element_by_xpath(contact.birth_month).click()\n self.change_field_value(\"byear\", contact.birth_year)\n if not wd.find_element_by_xpath(contact.anniversary_date).is_selected():\n wd.find_element_by_xpath(contact.anniversary_date).click()\n if not wd.find_element_by_xpath(contact.anniversary_month).is_selected():\n wd.find_element_by_xpath(contact.anniversary_month).click()\n # fill contact commentary\n self.change_field_value(\"notes\", contact.notes)\n if not wd.find_element_by_xpath(contact.new_group).is_selected():\n wd.find_element_by_xpath(contact.new_group).click()\n\n\n def change_field_value(self, field_name, text):\n wd = self.app.wd\n if text is not None:\n wd.find_element_by_name(field_name).click()\n wd.find_element_by_name(field_name).clear()\n wd.find_element_by_name(field_name).send_keys(text)\n\n def select_contact_by_index(self, index):\n wd = self.app.wd\n wd.find_elements_by_name(\"selected[]\")[index].click()\n\n def select_first_contact(self):\n wd = self.app.wd\n wd.find_element_by_name(\"selected[]\").click()\n\n def delete_contact_by_index(self, index):\n wd = self.app.wd\n self.app.navigation.turn_to_home_page()\n self.select_contact_by_index(index)\n wd.find_element_by_xpath(\"//div[@id='content']/form[2]/div[2]/input\").click()\n wd.switch_to_alert().accept()\n # Здесь повторно используется метод TURN вместо RETURN, так как после удаления\n # не доступен переход по ссылке home_page\n self.app.navigation.turn_to_home_page()\n self.contact_cache = None\n\n def delete_first_contact(self):\n self.delete_contact_by_index(0)\n\n def edit_contact_by_index(self, index, contact):\n wd = self.app.wd\n self.open_contact_to_edit_by_index(index)\n self.fill_contact_fields(contact)\n wd.find_element_by_xpath(\"//input[@name='update'][@value='Update']\").click()\n self.app.navigation.return_to_home_page()\n self.contact_cache = None\n\n def edit_contact_by_id(self, id, contact):\n wd = self.app.wd\n self.app.navigation.open_contact_edit_page_by_id(id)\n self.fill_contact_fields(contact)\n wd.find_element_by_xpath(\"//input[@name='update'][@value='Update']\").click()\n self.app.navigation.return_to_home_page()\n self.contact_cache = None\n\n def edit_first_contact(self, contact):\n self.edit_contact_by_index(0, contact)\n\n def count_contacts(self):\n wd = self.app.wd\n self.app.navigation.turn_to_home_page()\n return len(wd.find_elements_by_name(\"selected[]\"))\n\n contact_cache = None\n\n def get_contact_list(self):\n if self.contact_cache is None:\n wd = self.app.wd\n self.app.navigation.turn_to_home_page()\n self.contact_cache = []\n for row in wd.find_elements_by_css_selector('tr[name=entry]'):\n cells = row.find_elements_by_css_selector('td')\n id = cells[0].find_element_by_css_selector('input').get_attribute('value')\n lastname = cells[1].text\n firstname = cells[2].text\n address = cells[3].text\n all_email = cells[4].text\n all_phones = cells[5].text\n self.contact_cache.append(Contact(firstname=firstname, lastname=lastname, id=id, address=address,\n all_phones_from_home_page=all_phones, all_email_from_home_page=all_email))\n return list(self.contact_cache)\n\n def open_contact_view_by_index(self, index):\n wd = self.app.wd\n self.app.navigation.turn_to_home_page()\n row = wd.find_elements_by_name(\"entry\")[index]\n cell = row.find_elements_by_tag_name(\"td\")[6]\n cell.find_element_by_tag_name(\"a\").click()\n\n def open_contact_to_edit_by_index(self, index):\n wd = self.app.wd\n self.app.navigation.turn_to_home_page()\n wd.find_element_by_xpath(\"//table[@id='maintable']/tbody/tr[\"+str(index+2)+\"]/td[8]/a/img\").click()\n\n def get_contact_info_from_edit_page(self, index):\n wd = self.app.wd\n self.open_contact_to_edit_by_index(index)\n firstname = wd.find_element_by_name('firstname').get_attribute('value')\n lastname = wd.find_element_by_name('lastname').get_attribute('value')\n id = wd.find_element_by_name('id').get_attribute('value')\n homenumber = wd.find_element_by_name('home').get_attribute('value')\n mobilenumber = wd.find_element_by_name('mobile').get_attribute('value')\n worknumber = wd.find_element_by_name('work').get_attribute('value')\n secondarynumber = wd.find_element_by_name('phone2').get_attribute('value')\n address = wd.find_element_by_name('address').get_attribute('value')\n email = wd.find_element_by_name('email').get_attribute('value')\n email2 = wd.find_element_by_name('email2').get_attribute('value')\n email3 = wd.find_element_by_name('email3').get_attribute('value')\n return Contact(id=id, firstname=firstname, lastname=lastname, homenumber=homenumber, mobilenumber=mobilenumber,\n worknumber=worknumber, secondarynumber=secondarynumber, address=address, email=email,\n email2=email2, email3=email3)\n\n def get_contact_from_view_page(self, index):\n wd = self.app.wd\n self.open_contact_view_by_index(index)\n text = wd.find_element_by_id(\"content\").text\n homenumber = re.search(\"H: (.*)\", text)\n if homenumber is not None:\n homenumber = homenumber.group(1)\n worknumber = re.search(\"W: (.*)\", text)\n if worknumber is not None:\n worknumber = worknumber.group(1)\n mobilenumber = re.search(\"M: (.*)\", text)\n if mobilenumber is not None:\n mobilenumber = mobilenumber.group(1)\n secondarynumber = re.search(\"P: (.*)\", text)\n if secondarynumber is not None:\n secondarynumber = secondarynumber.group(1)\n return Contact(homenumber=homenumber, worknumber=worknumber, mobilenumber=mobilenumber, secondarynumber=secondarynumber)\n\n def delete_contact_by_id(self, id):\n wd = self.app.wd\n self.app.navigation.turn_to_home_page()\n self.select_contact_by_id(id)\n wd.find_element_by_xpath(\"//div[@id='content']/form[2]/div[2]/input\").click()\n wd.switch_to_alert().accept()\n # Здесь повторно используется метод TURN вместо RETURN, так как после удаления\n # не доступен переход по ссылке home_page\n self.app.navigation.turn_to_home_page()\n self.contact_cache = None\n\n def select_contact_by_id(self, id):\n wd = self.app.wd\n wd.find_element_by_id(id).click()\n\n def clean(self, contact):\n return Contact(id=contact.id, firstname=contact.firstname.strip(), lastname=contact.lastname.strip())\n\n def add_contact_to_group(self):\n wd = self.app.wd\n wd.find_element_by_name(\"add\").click()\n self.contact_cache = None\n\n def delete_contact_from_group(self):\n wd = self.app.wd\n wd.find_element_by_xpath('//input[@name=\"remove\"]').click()\n self.contact_cache = None\n" }, { "alpha_fraction": 0.674876868724823, "alphanum_fraction": 0.675772488117218, "avg_line_length": 49.75, "blob_id": "4ca314367dd986ea5d2fff41ce8022cd01735c51", "content_id": "1e0312caffae37b3e462578e630c277a2eecb300", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2233, "license_type": "permissive", "max_line_length": 119, "num_lines": 44, "path": "/test/test_contact_data_validation.py", "repo_name": "AklerQ/python_training", "src_encoding": "UTF-8", "text": "import re\nfrom random import randrange\nfrom model.contact import Contact\n\n\ndef test_random_contact_data_on_home_page(app):\n contacts = app.contact.get_contact_list()\n index = randrange(len(contacts))\n contact_from_home_page = app.contact.get_contact_list()[index]\n contact_from_edit_page = app.contact.get_contact_info_from_edit_page(index)\n assert contact_from_home_page.all_phones_from_home_page == merge_phones_like_on_home_page(contact_from_edit_page)\n assert contact_from_home_page.all_email_from_home_page == merge_email_like_on_home_page(contact_from_edit_page)\n assert contact_from_home_page.firstname == contact_from_edit_page.firstname\n assert contact_from_home_page.lastname == contact_from_edit_page.lastname\n assert contact_from_home_page.address == contact_from_edit_page.address\n\n\ndef clear(s):\n return re.sub(\"[() -]\", \"\", s)\n\n\ndef merge_phones_like_on_home_page(contact):\n return \"\\n\".join(filter(lambda x: x != \"\",\n map(lambda x: clear(x),\n filter(lambda x: x is not None,\n [contact.homenumber, contact.mobilenumber, contact.worknumber, contact.secondarynumber]))))\n\n\ndef merge_email_like_on_home_page(contact):\n return \"\\n\".join(filter(lambda x: x != \"\",\n filter(lambda x: x is not None, [contact.email, contact.email2, contact.email3])))\n\n\ndef test_full_contacts_data_on_home_page(app, db):\n contacts = app.contact.get_contact_list()\n count = len(contacts)\n contacts_from_db = sorted(list(db.get_contact_list()), key=Contact.id_or_max)\n contacts_from_ui = sorted(list(app.contact.get_contact_list()), key=Contact.id_or_max)\n for i in range(count):\n assert contacts_from_ui[i].firstname.strip() == contacts_from_db[i].firstname.strip()\n assert contacts_from_ui[i].lastname.strip() == contacts_from_db[i].lastname.strip()\n assert contacts_from_ui[i].address.strip() == contacts_from_db[i].address.strip()\n assert contacts_from_ui[i].all_email_from_home_page == merge_email_like_on_home_page(contacts_from_db[i])\n assert contacts_from_ui[i].all_phones_from_home_page == merge_phones_like_on_home_page(contacts_from_db[i])\n" }, { "alpha_fraction": 0.604873776435852, "alphanum_fraction": 0.6144473552703857, "avg_line_length": 48.956520080566406, "blob_id": "aa08118b1229f7a34310979ef8ce6e60042c5f55", "content_id": "36c336a2fcf1884bc3a06d4bfc9272b9065c84b8", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1169, "license_type": "permissive", "max_line_length": 123, "num_lines": 23, "path": "/test/test_del_contact.py", "repo_name": "AklerQ/python_training", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom model.contact import Contact\nimport random\n\n\ndef test_delete_first_contact(app, db, check_ui):\n if app.contact.count_contacts() == 0:\n app.contact.create(Contact(firstname=\"Тест_имени\", lastname=\"Тест_фамилии\",\n birth_date=\"//div[@id='content']/form/select[1]//option[1]\",\n birth_month=\"//div[@id='content']/form/select[2]//option[1]\",\n anniversary_date=\"//div[@id='content']/form/select[3]//option[1]\",\n anniversary_month=\"//div[@id='content']/form/select[4]//option[1]\"))\n old_contacts = db.get_contact_list()\n contact = random.choice(old_contacts)\n app.contact.delete_contact_by_id(contact.id)\n # Test validation\n new_contacts = db.get_contact_list()\n assert len(old_contacts) - 1 == len(new_contacts)\n old_contacts.remove(contact)\n assert old_contacts == new_contacts\n if check_ui:\n new_contacts = map(app.contact.clean, db.get_contact_list())\n assert sorted(new_contacts, key=Contact.id_or_max) == sorted(app.contact.get_contact_list(), key=Contact.id_or_max)\n" }, { "alpha_fraction": 0.6227223873138428, "alphanum_fraction": 0.625937819480896, "avg_line_length": 37.875, "blob_id": "bd60c93b3c31c44e71bce028acfcb995ef04bb70", "content_id": "c3934c14c0490a13fb1c51165bc7da7c13eb9488", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1866, "license_type": "permissive", "max_line_length": 117, "num_lines": 48, "path": "/model/contact.py", "repo_name": "AklerQ/python_training", "src_encoding": "UTF-8", "text": "from sys import maxsize\n\n\nclass Contact:\n\n def __init__(self, firstname=None, middlename=None, lastname=None, nickname=None, companyname=None, address=None,\n homenumber=None, worknumber=None, mobilenumber=None, faxnumber=None, email=None, email2=None,\n birth_date=None, birth_month=None, birth_year=None, anniversary_date=None, anniversary_month=None,\n secondarynumber=None, notes=None, id=None, email3=None, all_phones_from_home_page=None,\n all_email_from_home_page=None, new_group=None):\n self.firstname = firstname\n self.middlename = middlename\n self.lastname = lastname\n self.nickname = nickname\n self.companyname = companyname\n self.address = address\n self.homenumber = homenumber\n self.mobilenumber = mobilenumber\n self.worknumber = worknumber\n self.faxnumber = faxnumber\n self.email = email\n self.email2 = email2\n self.email3 = email3\n self.birth_date = birth_date\n self.birth_month = birth_month\n self.birth_year = birth_year\n self.anniversary_date = anniversary_date\n self.anniversary_month = anniversary_month\n self.secondarynumber = secondarynumber\n self.notes = notes\n self.id = id\n self.all_phones_from_home_page = all_phones_from_home_page\n self.all_email_from_home_page = all_email_from_home_page\n self.new_group = new_group\n\n\n def __repr__(self):\n return \"%s:%s:%s\" % (self.id, self.firstname, self.lastname)\n\n def __eq__(self, other):\n return (self.id == other.id or self.id is None) and self.firstname == other.firstname \\\n and self.lastname == other.lastname\n\n def id_or_max(self):\n if self.id:\n return int(self.id)\n else:\n return maxsize\n" }, { "alpha_fraction": 0.6801619529724121, "alphanum_fraction": 0.6801619529724121, "avg_line_length": 34.28571319580078, "blob_id": "113e738ddd774b06cbc555f5cffa3da4b42a6e4d", "content_id": "8127bbdc213474d8c20c0c50268c040a297bcf57", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 247, "license_type": "permissive", "max_line_length": 87, "num_lines": 7, "path": "/test/test_db_matches_ui.py", "repo_name": "AklerQ/python_training", "src_encoding": "UTF-8", "text": "from model.group import Group\n\n\ndef test_group_list(app, db):\n ui_list = app.group.get_group_list()\n db_list = map(app.group.clean, db.get_group_list())\n assert sorted(ui_list, key=Group.id_or_max) == sorted(db_list, key=Group.id_or_max)\n" }, { "alpha_fraction": 0.6232501268386841, "alphanum_fraction": 0.6335970759391785, "avg_line_length": 48.727272033691406, "blob_id": "631ca442b7814f47c54a951ae1aeffaf541587f3", "content_id": "860a9560353d118a9b2d86b08f243f91865e59db", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1731, "license_type": "permissive", "max_line_length": 110, "num_lines": 33, "path": "/test/test_add_contact_to_group.py", "repo_name": "AklerQ/python_training", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom model.group import Group\nfrom model.contact import Contact\nfrom fixture.orm import ORMfixture\nimport random\n\norm = ORMfixture(host=\"127.0.0.1\", name=\"addressbook\", user=\"root\", password=\"root\")\n\n\ndef test_add_contact_to_group(app, db):\n # Проверка на наличие групп\n if len(db.get_group_list()) == 0:\n app.group.create(Group(name=\"For adds contact\", header=\"For adds contact\", footer=\"For adds contact\"))\n # Проверка на наличие свободных контактов\n if len(db.get_contacts_out_groups()) == 0:\n app.contact.create(Contact(firstname=\"Тест_добавления\", lastname=\"Тест_для_добавления\",\n birth_date=\"//div[@id='content']/form/select[1]//option[1]\",\n birth_month=\"//div[@id='content']/form/select[2]//option[1]\",\n anniversary_date=\"//div[@id='content']/form/select[3]//option[1]\",\n anniversary_month=\"//div[@id='content']/form/select[4]//option[1]\",\n new_group=\"//select[@name='new_group']/option[@value='[none]']\"))\n contact_list = db.get_contacts_out_groups()\n contact = random.choice(contact_list)\n group_list = db.get_group_list()\n group = random.choice(group_list)\n app.navigation.turn_to_home_page()\n app.contact.select_contact_by_id(contact.id)\n app.group.select_group_by_id_for_add_to(group.id)\n app.contact.add_contact_to_group()\n app.navigation.open_group_page_by_id(group.id)\n # test validation\n assert contact in list(orm.get_contacts_in_group(group))\n assert contact not in list(db.get_contacts_out_groups())\n\n\n" }, { "alpha_fraction": 0.5947734117507935, "alphanum_fraction": 0.6129672527313232, "avg_line_length": 40.98611068725586, "blob_id": "b36ace0a5d437b08e2d835448b55a31264c9f9a5", "content_id": "b75a4fe69049757c22f818752df836a48483a924", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3023, "license_type": "permissive", "max_line_length": 120, "num_lines": 72, "path": "/generator/contact_gen.py", "repo_name": "AklerQ/python_training", "src_encoding": "UTF-8", "text": "from model.contact import Contact\nimport random\nimport string\nimport os.path\nimport jsonpickle\nimport getopt\nimport sys\n\n\ntry:\n opts, args = getopt.getopt(sys.argv[1:], \"n:f:\", [\"number of contacts\", \"file\"])\nexcept getopt.GetoptError as err:\n getopt.usage()\n sys.exit(2)\n\n\nn = 5\nf = \"data/contacts.json\"\n\n\nfor o, a in opts:\n if o == \"-n\":\n n = int(a)\n elif o == \"-f\":\n f = a\n\n\ndef random_string(prefix, maxlen):\n symbols = string.ascii_letters + string.digits + \" \"*10\n return prefix + \"\".join([random.choice(symbols) for i in range(random.randrange(maxlen))])\n\n\ndef random_number(maxlen):\n symbols = string.digits + \")\" + \"(\" + \"-\" + \" \"\n return \"\".join([random.choice(symbols) for i in range(random.randrange(maxlen))])\n\n\ndef random_email(maxlen):\n symbols = string.ascii_lowercase + string.digits + \"_\" + \"-\"\n return \"\".join([random.choice(symbols) for i in range(random.randrange(maxlen))] + ['@'] + [random.choice(symbols)\n for i in range(random.randrange(maxlen))] + ['.', 'ru'])\n\n\ndef random_date(maxlen):\n return str(random.randrange(maxlen))\n\n\ntestdata = [Contact(firstname=\"\", middlename=\"\", lastname=\"\", nickname=\"\", companyname=\"\", address=\"\",\n homenumber=\"\", worknumber=\"\", email=\"\", email2=\"\", mobilenumber=\"\",\n birth_date=\"//div[@id='content']/form/select[1]//option[1]\",\n birth_month=\"//div[@id='content']/form/select[2]//option[1]\", birth_year=\"\",\n anniversary_date=\"//div[@id='content']/form/select[3]//option[1]\",\n anniversary_month=\"//div[@id='content']/form/select[4]//option[1]\", notes=\"\",\n secondarynumber=\"\", new_group=\"//select[@name='new_group']/option[@value='[none]']\")] + [\nContact(firstname=random_string(\"firstname\", 10), middlename=random_string(\"middlename\", 10), lastname=random_string\n(\"lastname\", 10), nickname=random_string(\"nickname\", 10), companyname=random_string(\"companyname\", 10), address=\nrandom_string(\"address\", 25), homenumber=random_number(9), mobilenumber=random_number(12), worknumber=random_number(12),\nemail=random_email(6), email2=random_email(7), email3=random_email(8),\nbirth_date=\"//div[@id='content']/form/select[1]//option[\"+random_date(32)+\"]\",\nbirth_month=\"//div[@id='content']/form/select[2]//option[\"+random_date(13)+\"]\", birth_year=random_number(4),\nanniversary_date=\"//div[@id='content']/form/select[3]//option[\"+random_date(32)+\"]\", notes=random_string(\"name\", 30),\nanniversary_month=\"//div[@id='content']/form/select[4]//option[\"+random_date(13)+\"]\", secondarynumber=random_number(12),\nnew_group=\"//select[@name='new_group']/option[@value='[none]']\")\n for i in range(5)]\n\n\nfile = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"..\", f)\n\n\nwith open(file, \"w\") as out:\n jsonpickle.set_encoder_options(\"json\", indent=2)\n out.write(jsonpickle.encode(testdata))\n" }, { "alpha_fraction": 0.8448275923728943, "alphanum_fraction": 0.8448275923728943, "avg_line_length": 28, "blob_id": "d5fe65e0fa38a9e2af848af58a7e9eb594dcfbfc", "content_id": "0251e10a1d88fa5e2cdf1ca65e7deb7bbbe72fcd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 58, "license_type": "permissive", "max_line_length": 39, "num_lines": 2, "path": "/README.md", "repo_name": "AklerQ/python_training", "src_encoding": "UTF-8", "text": "# python_training\nHomework repository for python training\n" }, { "alpha_fraction": 0.5585322976112366, "alphanum_fraction": 0.5626091957092285, "avg_line_length": 38.906978607177734, "blob_id": "2c980515d6ae02f58439ce4efcaa994a5b35e5fe", "content_id": "9ee663f1976243015593ef2e6378aafdb596856e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1717, "license_type": "permissive", "max_line_length": 100, "num_lines": 43, "path": "/fixture/navigation.py", "repo_name": "AklerQ/python_training", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nclass NavigationHelper:\n\n def __init__(self, app):\n self.app = app\n\n def open_home_page(self):\n wd = self.app.wd\n if not ((len(wd.find_elements_by_link_text(\"Create account\")) > 0)\n and (len(wd.find_elements_by_link_text(\"Forgot password\")) > 0)):\n wd.get(self.app.base_url)\n\n def turn_to_home_page(self):\n wd = self.app.wd\n if not (len(wd.find_elements_by_name(\"add\")) > 0\n and wd.find_element_by_xpath(\"//*[contains(text(), 'Number of results')]\")):\n wd.find_element_by_link_text(\"home\").click()\n\n def return_to_home_page(self):\n wd = self.app.wd\n if not (len(wd.find_elements_by_name(\"add\")) > 0\n and wd.find_element_by_xpath(\"//*[contains(text(), 'Number of results')]\")):\n wd.find_element_by_link_text(\"home page\").click()\n\n def open_groups_page(self):\n wd = self.app.wd\n if not (wd.current_url.endswith(\"/group.php\") and len(wd.find_elements_by_name(\"new\")) > 0):\n wd.find_element_by_link_text(\"groups\").click()\n\n def return_to_groups_page(self):\n wd = self.app.wd\n if not (wd.current_url.endswith(\"/group.php\") and len(wd.find_elements_by_name(\"new\")) > 0):\n wd.find_element_by_link_text(\"group page\").click()\n\n def open_contact_edit_page_by_id(self, id):\n wd = self.app.wd\n if not wd.current_url.endswith(\"/edit.php?id=%s\" % id):\n wd.get(self.app.base_url+\"/edit.php?id=%s\" % id)\n\n def open_group_page_by_id(self, id):\n wd = self.app.wd\n if not wd.current_url.endswith(\"/?group=%s\" % id):\n wd.get(self.app.base_url+\"?group=%s\" % id)\n\n" } ]
14
NuriAmari/website-server
https://github.com/NuriAmari/website-server
983af395b640d761fd0deeabd5a13eb3f8e27e5f
c0f47ed0ceba4355c5109b5b43a09e9dc2f49cbd
6700ef35a992272abc1d821a1310d5726d08e84f
refs/heads/master
2023-02-11T19:53:32.674435
2021-01-07T22:11:02
2021-01-07T22:11:02
324,398,623
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6739469766616821, "alphanum_fraction": 0.6833073496818542, "avg_line_length": 25.70833396911621, "blob_id": "74221edcd5972705ef55b81e498ae693e245394e", "content_id": "17300783e3b93838ada9f12d6146214b3f747f68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 641, "license_type": "no_license", "max_line_length": 58, "num_lines": 24, "path": "/main.py", "repo_name": "NuriAmari/website-server", "src_encoding": "UTF-8", "text": "from tornado.httpserver import HTTPServer\nfrom tornado.ioloop import IOLoop\nimport os\n\nfrom tornado.web import Application\nfrom chess_ws_server import WSHandler\nfrom auth import AuthHandler\nfrom nuri_format import FormatHandler, LintHandler\n\napplication = Application(\n [\n (r\"^/api/lint\", LintHandler),\n (r\"^/api/format\", FormatHandler),\n (r\"^/api/auth\", AuthHandler),\n (r\"^/ws\", WSHandler),\n ],\n cookie_secret=os.environ.get(\"TORNADO_COOKIE_SECRET\"),\n websocket_ping_interval=15,\n)\n\nif __name__ == \"__main__\":\n server = HTTPServer(application)\n server.listen(8000)\n IOLoop.current().start()\n" }, { "alpha_fraction": 0.7826989889144897, "alphanum_fraction": 0.783390998840332, "avg_line_length": 89.3125, "blob_id": "847eb5093babbb2f4d296fd3b9ee3aa38687c2bb", "content_id": "2c7dd69c517fa74bbc9cd22e2bf5bbe60e7ca950", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1445, "license_type": "no_license", "max_line_length": 335, "num_lines": 16, "path": "/README.md", "repo_name": "NuriAmari/website-server", "src_encoding": "UTF-8", "text": "This repository contains source code and configuration for a series of tools that support my [new website](https://nuriamari.dev). More information about the client side can be found [here](https://github.com/NuriAmari/website).\n\n## Hosting\n\nThis entire system is currently run on an Ubuntu machine provided by [AWS](https://aws.amazon.com/ec2/instance-types/). Static files are served using an [NGINX](https://www.nginx.com/) proxy, behind which a small [Tornado](https://www.tornadoweb.org/en/stable/) webserver operates.\nThe webserver currently supports the site's Chess functionality, communicating over regular HTTP and Websockets. SSL certs are generated using [Let's Encrypt](https://letsencrypt.org/) and the entire system, aside from domain registration, is free.\n\n## Persistance\n\nIn order to persist game state during maintenance or after downtime of any sort, site information (mostly chess game state) is stored in Redis, running on the same machine. Redis was chosen for its speed and convenient data structures. [Redis-py](https://github.com/andymccurdy/redis-py) is used to communicate with the Redis instance.\n\n## Tornado Service\n\nFor convenience, the Tornado webserver is configured to be managed by [systemd](https://en.wikipedia.org/wiki/Systemd).\n\nIn the future, I think it would be interesting to add health checks and metric collection using tools like [collectd](https://collectd.org/) and [Grafana](https://grafana.com/)\n" }, { "alpha_fraction": 0.3886328637599945, "alphanum_fraction": 0.3906809985637665, "avg_line_length": 33.26315689086914, "blob_id": "79eeac35fad71a964baf3599fda8a86a601a28ae", "content_id": "057ce56178ef72cdcda7883030ca925b1b4ea61e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1953, "license_type": "no_license", "max_line_length": 129, "num_lines": 57, "path": "/nuri_format.py", "repo_name": "NuriAmari/website-server", "src_encoding": "UTF-8", "text": "from tornado.web import RequestHandler\nfrom simplejson.src.json import json\n\nfrom langtools.lexer.exceptions import LexicalError\n\nimport json as simplejson\n\n\nclass FormatHandler(RequestHandler):\n def post(self):\n try:\n content_str = self.request.body.decode(\"utf-8\")\n content = json.loads(content_str)\n except LexicalError as le:\n self.write(\n simplejson.dumps(\n {\n \"content\": content_str,\n \"annotations\": [\n {\n \"type\": \"error\",\n \"text\": f\"Unexpected Character: {le.error_char} at line {le.error_line + 1}, col {le.error_col}\",\n \"row\": le.error_line,\n \"column\": le.error_col,\n }\n ],\n \"markers\": [\n {\n \"startRow\": le.error_line,\n \"endRow\": le.error_line,\n \"startCol\": le.error_col,\n \"endCol\": le.error_col + 1,\n \"type\": \"text\",\n \"className\": \"error-marker\",\n }\n ],\n }\n )\n )\n except Exception as e:\n print(e)\n self.write(\n simplejson.dumps({\"content\": '{\"oops\": true}', \"annotations\": []})\n )\n else:\n self.write(\n simplejson.dumps({\"content\": json.dumps(content), \"annotations\": []})\n )\n\n\nclass LintHandler(RequestHandler):\n def post(self):\n self.write(\n json.dumps(\n {\"content\": self.request.body.decode(\"utf-8\"), \"annotations\": []}\n )\n )\n" }, { "alpha_fraction": 0.6379562020301819, "alphanum_fraction": 0.645255446434021, "avg_line_length": 28.782608032226562, "blob_id": "a3dc2457ffec4b8e6e14bd8ae352a8b91c94bc18", "content_id": "ca9b1afc107466a501200d56110f1bcba9812360", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 685, "license_type": "no_license", "max_line_length": 75, "num_lines": 23, "path": "/auth.py", "repo_name": "NuriAmari/website-server", "src_encoding": "UTF-8", "text": "import secrets\nimport json\nimport os\n\nimport redis\nfrom tornado.web import RequestHandler\n\nr = redis.Redis(host=\"localhost\", port=6379, db=0)\n\nusername = os.environ.get(\"WEBSITE_USERNAME\")\npassword = os.environ.get(\"WEBSITE_PASSWORD\")\n\n\nclass AuthHandler(RequestHandler):\n def post(self):\n data = json.loads(self.request.body)\n if data[\"username\"] == username and data[\"password\"] == password:\n auth_cookie = secrets.token_urlsafe()\n r.sadd(\"COOKIES\", auth_cookie)\n self.set_secure_cookie(\"auth\", auth_cookie)\n self.write(json.dumps({\"success\": True}))\n else:\n self.write(json.dumps({\"success\": False}))\n" }, { "alpha_fraction": 0.582848846912384, "alphanum_fraction": 0.582848846912384, "avg_line_length": 31.714284896850586, "blob_id": "ac39f42030d0850963a4171614a41546a891b9ba", "content_id": "cea20a28dcacf8a5c9e5ec91be839b8644cbbed9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 688, "license_type": "no_license", "max_line_length": 70, "num_lines": 21, "path": "/mail.py", "repo_name": "NuriAmari/website-server", "src_encoding": "UTF-8", "text": "import os\nfrom sendgrid import SendGridAPIClient\nfrom sendgrid.helpers.mail import Mail\n\ndef send_notification():\n if os.environ.get('MODE') == 'PROD':\n message = Mail(\n from_email=os.environ.get('WEBSITE_EMAIL'),\n to_emails=os.environ.get('WEBSITE_EMAIL'),\n subject='Your move pal',\n html_content=\"<p>Someone's made a move</p>\"\n )\n\n try:\n sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))\n response = sg.send(message)\n print(response.status_code)\n print(response.body)\n print(response.headers)\n except Exception as e:\n print(e.message)\n\n" }, { "alpha_fraction": 0.5288461446762085, "alphanum_fraction": 0.692307710647583, "avg_line_length": 16.33333396911621, "blob_id": "9ed6bbf1ba3a92b75c9e3de18a619ce388208c74", "content_id": "48591f2f921e40a62d0df399f2f9e1e1b5040017", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 104, "license_type": "no_license", "max_line_length": 25, "num_lines": 6, "path": "/requirements.txt", "repo_name": "NuriAmari/website-server", "src_encoding": "UTF-8", "text": "chess==1.3.2\npython-http-client==3.3.1\nredis==3.5.3\nsendgrid==6.4.8\nstarkbank-ecdsa==1.1.0\ntornado==6.1\n" }, { "alpha_fraction": 0.4756455421447754, "alphanum_fraction": 0.4809272289276123, "avg_line_length": 23.69565200805664, "blob_id": "b29aaf99e912453e9788a2d4a6d918201833e6fb", "content_id": "b19d276ed36539ee916ffc095859188c30688997", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3408, "license_type": "no_license", "max_line_length": 87, "num_lines": 138, "path": "/chess_ws_server.py", "repo_name": "NuriAmari/website-server", "src_encoding": "UTF-8", "text": "from typing import Set\nimport json\nimport threading\n\nimport redis\nimport chess\nfrom tornado.websocket import WebSocketHandler\n\nfrom mail import send_notification\n\nclients: Set[WebSocketHandler] = set()\nr = redis.Redis(host=\"localhost\", port=6379, db=0)\n\n\ndef get_white_wins():\n if not r.exists(\"W_WINS\"):\n r.set(\"W_WINS\", 0)\n return r.get(\"W_WINS\").decode(\"utf-8\")\n\n\ndef get_black_wins():\n if not r.exists(\"B_WINS\"):\n r.set(\"B_WINS\", 0)\n return r.get(\"B_WINS\").decode(\"utf-8\")\n\n\ndef get_most_recent_UCI():\n if not r.exists(\"MR_UCI\"):\n r.set(\"MR_UCI\", \"\")\n return r.get(\"MR_UCI\").decode(\"utf-8\")\n\n\ndef white_win():\n r.incr(\"W_WINS\")\n\n\ndef black_win():\n r.incr(\"B_WINS\")\n\n\ndef reset_board():\n r.set(\"FEN\", chess.STARTING_FEN)\n\n\ndef get_board_state():\n if not r.exists(\"FEN\"):\n reset_board()\n return r.get(\"FEN\").decode(\"utf-8\")\n\n\ndef get_move_history():\n return [move.decode(\"utf-8\") for move in r.lrange(\"HISTORY\", 0, -1)]\n\n\ndef broadcast(fen):\n for client in clients:\n client.write_message(fen)\n\n\nclass WSHandler(WebSocketHandler):\n def check_origin(self, origin):\n return True\n\n def open(self):\n clients.add(self)\n self.write_message(\n json.dumps(\n {\n \"FEN\": get_board_state(),\n \"W_WINS\": get_white_wins(),\n \"B_WINS\": get_black_wins(),\n \"HISTORY\": get_move_history(),\n \"MR_UCI\": get_most_recent_UCI(),\n }\n )\n )\n\n def reset(self):\n reset_board()\n r.delete(\"HISTORY\")\n r.set(\"MR_UCI\", \"\")\n broadcast(\n json.dumps(\n {\n \"FEN\": get_board_state(),\n \"W_WINS\": get_white_wins(),\n \"B_WINS\": get_black_wins(),\n \"HISTORY\": get_move_history(),\n \"MR_UCI\": get_most_recent_UCI(),\n }\n )\n )\n\n def on_message(self, message):\n board = chess.Board(get_board_state())\n next_move = board.parse_san(message)\n\n if board.turn == chess.BLACK:\n # check for auth cookie\n auth_cookie = self.get_secure_cookie(\"auth\")\n if not auth_cookie or not r.sismember(\"COOKIES\", auth_cookie):\n return\n\n try:\n board.push_san(message)\n except ValueError:\n # ignore illegal moves\n pass\n else:\n new_board_state = board.fen()\n r.set(\"FEN\", new_board_state)\n r.rpush(\"HISTORY\", message)\n r.set(\"MR_UCI\", next_move.uci())\n broadcast(\n json.dumps(\n {\"FEN\": new_board_state, \"SAN\": message, \"MR_UCI\": next_move.uci()}\n )\n )\n\n if board.turn == chess.BLACK:\n # notify me, someone has made a valid move\n send_notification()\n\n if board.is_game_over():\n result = board.result()\n if result == \"1-0\":\n white_win()\n elif result == \"0-1\":\n black_win()\n else:\n # draw\n white_win()\n black_win()\n\n self.reset()\n\n def on_close(self):\n clients.remove(self)\n" } ]
7
7h3rAm/kalpi
https://github.com/7h3rAm/kalpi
a091b65db82de4787a65d3f0e920bfdb4428a0fb
9142ecf96bcce51eecbb24f0ffd8a47a55795803
c63742de9286101f5d7835c1c6e1c8c2fa12696c
refs/heads/master
2023-02-22T16:21:21.613220
2023-02-08T03:05:41
2023-02-08T03:05:41
48,249,819
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5536128878593445, "alphanum_fraction": 0.5794716477394104, "avg_line_length": 48.39187240600586, "blob_id": "f5f6a23b2f5c6e52eeea9c210fe748c04a3a0aa8", "content_id": "611c65f802d556b54cc6b4b8a9a61512c04b5a82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 34238, "license_type": "no_license", "max_line_length": 238, "num_lines": 689, "path": "/bitcoin.py", "repo_name": "7h3rAm/kalpi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom datetime import datetime, timezone\nfrom pprint import pprint\nimport sparkline\nimport hashlib\nimport random\nimport time\nimport csv\n\nimport utils\n\n\"\"\"\nhttp://172.16.1.48:3006/api/v1/blocks/tip/height\nhttp://172.16.1.48:3006/api/v1/block-height/695148\nhttp://172.16.1.48:3006/api/v1/block/000000000000000015dc777b3ff2611091336355d3f0ee9766a2cf3be8e4b1ce\nhttp://172.16.1.48:3006/api/v1/block/000000000000000015dc777b3ff2611091336355d3f0ee9766a2cf3be8e4b1ce/txids\nhttp://172.16.1.48:3006/api/v1/block/000000000000000015dc777b3ff2611091336355d3f0ee9766a2cf3be8e4b1ce/txs\nhttp://172.16.1.48:3006/api/v1/blocks\nhttp://172.16.1.48:3006/api/v1/difficulty-adjustment\nhttp://172.16.1.48:3006/api/v1/fees/mempool-blocks\nhttp://172.16.1.48:3006/api/v1/fees/recommended\nhttp://172.16.1.48:3006/api/v1/mempool/txids\nhttp://172.16.1.48:3006/api/v1/mempool/recent\nhttp://172.16.1.48:3006/api/v1/tx/15e10745f15593a899cef391191bdd3d7c12412cc4696b7bcb669d0feadc8521\nhttp://172.16.1.48:3006/api/v1/tx/15e10745f15593a899cef391191bdd3d7c12412cc4696b7bcb669d0feadc8521/status\n\nhttps://api.coinpaprika.com/v1/tickers/btc-bitcoin\nhttps://chain.so/api/v2/get_address_balance\nhttps://chain.so/api/v2/get_tx_received\n\nhttps://api.github.com/repos/7h3rAm/writeups\nhttps://check.torproject.org/api/ip\nhttps://ifconfig.me/all.json\nhttp://ip-api.com/json/108.193.5.5\n\"\"\"\n\n\nclass Bitcoin:\n def __init__(self):\n self.datastore_url = \"https://raw.githubusercontent.com/7h3rAm/datastore/master\"\n self.datastorepath = \"%s/datastore\" % (utils.expand_env(var=\"$PROJECTSPATH\"))\n self.statsfilepath = \"%s/datastore/bitcoin.json\" % (utils.expand_env(var=\"$PROJECTSPATH\"))\n self.addressesfilepath = \"%s/toolbox/bootstrap/btctxsmon-addresses.json\" % (utils.expand_env(var=\"$HOME\"))\n self.addresses = utils.load_json(self.addressesfilepath)\n try:\n self.bitcoin = utils.load_json(self.statsfilepath)\n except:\n self.bitcoin = {\n \"category\": {\n \"donation\": {},\n \"popular\": {},\n \"ransom\": {}\n },\n \"graph\": {},\n \"last_update\": None,\n \"nodes\": [],\n \"nodessummary\": {},\n \"stats\": {\n \"count_address\": 0,\n \"count_wallet\": 0,\n \"count_received\": 0,\n \"count_sent\": 0,\n \"count_balance\": 0,\n \"count_txs\": 0,\n \"donation\": {\n \"count_wallet\": 0,\n \"count_address\": 0,\n \"count_received\": 0,\n \"count_sent\": 0,\n \"count_balance\": 0,\n \"count_txs\": 0,\n },\n \"popular\": {\n \"count_wallet\": 0,\n \"count_address\": 0,\n \"count_received\": 0,\n \"count_sent\": 0,\n \"count_balance\": 0,\n \"count_txs\": 0,\n },\n \"ransom\": {\n \"count_wallet\": 0,\n \"count_address\": 0,\n \"count_received\": 0,\n \"count_sent\": 0,\n \"count_balance\": 0,\n \"count_txs\": 0,\n },\n }\n }\n\n def sparkify(self, content, maxsize=10, unique=True, sparkmode=True, skiphashing=True):\n sparkid = content if skiphashing else hashlib.sha256(content.encode(\"utf-8\")).hexdigest()\n spark = \"\".join(sparkline.sparkify([int(x, base=16) for x in sparkid]))\n charmap = {\n \"▁\": \"◐\",\n \"▂\": \"■\",\n \"▃\": \"◩\",\n \"▄\": \"◆\",\n \"▅\": \"◢\",\n \"▆\": \"◨\",\n \"▇\": \"●\",\n \"█\": \"▲\",\n }\n if unique:\n sparkshort = \"\".join(['%s' % (ch if sparkmode else charmap[ch]) for ch in spark[:maxsize]])\n else:\n chars = [\"▣\", \"►\", \"◐\", \"◧\", \"▤\", \"▼\", \"◑\", \"◨\", \"▥\", \"◀\", \"◒\", \"◩\", \"▦\", \"◆\", \"◕\", \"◪\", \"▧\", \"◈\", \"◢\", \"■\", \"▨\", \"◉\", \"◣\", \"▩\", \"◎\", \"◤\", \"▲\", \"●\", \"◥\"]\n sparkshort = \"\".join(['%s' % (random.choice(chars)) for _ in range(len(sparkid[:maxsize]))])\n return sparkshort\n\n def load_from_csv(self):\n with open(\"%s/toolbox/bootstrap/btcpaymon.csv\" % (utils.expand_env(var=\"$HOME\"))) as csvfile:\n rows = csv.reader(csvfile, delimiter=\",\")\n header = next(rows)\n newaddresses = 0\n for row in rows:\n address = row[0]\n wallet = row[1].replace(\"_\", \" \")\n tag = row[2]\n category = row[3].lower()\n source = row[4].split(\";\") if row[4] and row[4] != \"\" else None\n if category not in [\"donation\", \"popular\", \"ransom\"]:\n continue\n if address not in self.addresses[\"category\"][category]:\n newaddresses += 1\n self.addresses[\"category\"][category][address] = {\n \"wallet\": wallet,\n \"tag\": tag,\n \"source\": source,\n \"received\": 0,\n \"sent\": 0,\n \"balance\": 0,\n \"transaction\": 0,\n \"lastseen\": None,\n \"lasttxepoch\": 0,\n }\n if newaddresses:\n print(\"added %d new addresses from %s file\" % (newaddresses, \"%s/toolbox/bootstrap/btcpaymon.csv\" % (utils.expand_env(var=\"$HOME\"))))\n\n def query_address(self, address, explorer=\"blockchaininfomulti\"):\n if explorer == \"chainso\":\n content = utils.get_http(\"https://chain.so/api/v2/address/BTC/%s\" % (address))\n if \"data\" in content and len(content[\"data\"][\"txs\"]):\n return {\n \"balance\": int(float(content[\"data\"][\"balance\"]) * (10**8)),\n \"received\": int(float(content[\"data\"][\"received_value\"]) * (10**8)),\n \"sent\": int((float(content[\"data\"][\"received_value\"])-float(content[\"data\"][\"balance\"])) * (10**8)),\n \"transaction\": int(content[\"data\"][\"total_txs\"]),\n \"lasttxepoch\": content[\"data\"][\"txs\"][0][\"time\"],\n \"lastseen\": time.strftime(\"%d/%b/%Y @ %H:%M:%S %Z\", time.localtime(content[\"data\"][\"txs\"][0][\"time\"])),\n }\n elif explorer == \"blockchaininfo\":\n content = utils.get_http(\"https://blockchain.info/rawaddr/%s\" % (address))\n if \"n_tx\" in content:\n return {\n \"transaction\": content[\"n_tx\"],\n \"received\": content[\"total_received\"],\n \"sent\": content[\"total_sent\"],\n \"balance\": content[\"final_balance\"],\n \"lasttxepoch\": content[\"txs\"][0][\"time\"] if len(content[\"txs\"]) else None,\n \"lastseen\": time.strftime(\"%d/%b/%Y @ %H:%M:%S %Z\", time.localtime(content[\"txs\"][0][\"time\"])) if len(content[\"txs\"]) else \"\",\n }\n elif explorer == \"blockchaininfomulti\":\n content = utils.get_http(\"https://blockchain.info/multiaddr?active=%s\" % (address))\n if \"addresses\" in content and content[\"addresses\"][0][\"address\"] == address:\n return {\n \"transaction\": content[\"addresses\"][0][\"n_tx\"],\n \"received\": content[\"addresses\"][0][\"total_received\"],\n \"sent\": content[\"addresses\"][0][\"total_sent\"],\n \"balance\": content[\"addresses\"][0][\"final_balance\"],\n \"lasttxepoch\": content[\"txs\"][0][\"time\"] if len(content[\"txs\"]) else None,\n \"lastseen\": time.strftime(\"%d/%b/%Y @ %H:%M:%S %Z\", time.localtime(content[\"txs\"][0][\"time\"])) if len(content[\"txs\"]) else \"\",\n }\n\n def update_category(self, category, force=False):\n updated, foundaddresses = [], []\n chunks = list(utils.chunkify(list(self.addresses[\"category\"][category].keys()), 50))\n print(\"performing lookup for %d chunks of %d %s addresses\" % (len(chunks), len(list(self.addresses[\"category\"][category].keys())), category))\n for chunk in chunks:\n stats = utils.get_http(\"https://blockchain.info/multiaddr?active=%s\" % (\"|\".join(chunk)))\n if \"addresses\" in stats:\n for entry in stats[\"addresses\"]:\n foundaddresses.append(entry[\"address\"])\n if force or entry[\"n_tx\"] != self.addresses[\"category\"][category][entry[\"address\"]][\"transaction\"] or not self.addresses[\"category\"][category][entry[\"address\"]][\"lastseen\"]:\n # new txs since we last updated this address, update with new lasttx\n self.addresses[\"category\"][category][entry[\"address\"]][\"transaction\"] = entry[\"n_tx\"]\n self.addresses[\"category\"][category][entry[\"address\"]][\"balance\"] = entry[\"final_balance\"]\n self.addresses[\"category\"][category][entry[\"address\"]][\"received\"] = entry[\"total_received\"]\n self.addresses[\"category\"][category][entry[\"address\"]][\"sent\"] = entry[\"total_sent\"]\n self.addresses[\"category\"][category][entry[\"address\"]][\"lastseen\"] = None\n self.addresses[\"category\"][category][entry[\"address\"]][\"lasttxepoch\"] = None\n self.addresses[\"category\"][category][entry[\"address\"]][\"retired\"] = False\n updated.append(entry[\"address\"])\n alladdresses = list(self.addresses[\"category\"][category].keys())\n updated.extend(list(set(alladdresses)-set(foundaddresses)))\n updated = list(set(updated))\n print(\"updating stats for %d %s addresses\" % (len(updated), category))\n for address in updated:\n stats = self.query_address(address)\n if stats:\n self.addresses[\"category\"][category][address][\"transaction\"] = stats[\"transaction\"]\n self.addresses[\"category\"][category][address][\"received\"] = stats[\"received\"]\n self.addresses[\"category\"][category][address][\"sent\"] = stats[\"sent\"]\n self.addresses[\"category\"][category][address][\"balance\"] = stats[\"balance\"]\n self.addresses[\"category\"][category][address][\"lasttxepoch\"] = stats[\"lasttxepoch\"]\n self.addresses[\"category\"][category][address][\"lastseen\"] = stats[\"lastseen\"]\n self.addresses[\"category\"][category][address][\"retired\"] = False\n else:\n if self.addresses[\"category\"][category][address][\"transaction\"] == 0:\n # this address has no txs and we could not find stats via 2 public apis; mark it retired\n self.addresses[\"category\"][category][address][\"retired\"] = True\n else:\n self.addresses[\"category\"][category][address][\"retired\"] = False\n\n def group_wallet(self):\n self.bitcoin[\"category\"][\"donation\"] = {}\n self.bitcoin[\"category\"][\"popular\"] = {}\n self.bitcoin[\"category\"][\"ransom\"] = {}\n self.bitcoin[\"stats\"] = {\n \"count_address\": 0,\n \"count_wallet\": 0,\n \"count_received\": 0,\n \"count_sent\": 0,\n \"count_balance\": 0,\n \"count_txs\": 0,\n \"donation\": {\n \"count_wallet\": 0,\n \"count_address\": 0,\n \"count_received\": 0,\n \"count_sent\": 0,\n \"count_balance\": 0,\n \"count_txs\": 0,\n },\n \"popular\": {\n \"count_wallet\": 0,\n \"count_address\": 0,\n \"count_received\": 0,\n \"count_sent\": 0,\n \"count_balance\": 0,\n \"count_txs\": 0,\n },\n \"ransom\": {\n \"count_wallet\": 0,\n \"count_address\": 0,\n \"count_received\": 0,\n \"count_sent\": 0,\n \"count_balance\": 0,\n \"count_txs\": 0,\n },\n }\n\n for category in [\"donation\", \"popular\", \"ransom\"]:\n print(\"grouping %d addresses for %s category\" % (len(self.addresses[\"category\"][category]), category))\n for address in self.addresses[\"category\"][category]:\n if self.addresses[\"category\"][category][address][\"retired\"]:\n continue\n wallet = self.addresses[\"category\"][category][address][\"wallet\"]\n if wallet not in self.bitcoin[\"category\"][category]:\n self.bitcoin[\"category\"][category][wallet] = {\n \"addresses\": 0,\n \"received\": 0,\n \"sent\": 0,\n \"balance\": 0,\n \"transaction\": 0,\n \"lasttxepoch\": None,\n \"lastseen\": None,\n }\n self.bitcoin[\"category\"][category][wallet][\"addresses\"] += 1\n self.bitcoin[\"category\"][category][wallet][\"received\"] += (self.addresses[\"category\"][category][address][\"received\"] / (10**8))\n self.bitcoin[\"category\"][category][wallet][\"sent\"] += (self.addresses[\"category\"][category][address][\"sent\"] / (10**8))\n self.bitcoin[\"category\"][category][wallet][\"balance\"] += (self.addresses[\"category\"][category][address][\"balance\"] / (10**8))\n self.bitcoin[\"category\"][category][wallet][\"transaction\"] += self.addresses[\"category\"][category][address][\"transaction\"]\n\n if self.addresses[\"category\"][category][address][\"lasttxepoch\"]:\n if not self.bitcoin[\"category\"][category][wallet][\"lasttxepoch\"]:\n self.bitcoin[\"category\"][category][wallet][\"lasttxepoch\"] = self.addresses[\"category\"][category][address][\"lasttxepoch\"]\n self.bitcoin[\"category\"][category][wallet][\"lastseen\"] = time.strftime(\"%d/%b/%Y @ %H:%M:%S %Z\", time.localtime(self.bitcoin[\"category\"][category][wallet][\"lasttxepoch\"]))\n else:\n if self.addresses[\"category\"][category][address][\"lasttxepoch\"] > self.bitcoin[\"category\"][category][wallet][\"lasttxepoch\"]:\n self.bitcoin[\"category\"][category][wallet][\"lasttxepoch\"] = self.addresses[\"category\"][category][address][\"lasttxepoch\"]\n self.bitcoin[\"category\"][category][wallet][\"lastseen\"] = time.strftime(\"%d/%b/%Y @ %H:%M:%S %Z\", time.localtime(self.bitcoin[\"category\"][category][wallet][\"lasttxepoch\"]))\n\n for wallet in self.bitcoin[\"category\"][category]:\n self.bitcoin[\"stats\"][category][\"count_received\"] += self.bitcoin[\"category\"][category][wallet][\"received\"]\n self.bitcoin[\"stats\"][category][\"count_sent\"] += self.bitcoin[\"category\"][category][wallet][\"sent\"]\n self.bitcoin[\"stats\"][category][\"count_txs\"] += self.bitcoin[\"category\"][category][wallet][\"transaction\"]\n self.bitcoin[\"stats\"][category][\"count_balance\"] += self.bitcoin[\"category\"][category][wallet][\"balance\"]\n self.bitcoin[\"stats\"][category][\"count_address\"] = len(self.addresses[\"category\"][category])\n self.bitcoin[\"stats\"][category][\"count_wallet\"] = len(self.bitcoin[\"category\"][category])\n self.bitcoin[\"category\"][category][wallet][\"sparkid\"] = self.sparkify(\"%x%x%x%x%x\" % (\n int(self.bitcoin[\"category\"][category][wallet][\"addresses\"] % 15),\n int(self.bitcoin[\"category\"][category][wallet][\"transaction\"] % 15),\n int(self.bitcoin[\"category\"][category][wallet][\"received\"] % 15),\n int(self.bitcoin[\"category\"][category][wallet][\"sent\"] % 15),\n int(self.bitcoin[\"category\"][category][wallet][\"balance\"] % 15),\n ), skiphashing=True)\n\n self.bitcoin[\"stats\"][\"count_address\"] = len(self.addresses[\"category\"][\"donation\"]) + len(self.addresses[\"category\"][\"popular\"]) + len(self.addresses[\"category\"][\"ransom\"])\n self.bitcoin[\"stats\"][\"count_wallet\"] = len(self.bitcoin[\"category\"][\"donation\"]) + len(self.bitcoin[\"category\"][\"popular\"]) + len(self.bitcoin[\"category\"][\"ransom\"])\n self.bitcoin[\"stats\"][\"count_received\"] = self.bitcoin[\"stats\"][\"donation\"][\"count_received\"] + self.bitcoin[\"stats\"][\"popular\"][\"count_received\"] + self.bitcoin[\"stats\"][\"ransom\"][\"count_received\"]\n self.bitcoin[\"stats\"][\"count_sent\"] = self.bitcoin[\"stats\"][\"donation\"][\"count_sent\"] + self.bitcoin[\"stats\"][\"popular\"][\"count_sent\"] + self.bitcoin[\"stats\"][\"ransom\"][\"count_sent\"]\n self.bitcoin[\"stats\"][\"count_balance\"] = self.bitcoin[\"stats\"][\"donation\"][\"count_balance\"] + self.bitcoin[\"stats\"][\"popular\"][\"count_balance\"] + self.bitcoin[\"stats\"][\"ransom\"][\"count_balance\"]\n self.bitcoin[\"stats\"][\"count_txs\"] = self.bitcoin[\"stats\"][\"donation\"][\"count_txs\"] + self.bitcoin[\"stats\"][\"popular\"][\"count_txs\"] + self.bitcoin[\"stats\"][\"ransom\"][\"count_txs\"]\n\n def update(self, skipupdate=False):\n self.load_from_csv()\n self.get_bitnodes()\n self.bitcoin[\"last_update_epoch\"] = datetime.now().astimezone(tz=None)\n self.bitcoin[\"last_update\"] = self.bitcoin[\"last_update_epoch\"].strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n utils.save_json(self.bitcoin, self.statsfilepath)\n if not skipupdate:\n for category in [\"donation\", \"popular\", \"ransom\"]:\n self.update_category(category)\n self.addresses[\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n utils.save_json(self.addresses, self.addressesfilepath)\n self.group_wallet()\n self.bitcoin[\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n utils.save_json(self.bitcoin, self.statsfilepath)\n\n def get_bitnodes(self):\n nodes = utils.get_http(\"https://bitnodes.io/api/v1/snapshots/latest/\")\n if nodes:\n self.bitcoin[\"nodes\"] = []\n self.bitcoin[\"nodessummary\"] = {\n \"asn\": {},\n \"country\": {},\n \"useragent\": {},\n \"timezone\": {},\n }\n print(\"adding stats for %d bitcoin nodes\" % len(nodes[\"nodes\"]))\n for node in nodes[\"nodes\"]:\n asn = nodes[\"nodes\"][node][11] if nodes[\"nodes\"][node][11] else \"Unknown\"\n city = nodes[\"nodes\"][node][6] if nodes[\"nodes\"][node][6] else \"Unknown\"\n connectedsince = nodes[\"nodes\"][node][2] if nodes[\"nodes\"][node][2] else \"Unknown\"\n connectedsincehuman = time.strftime(\"%d/%b/%Y @ %H:%M:%S %Z\", time.localtime(nodes[\"nodes\"][node][2])) if nodes[\"nodes\"][node][2] else \"Unknown\"\n country = nodes[\"nodes\"][node][7] if nodes[\"nodes\"][node][7] else \"Unknown\"\n height = nodes[\"nodes\"][node][4] if nodes[\"nodes\"][node][4] else \"Unknown\"\n hostname = nodes[\"nodes\"][node][5] if nodes[\"nodes\"][node][5] else \"Unknown\"\n ipurl = node\n latitude = nodes[\"nodes\"][node][8] if nodes[\"nodes\"][node][8] else \"Unknown\"\n longitude = nodes[\"nodes\"][node][9] if nodes[\"nodes\"][node][9] else \"Unknown\"\n orgname = nodes[\"nodes\"][node][12] if nodes[\"nodes\"][node][12] else \"Unknown\"\n protoversion = nodes[\"nodes\"][node][0] if nodes[\"nodes\"][node][0] else \"Unknown\"\n services = nodes[\"nodes\"][node][3] if nodes[\"nodes\"][node][3] else \"Unknown\"\n timezone = nodes[\"nodes\"][node][10] if nodes[\"nodes\"][node][10] else \"Unknown\"\n useragent = nodes[\"nodes\"][node][1] if nodes[\"nodes\"][node][1] else \"Unknown\"\n servicesflags = []\n if services & 0: servicesflags.append(\"NODE_NONE\")\n if services & (1 << 0): servicesflags.append(\"NODE_NETWORK\")\n if services & (1 << 1): servicesflags.append(\"NODE_GETUTXO\")\n if services & (1 << 2): servicesflags.append(\"NODE_BLOOM\")\n if services & (1 << 3): servicesflags.append(\"NODE_WITNESS\")\n if services & (1 << 4): servicesflags.append(\"NODE_XTHIN\")\n if services & (1 << 10): servicesflags.append(\"NODE_NETWORK_LIMITED\")\n self.bitcoin[\"nodes\"].append({\n \"asn\": asn,\n \"city\": city,\n \"connectedsince\": connectedsince,\n \"connectedsincehuman\": connectedsincehuman,\n \"country\": country,\n \"height\": height,\n \"hostname\": hostname,\n \"ipurl\": ipurl,\n \"latitude\": latitude,\n \"longitude\": longitude,\n \"orgname\": orgname,\n \"protoversion\": protoversion,\n \"services\": services,\n \"servicesflags\": servicesflags,\n \"timezone\": timezone,\n \"useragent\": useragent,\n })\n if asn not in self.bitcoin[\"nodessummary\"][\"asn\"]:\n self.bitcoin[\"nodessummary\"][\"asn\"][asn] = 1\n else:\n self.bitcoin[\"nodessummary\"][\"asn\"][asn] += 1\n if country not in self.bitcoin[\"nodessummary\"][\"country\"]:\n self.bitcoin[\"nodessummary\"][\"country\"][country] = 1\n else:\n self.bitcoin[\"nodessummary\"][\"country\"][country] += 1\n if timezone not in self.bitcoin[\"nodessummary\"][\"timezone\"]:\n self.bitcoin[\"nodessummary\"][\"timezone\"][timezone] = 1\n else:\n self.bitcoin[\"nodessummary\"][\"timezone\"][timezone] += 1\n if useragent not in self.bitcoin[\"nodessummary\"][\"useragent\"]:\n self.bitcoin[\"nodessummary\"][\"useragent\"][useragent] = 1\n else:\n self.bitcoin[\"nodessummary\"][\"useragent\"][useragent] += 1\n self.bitcoin[\"stats\"][\"count_nodes\"] = len(self.bitcoin[\"nodes\"])\n self.bitcoin[\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n utils.save_json(self.bitcoin, self.statsfilepath)\n\n def group_and_update(self, categories=[\"donation\", \"popular\", \"ransom\"]):\n with open(\"%s/toolbox/bootstrap/btcpaymon.csv\" % (utils.expand_env(var=\"$HOME\"))) as csvfile:\n self.addresses = {\n \"category\": {\n \"donation\": {},\n \"popular\": {},\n \"ransom\": {},\n }\n }\n rows = csv.reader(csvfile, delimiter=\",\")\n header = next(rows)\n for row in rows:\n address = row[0]\n wallet = row[1].replace(\"_\", \" \")\n tag = row[2]\n category = row[3].lower()\n source = row[4].split(\";\") if row[4] and row[4] != \"\" else None\n if category in [\"donation\", \"popular\", \"ransom\"] and address not in self.addresses[\"category\"][category]:\n self.addresses[\"category\"][category][address] = {\n \"wallet\": wallet,\n \"tag\": tag,\n \"source\": source,\n }\n\n for category in categories:\n self.bitcoin[\"category\"][category] = {}\n self.bitcoin[\"stats\"][category][\"count_wallet\"] = 0\n self.bitcoin[\"stats\"][category][\"count_address\"] = 0\n self.bitcoin[\"stats\"][category][\"count_received\"] = 0\n self.bitcoin[\"stats\"][category][\"count_sent\"] = 0\n self.bitcoin[\"stats\"][category][\"count_balance\"] = 0\n self.bitcoin[\"stats\"][category][\"count_txs\"] = 0\n print(\"grouping %d addresses in %s category\" % (len(self.addresses[\"category\"][category]), category))\n for address in self.addresses[\"category\"][category]:\n wallet = self.addresses[\"category\"][category][address][\"wallet\"]\n if wallet not in self.bitcoin[\"category\"][category]:\n self.bitcoin[\"category\"][category][wallet] = {\n \"addresses\": [address],\n \"addrstats\": [],\n \"received\": 0,\n \"sent\": 0,\n \"balance\": 0,\n \"txcount\": 0,\n \"lasttx\": {\n \"epoch\": None,\n \"epochhuman\": None,\n \"hash\": None,\n \"block\": None,\n \"summary\": None,\n },\n \"sparkid\": None,\n }\n else:\n self.bitcoin[\"category\"][category][wallet][\"addresses\"].append(address)\n\n for category in categories:\n print(\"updating %d wallets in %s category\" % (len(self.bitcoin[\"category\"][category]), category))\n for wallet in self.bitcoin[\"category\"][category]:\n try:\n # https://www.blockchain.com/api/blockchain_api\n stats = utils.get_http(\"https://blockchain.info/multiaddr?active=%s\" % (\"|\".join(self.bitcoin[\"category\"][category][wallet][\"addresses\"])))\n except:\n stats= None\n if stats and \"addresses\" in stats:\n self.bitcoin[\"category\"][category][wallet][\"addrstats\"] = []\n for entry in stats[\"addresses\"]:\n self.bitcoin[\"category\"][category][wallet][\"addrstats\"].append({\n \"address\": entry[\"address\"],\n \"received\": entry[\"total_received\"],\n \"sent\": entry[\"total_sent\"],\n \"balance\": entry[\"final_balance\"],\n \"txcount\": entry[\"n_tx\"],\n })\n self.bitcoin[\"category\"][category][wallet][\"received\"] += entry[\"total_received\"]\n self.bitcoin[\"category\"][category][wallet][\"sent\"] += entry[\"total_sent\"]\n self.bitcoin[\"category\"][category][wallet][\"balance\"] += entry[\"final_balance\"]\n self.bitcoin[\"category\"][category][wallet][\"txcount\"] += entry[\"n_tx\"]\n if len(stats[\"txs\"]):\n self.bitcoin[\"category\"][category][wallet][\"lasttx\"][\"epoch\"] = stats[\"txs\"][0][\"time\"]\n self.bitcoin[\"category\"][category][wallet][\"lasttx\"][\"epochhuman\"] = time.strftime(\"%d/%b/%Y @ %H:%M:%S %Z\", time.localtime(stats[\"txs\"][0][\"time\"]))\n self.bitcoin[\"category\"][category][wallet][\"lasttx\"][\"hash\"] = stats[\"txs\"][0][\"hash\"]\n self.bitcoin[\"category\"][category][wallet][\"lasttx\"][\"block\"] = stats[\"txs\"][0][\"block_height\"]\n self.bitcoin[\"category\"][category][wallet][\"lasttx\"][\"summary\"] = stats[\"txs\"][0][\"result\"]\n\n self.bitcoin[\"category\"][category][wallet][\"sparkid\"] = self.sparkify(\"%x%x%x%x%x\" % (\n int(len(self.bitcoin[\"category\"][category][wallet][\"addresses\"]) % 15),\n int(self.bitcoin[\"category\"][category][wallet][\"txcount\"] % 15),\n int(self.bitcoin[\"category\"][category][wallet][\"received\"] % 15),\n int(self.bitcoin[\"category\"][category][wallet][\"sent\"] % 15),\n int(self.bitcoin[\"category\"][category][wallet][\"balance\"] % 15),\n ), skiphashing=True)\n\n self.bitcoin[\"stats\"][category][\"count_wallet\"] = len(self.bitcoin[\"category\"][category])\n self.bitcoin[\"stats\"][category][\"count_address\"] += len(self.bitcoin[\"category\"][category][wallet][\"addresses\"])\n self.bitcoin[\"stats\"][category][\"count_received\"] += self.bitcoin[\"category\"][category][wallet][\"received\"]\n self.bitcoin[\"stats\"][category][\"count_sent\"] += self.bitcoin[\"category\"][category][wallet][\"sent\"]\n self.bitcoin[\"stats\"][category][\"count_balance\"] += self.bitcoin[\"category\"][category][wallet][\"balance\"]\n self.bitcoin[\"stats\"][category][\"count_txs\"] += self.bitcoin[\"category\"][category][wallet][\"txcount\"]\n\n self.bitcoin[\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n utils.save_json(self.bitcoin, self.statsfilepath)\n\n self.bitcoin[\"stats\"][\"count_wallet\"] = self.bitcoin[\"stats\"][\"donation\"][\"count_wallet\"] + self.bitcoin[\"stats\"][\"popular\"][\"count_wallet\"] + self.bitcoin[\"stats\"][\"ransom\"][\"count_wallet\"]\n self.bitcoin[\"stats\"][\"count_address\"] = self.bitcoin[\"stats\"][\"donation\"][\"count_address\"] + self.bitcoin[\"stats\"][\"popular\"][\"count_address\"] + self.bitcoin[\"stats\"][\"ransom\"][\"count_address\"]\n self.bitcoin[\"stats\"][\"count_received\"] = self.bitcoin[\"stats\"][\"donation\"][\"count_received\"] + self.bitcoin[\"stats\"][\"popular\"][\"count_received\"] + self.bitcoin[\"stats\"][\"ransom\"][\"count_received\"]\n self.bitcoin[\"stats\"][\"count_sent\"] = self.bitcoin[\"stats\"][\"donation\"][\"count_sent\"] + self.bitcoin[\"stats\"][\"popular\"][\"count_sent\"] + self.bitcoin[\"stats\"][\"ransom\"][\"count_sent\"]\n self.bitcoin[\"stats\"][\"count_balance\"] = self.bitcoin[\"stats\"][\"donation\"][\"count_balance\"] + self.bitcoin[\"stats\"][\"popular\"][\"count_balance\"] + self.bitcoin[\"stats\"][\"ransom\"][\"count_balance\"]\n self.bitcoin[\"stats\"][\"count_txs\"] = self.bitcoin[\"stats\"][\"donation\"][\"count_txs\"] + self.bitcoin[\"stats\"][\"popular\"][\"count_txs\"] + self.bitcoin[\"stats\"][\"ransom\"][\"count_txs\"]\n\n self.bitcoin[\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n utils.save_json(self.bitcoin, self.statsfilepath)\n\n def wallet_graph(self):\n def sat2btc(sat):\n return sat/10**8\n\n def sat2size(sat):\n sizemap = {\n 1: 10,\n 10: 15,\n 100: 20,\n 1000: 25,\n 10000: 30,\n 100000: 35,\n 1000000: 40,\n 10000000: 45,\n 100000000: 50,\n }\n btc = sat2btc(sat)\n for maxbtc in sizemap:\n if btc <= maxbtc:\n return sizemap[maxbtc]\n\n grouplimits = {\n \"₿1\": {\"min\": 0, \"max\": 1},\n \"₿10\": {\"min\": 1, \"max\": 10},\n \"₿100\": {\"min\": 10, \"max\": 100},\n \"₿1k\": {\"min\": 100, \"max\": 1000},\n \"₿10k\": {\"min\": 1000, \"max\": 10000},\n \"₿100k\": {\"min\": 10000, \"max\": 100000},\n \"₿1m\": {\"min\": 100000, \"max\": 1000000},\n \"₿10m\": {\"min\": 1000000, \"max\": 10000000},\n \"₿100m\": {\"min\": 10000000, \"max\": 100000000},\n }\n\n groupingcriteria = \"received\"\n defaultnodesize = 20\n defaultfillcolor = \"#dedede\"\n rootfillcolor = \"#c3daf7\"\n edgecolor = \"#dddddd\"\n nodecolor = \"#f6f6f6\"\n categoryfillcolors = {\n \"donation\": \"#d7ecc9\",\n \"popular\": \"#fed9b5\",\n \"ransom\": \"#fbbfc5\",\n }\n\n self.bitcoin[\"graph\"] = {\n \"grouped\": {\n \"inlabel\": self.bitcoin[\"stats\"][\"count_wallet\"],\n \"outlabel\": \"💼 Wallets\",\n \"size\": defaultnodesize,\n \"edgecolor\": edgecolor,\n \"fillcolor\": rootfillcolor,\n \"tooltip\": \"\", #\"₿%.8f/₿%.8f/₿%.8f\" % (sat2btc(self.bitcoin[\"stats\"][\"count_received\"]), sat2btc(self.bitcoin[\"stats\"][\"count_sent\"]), sat2btc(self.bitcoin[\"stats\"][\"count_balance\"])),\n \"donation\": {\n \"inlabel\": None,\n \"outlabel\": \"🙏 Donation\",\n \"size\": defaultnodesize,\n \"edgecolor\": edgecolor,\n \"fillcolor\": categoryfillcolors[\"donation\"],\n \"tooltip\": None,\n \"₿1\": [],\n \"₿10\": [],\n \"₿100\": [],\n \"₿1k\": [],\n \"₿10k\": [],\n \"₿100k\": [],\n \"₿1m\": [],\n \"₿10m\": [],\n \"children\": []\n },\n \"popular\": {\n \"inlabel\": None,\n \"outlabel\": \"🔥 Popular\",\n \"size\": defaultnodesize,\n \"edgecolor\": edgecolor,\n \"fillcolor\": categoryfillcolors[\"popular\"],\n \"tooltip\": None,\n \"₿1\": [],\n \"₿10\": [],\n \"₿100\": [],\n \"₿1k\": [],\n \"₿10k\": [],\n \"₿100k\": [],\n \"₿1m\": [],\n \"₿10m\": [],\n \"children\": []\n },\n \"ransom\": {\n \"inlabel\": None,\n \"outlabel\": \"👾 Ransom\",\n \"size\": defaultnodesize,\n \"edgecolor\": edgecolor,\n \"fillcolor\": categoryfillcolors[\"ransom\"],\n \"tooltip\": None,\n \"₿1\": [],\n \"₿10\": [],\n \"₿100\": [],\n \"₿1k\": [],\n \"₿10k\": [],\n \"₿100k\": [],\n \"₿1m\": [],\n \"₿10m\": [],\n \"children\": []\n },\n \"children\": []\n }\n }\n\n for category in [\"donation\", \"popular\", \"ransom\"]:\n print(\"gathering stats for %d wallets in %s category\" % (len(self.bitcoin[\"category\"][category]), category))\n for wallet in self.bitcoin[\"category\"][category]:\n for fundgroup in grouplimits:\n if sat2btc(self.bitcoin[\"category\"][category][wallet][groupingcriteria]) > grouplimits[fundgroup][\"min\"] and sat2btc(self.bitcoin[\"category\"][category][wallet][groupingcriteria]) <= grouplimits[fundgroup][\"max\"]:\n self.bitcoin[\"graph\"][\"grouped\"][category][fundgroup].append({\n \"inlabel\": \"\",\n \"outlabel\": wallet,\n \"size\": defaultnodesize, #sat2size(self.bitcoin[\"category\"][category][wallet][groupingcriteria]),\n \"edgecolor\": edgecolor,\n \"nodecolor\": nodecolor,\n \"fillcolor\": categoryfillcolors[category] if self.bitcoin[\"category\"][category][wallet][\"balance\"] > 0 else defaultfillcolor,\n \"tooltip\": \"₿%.8f/₿%.8f/₿%.8f\" % (sat2btc(self.bitcoin[\"category\"][category][wallet][\"received\"]), sat2btc(self.bitcoin[\"category\"][category][wallet][\"sent\"]), sat2btc(self.bitcoin[\"category\"][category][wallet][\"balance\"])),\n \"lastactivity\": self.bitcoin[\"category\"][category][wallet][\"lasttx\"][\"epochhuman\"],\n \"children\": [],\n })\n print(\"grouping wallets using criteria '%s'\" % groupingcriteria)\n for fundgroup in grouplimits:\n if fundgroup in self.bitcoin[\"graph\"][\"grouped\"][category]:\n if len(self.bitcoin[\"graph\"][\"grouped\"][category][fundgroup]):\n self.bitcoin[\"graph\"][\"grouped\"][category][\"children\"].append({\n \"inlabel\": len(self.bitcoin[\"graph\"][\"grouped\"][category][fundgroup]),\n \"outlabel\": \"<=%s\" % (fundgroup),\n \"size\": defaultnodesize,\n \"edgecolor\": edgecolor,\n \"nodecolor\": nodecolor,\n \"fillcolor\": categoryfillcolors[category],\n \"tooltip\": \"\",\n \"children\": self.bitcoin[\"graph\"][\"grouped\"][category][fundgroup],\n })\n del self.bitcoin[\"graph\"][\"grouped\"][category][fundgroup]\n\n self.bitcoin[\"graph\"][\"grouped\"][\"children\"].append({\n \"inlabel\": self.bitcoin[\"stats\"][\"donation\"][\"count_wallet\"],\n \"outlabel\": \"🙏 Donation\",\n \"size\": defaultnodesize,\n \"edgecolor\": edgecolor,\n \"nodecolor\": nodecolor,\n \"fillcolor\": categoryfillcolors[\"donation\"],\n \"tooltip\": \"\", #\"₿%.8f/₿%.8f/₿%.8f\" % (sat2btc(self.bitcoin[\"stats\"][\"donation\"][\"count_received\"]), sat2btc(self.bitcoin[\"stats\"][\"donation\"][\"count_sent\"]), sat2btc(self.bitcoin[\"stats\"][\"donation\"][\"count_balance\"])),\n \"children\": self.bitcoin[\"graph\"][\"grouped\"][\"donation\"][\"children\"],\n })\n del self.bitcoin[\"graph\"][\"grouped\"][\"donation\"]\n self.bitcoin[\"graph\"][\"grouped\"][\"children\"].append({\n \"inlabel\": self.bitcoin[\"stats\"][\"popular\"][\"count_wallet\"],\n \"outlabel\": \"🔥 Popular\",\n \"size\": defaultnodesize,\n \"edgecolor\": edgecolor,\n \"nodecolor\": nodecolor,\n \"fillcolor\": categoryfillcolors[\"popular\"],\n \"tooltip\": \"\", #\"₿%.8f/₿%.8f/₿%.8f\" % (sat2btc(self.bitcoin[\"stats\"][\"popular\"][\"count_received\"]), sat2btc(self.bitcoin[\"stats\"][\"popular\"][\"count_sent\"]), sat2btc(self.bitcoin[\"stats\"][\"popular\"][\"count_balance\"])),\n \"children\": self.bitcoin[\"graph\"][\"grouped\"][\"popular\"][\"children\"],\n })\n del self.bitcoin[\"graph\"][\"grouped\"][\"popular\"]\n self.bitcoin[\"graph\"][\"grouped\"][\"children\"].append({\n \"inlabel\": self.bitcoin[\"stats\"][\"ransom\"][\"count_wallet\"],\n \"outlabel\": \"👾 Ransom\",\n \"size\": defaultnodesize,\n \"edgecolor\": edgecolor,\n \"nodecolor\": nodecolor,\n \"fillcolor\": categoryfillcolors[\"ransom\"],\n \"tooltip\": \"\", #\"₿%.8f/₿%.8f/₿%.8f\" % (sat2btc(self.bitcoin[\"stats\"][\"ransom\"][\"count_received\"]), sat2btc(self.bitcoin[\"stats\"][\"ransom\"][\"count_sent\"]), sat2btc(self.bitcoin[\"stats\"][\"ransom\"][\"count_balance\"])),\n \"children\": self.bitcoin[\"graph\"][\"grouped\"][\"ransom\"][\"children\"],\n })\n del self.bitcoin[\"graph\"][\"grouped\"][\"ransom\"]\n\n self.bitcoin[\"last_update_epoch\"] = datetime.now().timestamp(); self.bitcoin[\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n utils.save_json(self.bitcoin, self.statsfilepath)\n\n\nif __name__ == \"__main__\":\n bitcoin = Bitcoin()\n bitcoin.group_and_update()\n bitcoin.wallet_graph()\n bitcoin.get_bitnodes()\n" }, { "alpha_fraction": 0.5777748823165894, "alphanum_fraction": 0.5937376618385315, "avg_line_length": 49.11648178100586, "blob_id": "b60fe64d1e4d649491a9c053f95eab12a78048ab", "content_id": "688c89b222d6b0d425e7b0b24ee769bc1f65058b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22911, "license_type": "no_license", "max_line_length": 932, "num_lines": 455, "path": "/kalpi.py", "repo_name": "7h3rAm/kalpi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport os\nimport re\nimport time\nimport random\nimport hashlib\nimport htmlmin\nimport argparse\nimport markdown\nimport sparkline\nimport dateutil.relativedelta\nfrom datetime import datetime\nfrom jinja2 import Environment, BaseLoader, FileSystemLoader\n\nimport utils\n\n\nclass Kalpi:\n def __init__(self):\n self.datadict = {}\n\n self.datadict[\"tags\"] = {}\n self.datadict[\"posts\"] = {}\n self.datadict[\"recent_count\"] = 10\n self.basedir = \"%s/7h3rAm.github.io\" % (utils.expand_env(var=\"$PROJECTSPATH\"))\n self.outputdir = self.basedir\n self.postsdir = \"%s/_posts\" % (self.basedir)\n self.templatesdir = \"%s/_templates\" % (self.basedir)\n self.statsdir = \"%s/static/files/pages_stats\" % (self.outputdir)\n\n self.pages = {}\n self.pages[\"research\"] = \"%s/research.md\" % (self.templatesdir)\n self.pages[\"cv\"] = \"%s/cv.md\" % (self.templatesdir)\n self.pages[\"life\"] = \"%s/life.md\" % (self.templatesdir)\n self.pages[\"fitness\"] = \"%s/fitness.md\" % (self.templatesdir)\n\n self.datadict[\"pages\"] = {}\n self.datadict[\"metadata\"] = utils.load_yaml(\"%s/toolbox/bootstrap/self.yml\" % (utils.expand_env(var=\"$HOME\")))[\"metadata\"]\n self.datadict[\"fitness\"] = utils.load_yaml(\"%s/fitness.yml\" % (self.templatesdir))\n self.datadict[\"life\"] = utils.load_yaml(\"%s/life.yml\" % (self.templatesdir))\n self.datadict[\"oscp\"] = utils.load_yaml(\"%s/oscp.yml\" % (self.templatesdir))\n self.datadict[\"read\"] = utils.load_yaml(\"%s/read.yml\" % (self.templatesdir))\n self.datadict[\"startpage\"] = utils.load_yaml(\"%s/startpage.yml\" % (self.templatesdir))\n\n self.templatemapping = {\n \"index.html\": \"%s/index.html\" % (self.outputdir),\n \"archive.html\": \"%s/archive.html\" % (self.outputdir),\n \"tags.html\": \"%s/tags.html\" % (self.outputdir),\n \"stats.html\": \"%s/stats.html\" % (self.outputdir),\n\n \"cv.html\": \"%s/pages/cv.html\" % (self.outputdir),\n \"fitness.html\": \"%s/pages/fitness.html\" % (self.outputdir),\n \"life.html\": \"%s/pages/life.html\" % (self.outputdir),\n \"oscp.html\": \"%s/pages/oscp.html\" % (self.outputdir),\n \"read.html\": \"%s/pages/read.html\" % (self.outputdir),\n \"research.html\": \"%s/pages/research.html\" % (self.outputdir),\n \"satview.html\": \"%s/pages/satview.html\" % (self.outputdir),\n \"astro.html\": \"%s/pages/astro.html\" % (self.outputdir),\n \"startpage.html\": \"%s/pages/startpage.html\" % (self.outputdir),\n }\n\n self.timeformat = \"%B %-d, %Y\"\n self.timeformat = \"%Y %b %d\"\n self.stimeformat = \"%b %d\"\n self.postdateformat = \"%d/%b/%Y\"\n\n self.trimlength = 30\n self.totalsize = 0\n self.minsize = 0\n\n def join_list(self, inlist, url=\"/tags.html#\"):\n outlist = []\n for item in sorted(inlist):\n outlist.append(\"<a href=%s%s>%s</a>\" % (url, item, item))\n return \", \".join(outlist)\n\n def join_list_and(self, inlist, url=\"/tags.html#\"):\n outlist = []\n for item in sorted(inlist):\n outlist.append(\"<a href=%s%s>%s</a>\" % (url, item, item))\n set1 = \", \".join(outlist[:-2])\n set2 = \" and \".join(outlist[-2:])\n if set1:\n return \", \".join([set1, set2])\n else:\n return set2\n\n def trim_length(self, text):\n return \"\".join([text[:self.trimlength], \"...\"]) if len(text) > self.trimlength else text\n\n def preprocess_text(self, mdtext):\n return mdtext.replace('\\n```\\n', '\\n```c\\n') if \"\\n```\\n\" in mdtext else mdtext\n\n def md2html(self, mdtext):\n return markdown.markdown(mdtext, extensions=[\"fenced_code\", \"footnotes\", \"tables\"])\n\n def clean_text(self, rgx_list, text, subtext=\"\"):\n # https://stackoverflow.com/a/37192727/1079836\n new_text = text\n for rgx_match in rgx_list:\n new_text = re.sub(rgx_match, subtext, new_text)\n return new_text\n\n def remove_para(self, htmltext):\n return self.clean_text([r\"<p>\", r\"</p>\"], text=htmltext)\n\n def remove_empty_ul(self, htmltext):\n return self.clean_text([r\"</li>\\s*</ul>\\s*<ul>\\s*<li>\"], text=self.clean_text([r\"<p>\\s*</p>\"], text=htmltext), subtext=\"</li><li>\")\n\n def get_template(self, templatefile, datadict):\n env = Environment(loader=FileSystemLoader(self.templatesdir), extensions=[\"jinja2_markdown.MarkdownExtension\"], autoescape=False)\n env.trim_blocks = True\n env.lsrtip_blocks = True\n env.filters[\"md2html\"] = self.md2html\n env.filters[\"removepara\"] = self.remove_para\n env.filters[\"removeemptyul\"] = self.remove_empty_ul\n env.filters[\"joinlist\"] = self.join_list\n env.filters[\"joinlistand\"] = self.join_list_and\n env.filters[\"trimlength\"] = self.trim_length\n return env.get_template(templatefile).render(datadict=datadict)\n\n def render_template(self, templatefile, postprocess=[]):\n if templatefile in self.templatemapping:\n output = self.get_template(templatefile, datadict=self.datadict)\n output = output.replace('<div class=\"footer\"></div>', '<div class=\"footer footercenter\"><span><a href=\"https://creativecommons.org/licenses/by-sa/4.0/\" class=\"footspan\">  </a></span></div>')\n html = output\n if \"minify\" in postprocess:\n html = htmlmin.minify(output, remove_comments=True, remove_empty_space=True)\n utils.file_save(self.templatemapping[templatefile], html)\n utils.info(\"rendered '%s' (%s)\" % (utils.cyan(self.templatemapping[templatefile]), utils.blue(utils.sizeof_fmt(len(html)))))\n self.totalsize += len(output)\n self.minsize += len(html)\n else:\n utils.warn(\"could not find mapping for file '%s'\" % (utils.red(templatefile)))\n\n def render_template_string(self, templatestr):\n env = Environment(loader=BaseLoader, extensions=[\"jinja2_markdown.MarkdownExtension\"], autoescape=False)\n env.trim_blocks = True\n env.lsrtip_blocks = True\n env.filters[\"md2html\"] = self.md2html\n env.filters[\"removepara\"] = self.remove_para\n env.filters[\"removeemptyul\"] = self.remove_empty_ul\n env.filters[\"joinlist\"] = self.join_list\n env.filters[\"joinlistand\"] = self.join_list_and\n env.filters[\"trimlength\"] = self.trim_length\n return env.from_string(htmlmin.minify(templatestr, remove_comments=True, remove_empty_space=True)).render(datadict=self.datadict)\n\n def tag_cloud(self):\n colors = [\"#20b2aa\", \"#99cc99\", \"#0c9\", \"#5b92e5\", \"#ffcc66\", \"#00b7eb\", \"#69359c\", \"#fe4164\", \"#a50b5e\"]\n random.shuffle(colors)\n maxtagcount = 0\n tags, tagcloud = {}, {}\n for tag in self.datadict[\"tags\"]:\n tagcloud[tag] = None\n tags[tag] = len(self.datadict[\"tags\"][tag])\n if tags[tag] > maxtagcount:\n maxtagcount = tags[tag]\n for tag in tags:\n percent = (tags[tag]*100/maxtagcount)\n if percent <= 10:\n tagcloud[tag] = \"font-size:1.0em; color:%s; padding:20px 5px 20px 5px;\" % (colors[0])\n elif percent <= 20:\n tagcloud[tag] = \"font-size:1.5em; font-weight:bold; color:%s; padding:20px 5px 20px 5px;\" % (colors[1])\n elif percent <= 30:\n tagcloud[tag] = \"font-size:2.0em; color:%s; padding:20px 5px 20px 5px;\" % (colors[2])\n elif percent <= 40:\n tagcloud[tag] = \"font-size:2.5em; font-weight:bold; color:%s; padding:20px 5px 20px 5px;\" % (colors[3])\n elif percent <= 50:\n tagcloud[tag] = \"font-size:3.0em; color:%s; padding:20px 5px 20px 5px;\" % (colors[4])\n elif percent <= 60:\n tagcloud[tag] = \"font-size:3.5em; font-weight:bold; color:%s; padding:0px 5px 0px 5px;\" % (colors[5])\n elif percent <= 70:\n tagcloud[tag] = \"font-size:4.0em; color:%s; padding:0px 5px 0px 5px;\" % (colors[6])\n elif percent <= 80:\n tagcloud[tag] = \"font-size:4.5em; font-weight:bold; color:%s; padding:0px 5px 0px 5px;\" % (colors[7])\n elif percent <= 90:\n tagcloud[tag] = \"font-size:5.0em; color:%s; padding:0px 5px 0px 5px;\" % (colors[8])\n elif percent <= 100:\n tagcloud[tag] = \"font-size:5.5em; font-weight:bold; color:%s; padding:0px 5px 0px 5px;\" % (colors[0])\n\n keys = list(tagcloud.keys())\n random.shuffle(keys)\n tagcloud = {key: tagcloud[key] for key in keys}\n\n return tagcloud\n\n def parse(self, lines):\n date, summary, tags, content = None, None, None, None\n for idx, line in enumerate(lines):\n if line.startswith(\"date:\"):\n date = time.strptime(\"\".join(line.split(\":\")[1:]).strip(), self.postdateformat)\n if line.startswith(\"summary:\"):\n summary = \":\".join(line.split(\":\")[1:]).strip()\n summary = None if summary in [\"\", \"This is the summary for an awesome post.\"] else summary\n if line.startswith(\"tags:\"):\n tags = []\n for tag in \"\".join(line.split(\":\")[1:]).strip().split(\", \"):\n tags.append(tag.replace(\" \", \"_\"))\n if line == \"\\n\":\n content = self.md2html(\"\".join(lines[idx+1:]))\n break\n return date, summary, tags, content\n\n def sparkify(self, content, maxsize=10, unique=True, sparkmode=True):\n sparkid = hashlib.sha256(content.encode(\"utf-8\")).hexdigest()\n spark = \"\".join(sparkline.sparkify([int(x, base=16) for x in sparkid]))\n colors = [\"#007bff\", \"#00bcd4\", \"#17a2b8\", \"#20c997\", \"#2196f3\", \"#28a745\", \"#4caf50\", \"#6610f2\", \"#6c757d\", \"#6f42c1\", \"#8357ff\", \"#dc3545\", \"#e83e8c\", \"#f44336\", \"#fd7e14\", \"#ffc107\", \"#20b2aa\", \"#99cc99\", \"#0c9\", \"#5b92e5\", \"#ffcc66\", \"#00b7eb\", \"#69359c\", \"#fe4164\", \"#a50b5e\"]\n charmap = {\n \"▁\": \"◐\",\n \"▂\": \"■\",\n \"▃\": \"◩\",\n \"▄\": \"◆\",\n \"▅\": \"◢\",\n \"▆\": \"◨\",\n \"▇\": \"●\",\n \"█\": \"▲\",\n }\n if unique:\n sparkcolored = \"\".join(['<span style=\"color:%s;\">%s</span>' % (random.choice(colors), ch if sparkmode else charmap[ch]) for ch in spark[:maxsize]])\n sparkcoloredlong = \"\".join(['<span style=\"color:%s;\">%s</span>' % (random.choice(colors), ch if sparkmode else charmap[ch]) for ch in spark])\n else:\n chars = [\"▣\", \"►\", \"◐\", \"◧\", \"▤\", \"▼\", \"◑\", \"◨\", \"▥\", \"◀\", \"◒\", \"◩\", \"▦\", \"◆\", \"◕\", \"◪\", \"▧\", \"◈\", \"◢\", \"■\", \"▨\", \"◉\", \"◣\", \"▩\", \"◎\", \"◤\", \"▲\", \"●\", \"◥\"]\n sparkcolored = \"\".join(['<span style=\"color:%s;\">%s</span>' % (random.choice(colors), random.choice(chars)) for _ in range(len(sparkid[:maxsize]))])\n sparkcoloredlong = \"\".join(['<span style=\"color:%s;\">%s</span>' % (random.choice(colors), random.choice(chars)) for _ in range(len(sparkid))])\n return ('<span class=\"sparklines\">%s</span>' % (sparkcolored), '<span class=\"sparklines\">%s</span>' % (sparkcoloredlong))\n\n def get_tree(self, source):\n posts = []\n self.datadict[\"tags\"] = dict()\n for root, ds, fs in os.walk(source):\n for name in fs:\n if name[0] == \".\": continue\n if not re.match(r\"^.+\\.(md|mdown|markdown)$\", name): continue\n path = os.path.join(root, name)\n with open(path, \"r\") as f:\n title = f.readline()[:-1].strip(\"\\n..\")\n contentmd = self.preprocess_text(f.readlines())\n date, summary, tags, content = self.parse(contentmd)\n year, month, day = date[:3]\n pretty_date = time.strftime(self.postdateformat, date)\n epoch = time.mktime(date)\n url = \"/posts/%d%02d%02d_%s.html\" % (year, month, day, os.path.splitext(name)[0])\n sparkcolored, sparkcoloredlong = self.sparkify(\"\\n\".join(contentmd))\n\n post = {\n \"title\": title,\n \"epoch\": epoch,\n \"content\": content,\n \"contentmd\": contentmd,\n \"url\": url,\n \"pretty_date\": pretty_date,\n \"sdate\": time.strftime(self.stimeformat, date),\n \"date\": date,\n \"year\": year,\n \"month\": month,\n \"day\": day,\n \"tags\": tags,\n \"summary\": summary,\n \"filename\": name,\n \"sparkline\": sparkcolored,\n \"sparklinelong\": sparkcoloredlong,\n \"previous\": None,\n \"next\": None,\n }\n posts.append(post)\n for tag in tags:\n if tag not in self.datadict[\"tags\"].keys():\n self.datadict[\"tags\"][tag] = [{\n \"title\": title,\n \"sparkline\": sparkcolored,\n \"sparklinelong\": sparkcoloredlong,\n \"summary\": summary,\n \"url\": url,\n \"pretty_date\": pretty_date,\n \"year\": year,\n \"month\": month,\n \"day\": day,\n }]\n else:\n self.datadict[\"tags\"][tag].append({\n \"title\": title,\n \"sparkline\": sparkcolored,\n \"sparklinelong\": sparkcoloredlong,\n \"summary\": summary,\n \"url\": url,\n \"pretty_date\": pretty_date,\n \"year\": year,\n \"month\": month,\n \"day\": day,\n })\n return posts\n\n def gen_stats(self):\n stats = {}\n stats[\"count_posts\"] = len(self.datadict[\"posts\"])\n stats[\"count_tags\"] = len(self.datadict[\"tags\"])\n stats[\"groups\"] = {\n \"per_yyyymm\": {},\n \"per_yyyy\": {},\n \"per_tag\": {},\n }\n stats[\"duration\"] = {\n \"start_year\": 2100,\n \"end_year\": 2000,\n }\n stats[\"dates\"] = []\n\n for post in self.datadict[\"posts\"]:\n if post[\"year\"] < stats[\"duration\"][\"start_year\"]:\n stats[\"duration\"][\"start_year\"] = post[\"year\"]\n if post[\"year\"] > stats[\"duration\"][\"end_year\"]:\n stats[\"duration\"][\"end_year\"] = post[\"year\"]\n\n stats[\"dates\"].append(\"%04d%02d%02d\" % (post[\"year\"], post[\"month\"], post[\"day\"]))\n\n key = \"%04d%02d\" % (post[\"year\"], post[\"month\"])\n if key not in stats[\"groups\"][\"per_yyyymm\"]:\n stats[\"groups\"][\"per_yyyymm\"][key] = {\n \"posts\": 1,\n \"tagslist\": [],\n \"tags\": len(post[\"tags\"]),\n }\n else:\n stats[\"groups\"][\"per_yyyymm\"][key]\n stats[\"groups\"][\"per_yyyymm\"][key][\"posts\"] += 1\n stats[\"groups\"][\"per_yyyymm\"][key][\"tags\"] += len(post[\"tags\"])\n stats[\"groups\"][\"per_yyyymm\"][key][\"tagslist\"] += post[\"tags\"]\n stats[\"groups\"][\"per_yyyymm\"][key][\"tagslist\"] = list(set(stats[\"groups\"][\"per_yyyymm\"][key][\"tagslist\"]))\n\n key = \"%04d\" % (post[\"year\"])\n if key not in stats[\"groups\"][\"per_yyyy\"]:\n stats[\"groups\"][\"per_yyyy\"][key] = {\n \"posts\": 1,\n \"tagslist\": [],\n \"tags\": len(post[\"tags\"]),\n }\n else:\n stats[\"groups\"][\"per_yyyy\"][key]\n stats[\"groups\"][\"per_yyyy\"][key][\"posts\"] += 1\n stats[\"groups\"][\"per_yyyy\"][key][\"tags\"] += len(post[\"tags\"])\n stats[\"groups\"][\"per_yyyy\"][key][\"tagslist\"] += post[\"tags\"]\n stats[\"groups\"][\"per_yyyy\"][key][\"tagslist\"] = list(set(stats[\"groups\"][\"per_yyyy\"][key][\"tagslist\"]))\n\n for tag in post[\"tags\"]:\n if tag not in stats[\"groups\"][\"per_tag\"]:\n stats[\"groups\"][\"per_tag\"][tag] = {\n \"posts\": 1,\n }\n else:\n stats[\"groups\"][\"per_tag\"][tag][\"posts\"] += 1\n\n stats[\"most_used_tag\"] = max(stats[\"groups\"][\"per_tag\"].keys(), key=(lambda key: stats[\"groups\"][\"per_tag\"][key][\"posts\"]))\n stats[\"least_used_tag\"] = min(stats[\"groups\"][\"per_tag\"].keys(), key=(lambda key: stats[\"groups\"][\"per_tag\"][key][\"posts\"]))\n\n stats[\"max_posts_yyyy\"] = max(stats[\"groups\"][\"per_yyyy\"].keys(), key=(lambda key: stats[\"groups\"][\"per_yyyy\"][key][\"posts\"]))\n stats[\"min_posts_yyyy\"] = min(stats[\"groups\"][\"per_yyyy\"].keys(), key=(lambda key: stats[\"groups\"][\"per_yyyy\"][key][\"posts\"]))\n\n stats[\"max_tags_yyyy\"] = max(stats[\"groups\"][\"per_yyyy\"].keys(), key=(lambda key: len(stats[\"groups\"][\"per_yyyy\"][key][\"tagslist\"])))\n stats[\"min_tags_yyyy\"] = min(stats[\"groups\"][\"per_yyyy\"].keys(), key=(lambda key: len(stats[\"groups\"][\"per_yyyy\"][key][\"tagslist\"])))\n\n curdate = datetime.now()\n maxdate = datetime.strptime(max(stats[\"dates\"]), \"%Y%m%d\")\n mindate = datetime.strptime(min(stats[\"dates\"]), \"%Y%m%d\")\n rd1 = dateutil.relativedelta.relativedelta (maxdate, mindate)\n rd2 = dateutil.relativedelta.relativedelta (curdate, maxdate)\n rd3 = dateutil.relativedelta.relativedelta (curdate, mindate)\n\n stats[\"summary\"] = []\n stats[\"summary\"].append(\"There are a total of `%d` posts with `%d` tags, written over a period of `%dy%dm%dd` (from `%s` till `%s`)\" % (stats[\"count_posts\"], stats[\"count_tags\"], rd1.years, rd1.months, rd1.days, datetime.strftime(mindate, \"%d/%b/%Y\"), datetime.strftime(maxdate, \"%d/%b/%Y\")))\n stats[\"summary\"].append(\"From the most recent update (on `%s`), it's been `%dy%dm%dd` when the last post was published and `%dy%dm%dd` since the first post\" % (datetime.strftime(curdate, \"%d/%b/%Y\"), rd2.years, rd2.months, rd2.days, rd3.years, rd3.months, rd3.days))\n stats[\"summary\"].append(\"The year `%s` has highest number of posts with a count of `%d`, while the year `%s` has lowest number of posts with a count of `%d`\" % (stats[\"max_posts_yyyy\"], stats[\"groups\"][\"per_yyyy\"][stats[\"max_posts_yyyy\"]][\"posts\"], stats[\"min_posts_yyyy\"], stats[\"groups\"][\"per_yyyy\"][stats[\"min_posts_yyyy\"]][\"posts\"]))\n stats[\"summary\"].append(\"The year `%s` has highest number of tags with a count of `%d`, while the year `%s` has lowest number of tags with a count of `%d`\" % (stats[\"max_tags_yyyy\"], len(stats[\"groups\"][\"per_yyyy\"][stats[\"max_tags_yyyy\"]][\"tagslist\"]), stats[\"min_tags_yyyy\"], len(stats[\"groups\"][\"per_yyyy\"][stats[\"min_tags_yyyy\"]][\"tagslist\"])))\n stats[\"summary\"].append(\"The most widely used of all `%d` tags across `%d` posts is `%s` while the least used is `%s`\" % (stats[\"count_tags\"], stats[\"count_posts\"], stats[\"most_used_tag\"], stats[\"least_used_tag\"]))\n stats[\"summary\"].append(\"On an average, there are `%d` posts per tag and `%d` posts, `%d` tags per year\" % (sum([stats[\"groups\"][\"per_tag\"][x][\"posts\"] for x in stats[\"groups\"][\"per_tag\"]])/len(stats[\"groups\"][\"per_tag\"].keys()), sum([stats[\"groups\"][\"per_yyyy\"][x][\"posts\"] for x in stats[\"groups\"][\"per_yyyy\"]])/len(stats[\"groups\"][\"per_yyyy\"].keys()), sum([len(stats[\"groups\"][\"per_yyyy\"][x][\"tagslist\"]) for x in stats[\"groups\"][\"per_yyyy\"]])/len(stats[\"groups\"][\"per_yyyy\"].keys())))\n stats[\"summary\"] = [self.md2html(x).replace(\"<p>\", \"\").replace(\"</p>\", \"\") for x in stats[\"summary\"]]\n\n ppt = {tag:stats[\"groups\"][\"per_tag\"][tag][\"posts\"] for tag in stats[\"groups\"][\"per_tag\"]}\n utils.to_xkcd(ppt, \"%s/posts_per_tag.png\" % (self.statsdir), \"\")\n\n ppy = {yyyy:stats[\"groups\"][\"per_yyyy\"][yyyy][\"posts\"] for yyyy in stats[\"groups\"][\"per_yyyy\"]}\n utils.to_xkcd(ppy, \"%s/posts_per_year.png\" % (self.statsdir), \"\")\n\n tpy = {yyyy:len(stats[\"groups\"][\"per_yyyy\"][yyyy][\"tagslist\"]) for yyyy in stats[\"groups\"][\"per_yyyy\"]}\n utils.to_xkcd(tpy, \"%s/tags_per_year.png\" % (self.statsdir), \"\")\n\n return stats\n\n def make(self, args, postprocess=[]):\n # posts\n calist = [x.replace(self.basedir, \"\") for x in utils.search_files_all(\"%s/static/images/clipart\" % (self.basedir))]\n posts = sorted(self.get_tree(self.postsdir), key=lambda post: post[\"epoch\"], reverse=False)\n self.datadict[\"posts\"] = sorted(posts, key=lambda post: post[\"epoch\"], reverse=True)\n total = len(posts)\n for idx, post in enumerate(posts):\n if idx == 0:\n post[\"next\"] = {}\n post[\"next\"][\"title\"] = posts[idx+1][\"title\"]\n post[\"next\"][\"url\"] = posts[idx+1][\"url\"]\n elif idx == total-1:\n post[\"previous\"] = {}\n post[\"previous\"][\"title\"] = posts[idx-1][\"title\"]\n post[\"previous\"][\"url\"] = posts[idx-1][\"url\"]\n else:\n post[\"previous\"] = {}\n post[\"previous\"][\"title\"] = posts[idx-1][\"title\"]\n post[\"previous\"][\"url\"] = posts[idx-1][\"url\"]\n post[\"next\"] = {}\n post[\"next\"][\"title\"] = posts[idx+1][\"title\"]\n post[\"next\"][\"url\"] = posts[idx+1][\"url\"]\n filename = \"%s%s\" % (self.outputdir, post[\"url\"])\n output = self.get_template(\"post.html\", datadict={\"metadata\": self.datadict[\"metadata\"], \"post\": post, \"tags\": self.datadict[\"tags\"]})\n output = output.replace('<h1>', '<h1 class=\"h1 collapsible\" onclick=\"toggle(this);\">').replace('<h2>', '<hr><h2 class=\"h2 collapsible\" onclick=\"toggle(this);\">').replace('<h3>', '<h3 class=\"h3 collapsible\" onclick=\"toggle(this);\">').replace('<h4>', '<h4 class=\"h4 collapsible\" onclick=\"toggle(this);\">').replace('<h5>', '<h5 class=\"h5 collapsible\" onclick=\"toggle(this);\">').replace('<h6>', '<h6 class=\"h6 collapsible\" onclick=\"toggle(this);\">').replace('<ul>', '<ul class=\"nested active\">').replace('<ol>', '<ol class=\"nested active\">').replace('<p>', '<p class=\"nested active\">').replace('<pre><code>', '<pre class=\"nested active\"><code>').replace('<pre><code class=\"','<pre class=\"nested active\"><code class=\"').replace('<p class=\"nested active\"><a href=\"/posts/', '<p><a href=\"/posts/').replace('<p class=\"nested active\">📅 published on ', '<p>📅 published on ').replace('<p class=\"nested active\">🔖 tagged ', '<p>🔖 tagged ')\n output = output.replace('](https://7h3ram.github.io/posts/', '](/posts/').replace('href=\"https://7h3ram.github.io/posts/', 'href=\"/posts/')\n #output = output.replace('BG_CLIPART_STYLE_HERE', 'class=\"bgclipart_sq\" style=\"background-image: url(%s);\"' % (random.choice(calist)))\n html = htmlmin.minify(output, remove_comments=True, remove_empty_space=True) if \"minify\" in postprocess else output\n utils.file_save(filename, html)\n utils.info(\"rendered '%s' (%s)\" % (utils.magenta(filename), utils.blue(utils.sizeof_fmt(len(html)))))\n self.totalsize += len(output)\n self.minsize += len(html)\n\n # pages\n self.render_template(\"cv.html\", postprocess=postprocess)\n self.render_template(\"fitness.html\", postprocess=postprocess)\n self.render_template(\"life.html\", postprocess=postprocess)\n self.render_template(\"read.html\", postprocess=postprocess)\n self.render_template(\"oscp.html\", postprocess=postprocess)\n self.render_template(\"research.html\", postprocess=postprocess)\n self.render_template(\"satview.html\", postprocess=postprocess)\n #self.render_template(\"astro.html\", postprocess=postprocess)\n self.render_template(\"startpage.html\", postprocess=postprocess)\n\n # default\n self.datadict[\"stats\"] = self.gen_stats()\n self.datadict[\"tagcloud\"] = self.tag_cloud()\n self.render_template(\"index.html\", postprocess=postprocess)\n self.render_template(\"archive.html\", postprocess=postprocess)\n self.render_template(\"tags.html\", postprocess=postprocess)\n self.render_template(\"stats.html\", postprocess=postprocess)\n\n utils.info(\"size: total:%s (%d), minified:%s (%d), delta:%s (%d)\" % (\n utils.sizeof_fmt(self.totalsize),\n self.totalsize,\n utils.sizeof_fmt(self.minsize),\n self.minsize,\n utils.sizeof_fmt(self.totalsize-self.minsize),\n self.totalsize-self.minsize\n ))\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"%s (v%s)\" % (utils.blue_bold(\"kalpi\"), utils.green_bold(\"0.1\")))\n args = parser.parse_args()\n\n klp = Kalpi()\n klp.make(args)\n" }, { "alpha_fraction": 0.6305555701255798, "alphanum_fraction": 0.675000011920929, "avg_line_length": 50.42856979370117, "blob_id": "47ad5fe830a7d8751a96a8677fe3e65ce4b30e57", "content_id": "d0357580b31a3b88093c2b0f088c3805a0b569b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 360, "license_type": "no_license", "max_line_length": 138, "num_lines": 7, "path": "/misc/bg.sh", "repo_name": "7h3rAm/kalpi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nblur=$(shuf -i 1-3 -n 1)\nwhite=$(shuf -i 44-48 -n 1)\nsize=\"900x100\"\necho \"convert -size ${size} xc:white +noise random -blur 0x${blur} -white-threshold ${white}% -gravity center result_${blur}_${white}.png\"\nconvert -size ${size} xc:white +noise random -blur 0x${blur} -white-threshold ${white}% -gravity center result_${blur}_${white}.png\n" }, { "alpha_fraction": 0.5564102530479431, "alphanum_fraction": 0.5628204941749573, "avg_line_length": 36.14285659790039, "blob_id": "9a49006fbcae2c5eec53641fba3ac115ad947120", "content_id": "a9de61951701cd74bb007e47ffe5204adff441df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 952, "license_type": "no_license", "max_line_length": 129, "num_lines": 21, "path": "/bitcoin.sh", "repo_name": "7h3rAm/kalpi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env zsh\n\nsource $HOME/.zshrc\n\ndiscord.sh \"[`basename $0`] daily sync started\"\n\npython3 ${PROJECTSPATH}/kalpi/bitcoin.py\n\nmessages=$(cat $HOME/toolbox/bootstrap/commit_messages.txt)\nnum_messages=$(echo \"$messages\" | wc -l)\nrandom_index=$[RANDOM % num_messages + 1]\nmsg=$(echo \"$messages\" | head -$random_index | tail -1)\nemojis=( ⏳ ♻️ ⚗️ ⚡ ✅ ✨ ⬆️ ⬇️ ⭐ 🍎 🍒 🎉 🎨 🎵 🎶 🏁 🐎 🐗 🐛 🐞 🐧 🐳 🐻 👌 👍 👏 👕 👷 👽 💚 💡 💥 💪 💫 📅 📇 📍 📖 📚 📝 📦 📺 🔒 🔖 🔥 🔧 🔨 🗑️ 😆 😈 🙏 🚀 🚑 🚚 🚧 🚨 🤖 )\nrand=$[$RANDOM % ${#emojis[@]}]\nemj=$(echo ${emojis[$rand]})\n\ncd ${PROJECTSPATH}/datastore && git status && git add . && git commit -m \"${emj} ${msg}\" && git push -u\n\necho -en \"bitcoin - last_update: \" ; cat ${PROJECTSPATH}/datastore/bitcoin.json | jq '.last_update'\n\ndiscord.sh \"[`basename $0`] daily sync completed\"\n" }, { "alpha_fraction": 0.5813559889793396, "alphanum_fraction": 0.590337336063385, "avg_line_length": 58.79487228393555, "blob_id": "39d803ea9b59dc42ff4e1b098a50518223402029", "content_id": "dd6a7da0423a74a04bf38247d734511987f8f657", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 42024, "license_type": "no_license", "max_line_length": 474, "num_lines": 702, "path": "/astro.py", "repo_name": "7h3rAm/kalpi", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom datetime import datetime, timezone\nfrom pprint import pprint\nimport time\n\nimport utils\n\n\nclass Astro:\n def __init__(self):\n self.apikey = utils.expand_env(var=\"$NASAKEY\")\n\n self.datastore_url = \"https://raw.githubusercontent.com/7h3rAm/datastore/master\"\n self.datastore_path = \"%s/datastore\" % (utils.expand_env(var=\"$PROJECTSPATH\"))\n self.datafile_path = \"%s/datastore/astro.json\" % (utils.expand_env(var=\"$PROJECTSPATH\"))\n self.downloads = {}\n self.data = {\n \"last_update\": None,\n \"apod\": None,\n \"neo\": None,\n \"earthevents\": None,\n \"satview\": None,\n \"spacex\": None,\n }\n self.category_map = {\n \"Drought\": {\n \"url\": \"https://eonet.sci.gsfc.nasa.gov/api/v3/categories/drought\",\n \"emoji\": \"💧\",\n },\n \"Dust and Haze\": {\n \"url\": \"https://eonet.sci.gsfc.nasa.gov/api/v3/categories/dustHaze\",\n \"emoji\": \"🌫️\",\n },\n \"Earthquakes\": {\n \"url\": \"https://eonet.sci.gsfc.nasa.gov/api/v3/categories/earthquakes\",\n \"emoji\": \"🌐\",\n },\n \"Earthquake\": {\n \"url\": \"https://earthquake.usgs.gov/earthquakes/\",\n \"emoji\": \"🔴\",\n },\n \"Floods\": {\n \"url\": \"https://eonet.sci.gsfc.nasa.gov/api/v3/categories/floods\",\n \"emoji\": \"🌊\",\n },\n \"Landslides\": {\n \"url\": \"https://eonet.sci.gsfc.nasa.gov/api/v3/categories/landslides\",\n \"emoji\": \"⛰️\",\n },\n \"Manmade\": {\n \"url\": \"https://eonet.sci.gsfc.nasa.gov/api/v3/categories/manmade\",\n \"emoji\": \"🧍\",\n },\n \"Sea and Lake Ice\": {\n \"url\": \"https://eonet.sci.gsfc.nasa.gov/api/v3/categories/seaLakeIce\",\n \"emoji\": \"🧊\",\n },\n \"Severe Storms\": {\n \"url\": \"https://eonet.sci.gsfc.nasa.gov/api/v3/categories/severeStorms\",\n \"emoji\": \"🌀\",\n },\n \"Snow\": {\n \"url\": \"https://eonet.sci.gsfc.nasa.gov/api/v3/categories/snow\",\n \"emoji\": \"🌨️\",\n },\n \"Temperature Extremes\": {\n \"url\": \"https://eonet.sci.gsfc.nasa.gov/api/v3/categories/tempExtremes\",\n \"emoji\": \"🌡️\",\n },\n \"Volcanoes\": {\n \"url\": \"https://eonet.sci.gsfc.nasa.gov/api/v3/categories/volcanoes\",\n \"emoji\": \"🌋\",\n },\n \"Water Color\": {\n \"url\": \"https://eonet.sci.gsfc.nasa.gov/api/v3/categories/waterColor\",\n \"emoji\": \"⛲\",\n },\n \"Wildfires\": {\n \"url\": \"https://eonet.sci.gsfc.nasa.gov/api/v3/categories/wildfires\",\n \"emoji\": \"🔥\",\n }\n }\n\n def apod(self):\n self.data[\"apod\"] = {\n \"todayurl\": \"https://apod.nasa.gov/apod/astropix.html\",\n \"archiveurl\": \"https://apod.nasa.gov/apod/archivepix.html\",\n }\n apodjson = utils.download_json(\"https://api.nasa.gov/planetary/apod?api_key=%s\" % (self.apikey))\n if apodjson:\n self.data[\"apod\"][\"title\"] = \"%s (%s)\" % (apodjson[\"title\"], datetime.strptime(apodjson[\"date\"], '%Y-%m-%d').astimezone(tz=None).strftime(\"%d/%b/%Y %Z\"))\n self.data[\"apod\"][\"source\"] = apodjson[\"url\"]\n self.data[\"apod\"][\"datastore\"] = \"%s/apod.jpg\" % (self.datastore_url)\n self.downloads[self.data[\"apod\"][\"source\"]] = \"%s/apod.jpg\" % (self.datastore_path)\n utils.download(self.data[\"apod\"][\"source\"], self.downloads[self.data[\"apod\"][\"source\"]])\n self.data[\"apod\"][\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n\n def neo(self):\n self.data[\"neo\"] = {\n \"date\": None,\n \"objects\": [],\n }\n neojson = utils.download_json(\"https://api.nasa.gov/neo/rest/v1/feed/today?detailed=true&api_key=%s\" % (self.apikey))\n datekey = list(neojson[\"near_earth_objects\"].keys())[0]\n self.data[\"neo\"][\"date\"] = datetime.strptime(datekey, \"%Y-%m-%d\").astimezone(tz=None).strftime(\"%d/%b/%Y %Z\")\n for neo in neojson[\"near_earth_objects\"][datekey]:\n self.data[\"neo\"][\"objects\"].append({\n \"cat\": datetime.strptime(neo[\"close_approach_data\"][0][\"close_approach_date_full\"], \"%Y-%b-%d %H:%M\").strftime(\"%d/%b/%Y @ %H:%M:%S %Z\"),\n \"diameter\": \"%s-%s miles\" % (\"{:,.2f}\".format(float(neo[\"estimated_diameter\"][\"miles\"][\"estimated_diameter_min\"])), \"{:,.2f}\".format(float(neo[\"estimated_diameter\"][\"miles\"][\"estimated_diameter_max\"]))),\n \"distance\": \"%s miles\" % (\"{:,.2f}\".format(float(neo[\"close_approach_data\"][0][\"miss_distance\"][\"miles\"]))),\n \"velocity\": \"%s mph\" % (\"{:,.2f}\".format(float(neo[\"close_approach_data\"][0][\"relative_velocity\"][\"miles_per_hour\"]))),\n \"hazardous\": neo[\"is_potentially_hazardous_asteroid\"],\n \"name\": \"Asteroid %s\" % (neo[\"name\"]),\n \"url\": neo[\"nasa_jpl_url\"],\n })\n self.data[\"neo\"][\"title\"] = \"%d objects making close approach (%s)\" % (len(self.data[\"neo\"][\"objects\"]), self.data[\"neo\"][\"date\"])\n self.data[\"neo\"][\"objects\"] = sorted(self.data[\"neo\"][\"objects\"], key=lambda k: k[\"name\"])\n self.data[\"neo\"][\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n\n def earthevents(self):\n self.data[\"earthevents\"] = {\n \"date\": datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y %Z\"),\n \"events\": [],\n }\n eonetjson = utils.download_json(\"https://eonet.gsfc.nasa.gov/api/v3/events?status=open&days=30\")\n usgseqjson = utils.download_json(\"https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson\")\n self.data[\"earthevents\"][\"mapdata\"] = {\n \"Drought\": [],\n \"Dust and Haze\": [],\n \"Earthquakes\": [],\n \"Floods\": [],\n \"Landslides\": [],\n \"Manmade\": [],\n \"Sea and Lake Ice\": [],\n \"Severe Storms\": [],\n \"Snow\": [],\n \"Temperature Extremes\": [],\n \"Volcanoes\": [],\n \"Water Color\": [],\n \"Wildfires\": [],\n }\n for event in eonetjson[\"events\"]:\n self.data[\"earthevents\"][\"events\"].append({\n \"eid\": event[\"id\"],\n \"name\": event[\"title\"],\n \"url\": event[\"link\"],\n \"location\": \"https://www.google.com/maps/dir/%s/@%s,%s,3z\" % (\"/\".join([\",\".join([str(x[\"coordinates\"][1]), str(x[\"coordinates\"][0])]) for x in event[\"geometry\"]]), event[\"geometry\"][0][\"coordinates\"][1], event[\"geometry\"][0][\"coordinates\"][0]),\n \"category\": [self.category_map[x[\"title\"]] for x in event[\"categories\"]],\n \"source\": [{\"url\": x[\"url\"], \"sid\": x[\"id\"]} for x in event[\"sources\"]],\n })\n\n for cat in event[\"categories\"]:\n\n if cat[\"title\"] == \"Drought\":\n for coord in event[\"geometry\"]:\n self.data[\"earthevents\"][\"mapdata\"][\"Drought\"].append(['<a href=\"http://maps.google.com/maps?q=%s,%s\"><b>%s</b></a><br/><b>Category</b>: %s<br/><b>Source</b>: %s' % (coord[\"coordinates\"][1], coord[\"coordinates\"][0], event[\"title\"], \", \".join(list(sorted([x[\"title\"] for x in event[\"categories\"]]))), \", \".join(list(sorted(['<a href=\"%s\">%s</a>' % (x[\"url\"], x[\"id\"]) for x in event[\"sources\"]])))), coord[\"coordinates\"][1], coord[\"coordinates\"][0]])\n\n if cat[\"title\"] == \"Dust and Haze\":\n for coord in event[\"geometry\"]:\n self.data[\"earthevents\"][\"mapdata\"][\"Dust and Haze\"].append(['<a href=\"http://maps.google.com/maps?q=%s,%s\"><b>%s</b></a><br/><b>Category</b>: %s<br/><b>Source</b>: %s' % (coord[\"coordinates\"][1], coord[\"coordinates\"][0], event[\"title\"], \", \".join(list(sorted([x[\"title\"] for x in event[\"categories\"]]))), \", \".join(list(sorted(['<a href=\"%s\">%s</a>' % (x[\"url\"], x[\"id\"]) for x in event[\"sources\"]])))), coord[\"coordinates\"][1], coord[\"coordinates\"][0]])\n\n if cat[\"title\"] == \"Earthquakes\":\n for coord in event[\"geometry\"]:\n self.data[\"earthevents\"][\"mapdata\"][\"Earthquakes\"].append(['<a href=\"http://maps.google.com/maps?q=%s,%s\"><b>%s</b></a><br/><b>Category</b>: %s<br/><b>Source</b>: %s' % (coord[\"coordinates\"][1], coord[\"coordinates\"][0], event[\"title\"], \", \".join(list(sorted([x[\"title\"] for x in event[\"categories\"]]))), \", \".join(list(sorted(['<a href=\"%s\">%s</a>' % (x[\"url\"], x[\"id\"]) for x in event[\"sources\"]])))), coord[\"coordinates\"][1], coord[\"coordinates\"][0]])\n\n if cat[\"title\"] == \"Floods\":\n for coord in event[\"geometry\"]:\n self.data[\"earthevents\"][\"mapdata\"][\"Floods\"].append(['<a href=\"http://maps.google.com/maps?q=%s,%s\"><b>%s</b></a><br/><b>Category</b>: %s<br/><b>Source</b>: %s' % (coord[\"coordinates\"][1], coord[\"coordinates\"][0], event[\"title\"], \", \".join(list(sorted([x[\"title\"] for x in event[\"categories\"]]))), \", \".join(list(sorted(['<a href=\"%s\">%s</a>' % (x[\"url\"], x[\"id\"]) for x in event[\"sources\"]])))), coord[\"coordinates\"][1], coord[\"coordinates\"][0]])\n\n if cat[\"title\"] == \"Landslides\":\n for coord in event[\"geometry\"]:\n self.data[\"earthevents\"][\"mapdata\"][\"Landslides\"].append(['<a href=\"http://maps.google.com/maps?q=%s,%s\"><b>%s</b></a><br/><b>Category</b>: %s<br/><b>Source</b>: %s' % (coord[\"coordinates\"][1], coord[\"coordinates\"][0], event[\"title\"], \", \".join(list(sorted([x[\"title\"] for x in event[\"categories\"]]))), \", \".join(list(sorted(['<a href=\"%s\">%s</a>' % (x[\"url\"], x[\"id\"]) for x in event[\"sources\"]])))), coord[\"coordinates\"][1], coord[\"coordinates\"][0]])\n\n if cat[\"title\"] == \"Manmade\":\n for coord in event[\"geometry\"]:\n self.data[\"earthevents\"][\"mapdata\"][\"Manmade\"].append(['<a href=\"http://maps.google.com/maps?q=%s,%s\"><b>%s</b></a><br/><b>Category</b>: %s<br/><b>Source</b>: %s' % (coord[\"coordinates\"][1], coord[\"coordinates\"][0], event[\"title\"], \", \".join(list(sorted([x[\"title\"] for x in event[\"categories\"]]))), \", \".join(list(sorted(['<a href=\"%s\">%s</a>' % (x[\"url\"], x[\"id\"]) for x in event[\"sources\"]])))), coord[\"coordinates\"][1], coord[\"coordinates\"][0]])\n\n if cat[\"title\"] == \"Sea and Lake Ice\":\n for coord in event[\"geometry\"]:\n self.data[\"earthevents\"][\"mapdata\"][\"Sea and Lake Ice\"].append(['<a href=\"http://maps.google.com/maps?q=%s,%s\"><b>%s</b></a><br/><b>Category</b>: %s<br/><b>Source</b>: %s' % (coord[\"coordinates\"][1], coord[\"coordinates\"][0], event[\"title\"], \", \".join(list(sorted([x[\"title\"] for x in event[\"categories\"]]))), \", \".join(list(sorted(['<a href=\"%s\">%s</a>' % (x[\"url\"], x[\"id\"]) for x in event[\"sources\"]])))), coord[\"coordinates\"][1], coord[\"coordinates\"][0]])\n\n if cat[\"title\"] == \"Severe Storms\":\n for coord in event[\"geometry\"]:\n self.data[\"earthevents\"][\"mapdata\"][\"Severe Storms\"].append(['<a href=\"http://maps.google.com/maps?q=%s,%s\"><b>%s</b></a><br/><b>Category</b>: %s<br/><b>Source</b>: %s' % (coord[\"coordinates\"][1], coord[\"coordinates\"][0], event[\"title\"], \", \".join(list(sorted([x[\"title\"] for x in event[\"categories\"]]))), \", \".join(list(sorted(['<a href=\"%s\">%s</a>' % (x[\"url\"], x[\"id\"]) for x in event[\"sources\"]])))), coord[\"coordinates\"][1], coord[\"coordinates\"][0]])\n\n if cat[\"title\"] == \"Snow\":\n for coord in event[\"geometry\"]:\n self.data[\"earthevents\"][\"mapdata\"][\"Snow\"].append(['<a href=\"http://maps.google.com/maps?q=%s,%s\"><b>%s</b></a><br/><b>Category</b>: %s<br/><b>Source</b>: %s' % (coord[\"coordinates\"][1], coord[\"coordinates\"][0], event[\"title\"], \", \".join(list(sorted([x[\"title\"] for x in event[\"categories\"]]))), \", \".join(list(sorted(['<a href=\"%s\">%s</a>' % (x[\"url\"], x[\"id\"]) for x in event[\"sources\"]])))), coord[\"coordinates\"][1], coord[\"coordinates\"][0]])\n\n if cat[\"title\"] == \"Temperature Extremes\":\n for coord in event[\"geometry\"]:\n self.data[\"earthevents\"][\"mapdata\"][\"Temperature Extremes\"].append(['<a href=\"http://maps.google.com/maps?q=%s,%s\"><b>%s</b></a><br/><b>Category</b>: %s<br/><b>Source</b>: %s' % (coord[\"coordinates\"][1], coord[\"coordinates\"][0], event[\"title\"], \", \".join(list(sorted([x[\"title\"] for x in event[\"categories\"]]))), \", \".join(list(sorted(['<a href=\"%s\">%s</a>' % (x[\"url\"], x[\"id\"]) for x in event[\"sources\"]])))), coord[\"coordinates\"][1], coord[\"coordinates\"][0]])\n\n if cat[\"title\"] == \"Volcanoes\":\n for coord in event[\"geometry\"]:\n self.data[\"earthevents\"][\"mapdata\"][\"Volcanoes\"].append(['<a href=\"http://maps.google.com/maps?q=%s,%s\"><b>%s</b></a><br/><b>Category</b>: %s<br/><b>Source</b>: %s' % (coord[\"coordinates\"][1], coord[\"coordinates\"][0], event[\"title\"], \", \".join(list(sorted([x[\"title\"] for x in event[\"categories\"]]))), \", \".join(list(sorted(['<a href=\"%s\">%s</a>' % (x[\"url\"], x[\"id\"]) for x in event[\"sources\"]])))), coord[\"coordinates\"][1], coord[\"coordinates\"][0]])\n\n if cat[\"title\"] == \"Water Color\":\n for coord in event[\"geometry\"]:\n self.data[\"earthevents\"][\"mapdata\"][\"Water Color\"].append(['<a href=\"http://maps.google.com/maps?q=%s,%s\"><b>%s</b></a><br/><b>Category</b>: %s<br/><b>Source</b>: %s' % (coord[\"coordinates\"][1], coord[\"coordinates\"][0], event[\"title\"], \", \".join(list(sorted([x[\"title\"] for x in event[\"categories\"]]))), \", \".join(list(sorted(['<a href=\"%s\">%s</a>' % (x[\"url\"], x[\"id\"]) for x in event[\"sources\"]])))), coord[\"coordinates\"][1], coord[\"coordinates\"][0]])\n\n if cat[\"title\"] == \"Wildfires\":\n for coord in event[\"geometry\"]:\n self.data[\"earthevents\"][\"mapdata\"][\"Wildfires\"].append(['<a href=\"http://maps.google.com/maps?q=%s,%s\"><b>%s</b></a><br/><b>Category</b>: %s<br/><b>Source</b>: %s' % (coord[\"coordinates\"][1], coord[\"coordinates\"][0], event[\"title\"], \", \".join(list(sorted([x[\"title\"] for x in event[\"categories\"]]))), \", \".join(list(sorted(['<a href=\"%s\">%s</a>' % (x[\"url\"], x[\"id\"]) for x in event[\"sources\"]])))), coord[\"coordinates\"][1], coord[\"coordinates\"][0]])\n\n for event in usgseqjson[\"features\"]:\n if event[\"properties\"][\"type\"] == \"earthquake\" and event[\"properties\"][\"mag\"] >= 4:\n self.data[\"earthevents\"][\"events\"].append({\n \"eid\": event[\"id\"],\n \"name\": event[\"properties\"][\"title\"],\n \"url\": event[\"properties\"][\"url\"],\n \"location\": \"http://maps.google.com/maps?q=%s,%s\" % (event[\"geometry\"][\"coordinates\"][1], event[\"geometry\"][\"coordinates\"][0]),\n \"category\": [self.category_map[event[\"properties\"][\"type\"].title()]],\n \"source\": [{\"url\": \"https://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php\", \"sid\": \"USGS\"}],\n })\n self.data[\"earthevents\"][\"mapdata\"][\"Earthquakes\"].append([\n '<a href=\"http://maps.google.com/maps?q=%s,%s\"><b>%s</b></a><br/>Category: %s<br/>Source: <a href=\"%s\">USGS</a>' % (\n event[\"geometry\"][\"coordinates\"][1],\n event[\"geometry\"][\"coordinates\"][0],\n event[\"properties\"][\"title\"],\n event[\"properties\"][\"type\"].title(),\n event[\"properties\"][\"url\"],\n ),\n event[\"geometry\"][\"coordinates\"][1],\n event[\"geometry\"][\"coordinates\"][0],\n ])\n\n self.data[\"earthevents\"][\"title\"] = \"%d events (%s)\" % (len(self.data[\"earthevents\"][\"events\"]), self.data[\"earthevents\"][\"date\"])\n self.data[\"earthevents\"][\"events\"] = sorted(self.data[\"earthevents\"][\"events\"], key=lambda k: k[\"name\"])\n self.data[\"earthevents\"][\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n\n def spaceppl(self):\n self.data[\"spaceppl\"] = {\n \"title\": None,\n \"people\": [],\n }\n spaceppljson = utils.download_json(\"http://api.open-notify.org/astros.json\")\n for ppl in spaceppljson[\"people\"]:\n self.data[\"spaceppl\"][\"people\"].append({\n \"name\": ppl[\"name\"],\n \"url\": \"https://www.google.com/search?q=Astronaut+%s\" % (ppl[\"name\"].replace(\" \", \"+\")),\n \"spacecraft\": ppl[\"craft\"],\n })\n self.data[\"spaceppl\"][\"title\"] = \"%d people in space (%s)\" % (len(self.data[\"spaceppl\"][\"people\"]), datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y %Z\"))\n self.data[\"spaceppl\"][\"people\"] = sorted(self.data[\"spaceppl\"][\"people\"], key=lambda k: k[\"name\"])\n self.data[\"spaceppl\"][\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n\n def spacex(self):\n self.data[\"spacex\"][\"capsules\"] = []\n capsulesjson = utils.download_json(\"https://api.spacexdata.com/v4/capsules\")\n for capsule in capsulesjson:\n self.data[\"spacex\"][\"capsules\"].append({\n \"name\": \"(%s) %s\" % (capsule[\"serial\"], capsule[\"type\"]),\n \"status\": capsule[\"status\"] if capsule[\"status\"] else \"\",\n \"status_emoji\": utils.to_emoji(capsule[\"status\"]) if capsule[\"status\"] else \"\",\n \"launches\": len(capsule[\"launches\"]) if capsule[\"launches\"] else 0,\n \"reuse_count\": capsule[\"reuse_count\"] if capsule[\"reuse_count\"] else 0,\n \"water_landings\": capsule[\"water_landings\"] if capsule[\"water_landings\"] else 0,\n \"land_landings\": capsule[\"land_landings\"] if capsule[\"land_landings\"] else 0,\n \"last_update\": capsule[\"last_update\"] if capsule[\"last_update\"] else \"Location and status unknown\",\n })\n self.data[\"spacex\"][\"capsules\"] = sorted(self.data[\"spacex\"][\"capsules\"], key=lambda k: k[\"name\"])\n\n companyjson = utils.download_json(\"https://api.spacexdata.com/v4/company\")\n self.data[\"spacex\"][\"company\"] = {\n \"name\": companyjson[\"name\"],\n \"url\": companyjson[\"links\"][\"website\"],\n \"employees\": companyjson[\"employees\"],\n \"vehicles\": companyjson[\"vehicles\"],\n \"launch_sites\": companyjson[\"launch_sites\"],\n \"test_sites\": companyjson[\"test_sites\"],\n \"valuation\": companyjson[\"valuation\"],\n \"valuation_human\": utils.currency_human(companyjson[\"valuation\"]),\n \"summary\": companyjson[\"summary\"],\n }\n\n # cores\n self.data[\"spacex\"][\"cores\"] = []\n coresjson = utils.download_json(\"https://api.spacexdata.com/v4/cores\")\n for core in coresjson:\n self.data[\"spacex\"][\"cores\"].append({\n \"name\": core[\"serial\"],\n \"status\": core[\"status\"] if core[\"status\"] else \"\",\n \"status_emoji\": utils.to_emoji(core[\"status\"]) if core[\"status\"] else \"\",\n \"last_update\": core[\"last_update\"] if core[\"last_update\"] else \"\",\n \"launches\": len(core[\"launches\"]) if core[\"launches\"] else 0,\n \"rtls_attempts\": core[\"rtls_attempts\"] if core[\"rtls_attempts\"] else 0,\n \"rtls_landings\": core[\"rtls_landings\"] if core[\"rtls_landings\"] else 0,\n \"asds_attempts\": core[\"asds_attempts\"] if core[\"asds_attempts\"] else 0,\n \"asds_landings\": core[\"asds_landings\"] if core[\"asds_landings\"] else 0,\n \"reuse_count\": core[\"reuse_count\"] if core[\"reuse_count\"] else 0,\n })\n self.data[\"spacex\"][\"cores\"] = sorted(self.data[\"spacex\"][\"cores\"], key=lambda k: k[\"name\"])\n\n # crew\n self.data[\"spacex\"][\"crew\"] = []\n crewjson = utils.download_json(\"https://api.spacexdata.com/v4/crew\")\n for crew in crewjson:\n self.data[\"spacex\"][\"crew\"].append({\n \"name\": crew[\"name\"],\n \"agency\": crew[\"agency\"] if crew[\"agency\"] else \"\",\n \"url\": crew[\"wikipedia\"] if crew[\"wikipedia\"] else \"\",\n \"launches\": len(crew[\"launches\"]) if crew[\"launches\"] else 0,\n \"status\": crew[\"status\"] if crew[\"status\"] else \"\",\n \"status_emoji\": utils.to_emoji(crew[\"status\"]) if crew[\"status\"] else \"\",\n })\n self.data[\"spacex\"][\"crew\"] = sorted(self.data[\"spacex\"][\"crew\"], key=lambda k: k[\"name\"])\n\n # dragons\n self.data[\"spacex\"][\"dragons\"] = []\n dragonsjson = utils.download_json(\"https://api.spacexdata.com/v4/dragons\")\n for dragon in dragonsjson:\n self.data[\"spacex\"][\"dragons\"].append({\n \"name\": dragon[\"name\"],\n \"description\": dragon[\"description\"],\n \"first_flight\": datetime.strptime(dragon[\"first_flight\"], \"%Y-%m-%d\").astimezone(tz=None).strftime(\"%d/%b/%Y %Z\"),\n \"type\": dragon[\"type\"],\n \"type_emoji\": utils.to_emoji(dragon[\"type\"]),\n \"active\": dragon[\"active\"],\n \"status_emoji\": utils.to_emoji(\"active\" if dragon[\"active\"] else \"retired\"),\n \"crew_capacity\": dragon[\"crew_capacity\"],\n \"dry_mass\": \"%s lbs\" % (\"{:,.2f}\".format(float(dragon[\"dry_mass_lb\"]))),\n \"url\": dragon[\"wikipedia\"],\n })\n self.data[\"spacex\"][\"dragons\"] = sorted(self.data[\"spacex\"][\"dragons\"], key=lambda k: k[\"name\"])\n\n # landpads\n self.data[\"spacex\"][\"landpads\"] = []\n landpadsjson = utils.download_json(\"https://api.spacexdata.com/v4/landpads\")\n for landpad in landpadsjson:\n self.data[\"spacex\"][\"landpads\"].append({\n \"name\": \"%s (%s)\" % (landpad[\"full_name\"], landpad[\"name\"]),\n \"type\": landpad[\"type\"],\n \"location\": \"%s, %s\" % (landpad[\"locality\"], landpad[\"region\"]),\n \"location_url\": \"https://www.google.com/maps/place/%s,%s\" % (landpad[\"latitude\"], landpad[\"longitude\"]),\n \"url\": landpad[\"wikipedia\"],\n \"landing_attempts\": landpad[\"landing_attempts\"],\n \"landing_successes\": landpad[\"landing_successes\"],\n \"description\": landpad[\"details\"],\n \"launches\": len(landpad[\"launches\"]),\n \"status\": landpad[\"status\"],\n \"status_emoji\": utils.to_emoji(landpad[\"status\"]),\n })\n self.data[\"spacex\"][\"landpads\"] = sorted(self.data[\"spacex\"][\"landpads\"], key=lambda k: k[\"name\"])\n\n # launches\n self.data[\"spacex\"][\"launches\"] = {\n \"past\": [],\n \"future\": [],\n }\n launchesjson = utils.download_json(\"https://api.spacexdata.com/v4/launches\")\n for launch in launchesjson:\n launchdata = {\n \"name\": launch[\"name\"],\n \"launch\": datetime.fromtimestamp(launch[\"date_unix\"], tz=timezone.utc).replace(tzinfo=timezone.utc).astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\"),\n \"upcoming\": launch[\"upcoming\"],\n \"flight\": launch[\"flight_number\"],\n \"description\": launch[\"details\"],\n \"url\": launch[\"links\"][\"webcast\"],\n }\n if launch[\"upcoming\"]:\n self.data[\"spacex\"][\"launches\"][\"future\"].append(launchdata)\n else:\n self.data[\"spacex\"][\"launches\"][\"past\"].append(launchdata)\n self.data[\"spacex\"][\"launches\"][\"past\"] = sorted(self.data[\"spacex\"][\"launches\"][\"past\"], key=lambda k: k[\"flight\"])\n self.data[\"spacex\"][\"launches\"][\"future\"] = sorted(self.data[\"spacex\"][\"launches\"][\"future\"], key=lambda k: k[\"flight\"])\n\n # launchpads\n self.data[\"spacex\"][\"launchpads\"] = []\n launchpadsjson = utils.download_json(\"https://api.spacexdata.com/v4/launchpads\")\n for launchpad in launchpadsjson:\n self.data[\"spacex\"][\"launchpads\"].append({\n \"name\": \"%s (%s)\" % (launchpad[\"full_name\"], launchpad[\"name\"]),\n \"location\": \"%s, %s\" % (launchpad[\"locality\"], launchpad[\"region\"]),\n \"location_url\": \"https://www.google.com/maps/place/%s,%s\" % (launchpad[\"latitude\"], launchpad[\"longitude\"]),\n \"launch_attempts\": launchpad[\"launch_attempts\"],\n \"launch_successes\": launchpad[\"launch_successes\"],\n \"description\": launchpad[\"details\"],\n \"status\": launchpad[\"status\"],\n \"status_emoji\": utils.to_emoji(launchpad[\"status\"]),\n })\n self.data[\"spacex\"][\"launchpads\"] = sorted(self.data[\"spacex\"][\"launchpads\"], key=lambda k: k[\"name\"])\n\n # payloads\n self.data[\"spacex\"][\"payloads\"] = []\n payloadsjson = utils.download_json(\"https://api.spacexdata.com/v4/payloads\")\n for payload in payloadsjson:\n self.data[\"spacex\"][\"payloads\"].append({\n \"name\": payload[\"name\"],\n \"type\": payload[\"type\"],\n \"type_emoji\": utils.to_emoji(payload[\"type\"]),\n \"customer\": \", \".join(payload[\"customers\"]),\n \"nationality\": \", \".join(payload[\"nationalities\"]),\n \"manufacturer\": \", \".join(payload[\"manufacturers\"]),\n \"orbit\": payload[\"orbit\"],\n })\n self.data[\"spacex\"][\"payloads\"] = sorted(self.data[\"spacex\"][\"payloads\"], key=lambda k: k[\"name\"])\n\n # roadster\n self.data[\"spacex\"][\"roadster\"] = {}\n roadsterjson = utils.download_json(\"https://api.spacexdata.com/v4/roadster\")\n self.data[\"spacex\"][\"roadster\"][\"name\"] = roadsterjson[\"name\"]\n self.data[\"spacex\"][\"roadster\"][\"url\"] = roadsterjson[\"video\"]\n self.data[\"spacex\"][\"roadster\"][\"date\"] = datetime.fromtimestamp(roadsterjson[\"launch_date_unix\"], tz=timezone.utc).replace(tzinfo=timezone.utc).astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n self.data[\"spacex\"][\"roadster\"][\"description\"] = roadsterjson[\"details\"]\n self.data[\"spacex\"][\"roadster\"][\"launch_mass\"] = \"%s lbs\" % (\"{:,.2f}\".format(float(roadsterjson[\"launch_mass_lbs\"])))\n self.data[\"spacex\"][\"roadster\"][\"orbit\"] = roadsterjson[\"orbit_type\"].title()\n self.data[\"spacex\"][\"roadster\"][\"speed\"] = \"%s mph\" % (\"{:,.2f}\".format(float(roadsterjson[\"speed_mph\"])))\n self.data[\"spacex\"][\"roadster\"][\"earth_distance\"] = \"%s miles\" % (\"{:,.2f}\".format(float(roadsterjson[\"earth_distance_mi\"])))\n self.data[\"spacex\"][\"roadster\"][\"mars_distance\"] = \"%s miles\" % (\"{:,.2f}\".format(float(roadsterjson[\"mars_distance_mi\"])))\n\n # rockets\n self.data[\"spacex\"][\"rockets\"] = []\n rocketsjson = utils.download_json(\"https://api.spacexdata.com/v4/rockets\")\n for rocket in rocketsjson:\n\n payload_weights_leo, payload_weights_gto, payload_weights_moon, payload_weights_mars = \"\", \"\", \"\", \"\"\n for item in rocket[\"payload_weights\"]:\n if item[\"id\"] == \"leo\":\n payload_weights_leo = \"%s lbs\" % (\"{:,}\".format(int(item[\"lb\"])))\n elif item[\"id\"] == \"gto\":\n payload_weights_gto = \"%s lbs\" % (\"{:,}\".format(int(item[\"lb\"])))\n elif item[\"id\"] == \"moon\":\n payload_weights_moon = \"%s lbs\" % (\"{:,}\".format(int(item[\"lb\"])))\n elif item[\"id\"] == \"mars\":\n payload_weights_mars = \"%s lbs\" % (\"{:,}\".format(int(item[\"lb\"])))\n\n self.data[\"spacex\"][\"rockets\"].append({\n \"name\": rocket[\"name\"],\n \"stage\": rocket[\"stages\"],\n \"booster\": rocket[\"boosters\"],\n \"landing_leg\": \"%d (%s)\" % (rocket[\"landing_legs\"][\"number\"], rocket[\"landing_legs\"][\"material\"]),\n \"height\": \"%s feet\" % (\"{:,}\".format(int(rocket[\"height\"][\"feet\"]))),\n \"diameter\": \"%s feet\" % (\"{:,}\".format(int(rocket[\"diameter\"][\"feet\"]))),\n \"mass\": \"%s lbs\" % (\"{:,}\".format(int(rocket[\"mass\"][\"lb\"]))),\n \"launch_cost\": \"$%s\" % (\"{:,}\".format(int(rocket[\"cost_per_launch\"]))),\n \"success_rate\": \"%s%%\" % (rocket[\"success_rate_pct\"]),\n \"first_flight\": datetime.strptime(rocket[\"first_flight\"], \"%Y-%m-%d\").astimezone(tz=None).strftime(\"%d/%b/%Y %Z\"),\n \"description\": rocket[\"description\"],\n \"url\": rocket[\"wikipedia\"],\n\n \"first_stage_reusable\": rocket[\"first_stage\"][\"reusable\"],\n \"first_stage_reusable_emoji\": utils.to_emoji(\"good\") if rocket[\"first_stage\"][\"reusable\"] else utils.to_emoji(\"bad\"),\n \"first_stage_engine\": rocket[\"first_stage\"][\"engines\"],\n \"first_stage_fuel\": \"%s tons\" % (rocket[\"first_stage\"][\"fuel_amount_tons\"]),\n \"first_stage_burn_time\": \"{:,.2f} sec\".format(int(rocket[\"first_stage\"][\"burn_time_sec\"])) if rocket[\"first_stage\"][\"burn_time_sec\"] else \"\",\n\n \"second_stage_reusable\": rocket[\"second_stage\"][\"reusable\"],\n \"second_stage_reusable_emoji\": utils.to_emoji(\"good\") if rocket[\"second_stage\"][\"reusable\"] else utils.to_emoji(\"bad\"),\n \"second_stage_engine\": rocket[\"second_stage\"][\"engines\"],\n \"second_stage_fuel\": \"%s tons\" % (rocket[\"second_stage\"][\"fuel_amount_tons\"]),\n \"second_stage_burn_time\": \"{:,.2f} sec\".format(int(rocket[\"second_stage\"][\"burn_time_sec\"])) if rocket[\"second_stage\"][\"burn_time_sec\"] else \"\",\n\n \"engine\": \"%s (%d)\" % (rocket[\"engines\"][\"type\"].title(), rocket[\"engines\"][\"number\"]),\n \"engine_propellant\": \"%s, %s\" % (rocket[\"engines\"][\"propellant_1\"], rocket[\"engines\"][\"propellant_2\"]),\n \"engine_thrust_to_weight\": rocket[\"engines\"][\"thrust_to_weight\"],\n\n \"payload_weights_leo\": payload_weights_leo,\n \"payload_weights_gto\": payload_weights_gto,\n \"payload_weights_mars\": payload_weights_mars,\n \"payload_weights_moon\": payload_weights_moon,\n\n \"type\": \"%d/%d/%s/%s feet/%s feet/%s lbs\" % (rocket[\"stages\"], rocket[\"boosters\"], \"%d (%s)\" % (rocket[\"landing_legs\"][\"number\"], rocket[\"landing_legs\"][\"material\"]) if rocket[\"landing_legs\"][\"number\"] else 0, \"{:,}\".format(int(rocket[\"height\"][\"feet\"])), \"{:,}\".format(int(rocket[\"diameter\"][\"feet\"])), \"{:,}\".format(int(rocket[\"mass\"][\"lb\"]))),\n \"first_stage\": \"%d/%s tons/%s/%s\" % (rocket[\"first_stage\"][\"engines\"], rocket[\"first_stage\"][\"fuel_amount_tons\"], \"{:,.2f} sec\".format(int(rocket[\"first_stage\"][\"burn_time_sec\"])) if rocket[\"first_stage\"][\"burn_time_sec\"] else \"\", utils.to_emoji(\"good\") if rocket[\"first_stage\"][\"reusable\"] else utils.to_emoji(\"bad\")),\n \"second_stage\": \"%d/%s tons/%s/%s\" % (rocket[\"second_stage\"][\"engines\"], rocket[\"second_stage\"][\"fuel_amount_tons\"], \"{:,.2f} sec\".format(int(rocket[\"second_stage\"][\"burn_time_sec\"])) if rocket[\"second_stage\"][\"burn_time_sec\"] else \"\", utils.to_emoji(\"good\") if rocket[\"second_stage\"][\"reusable\"] else utils.to_emoji(\"bad\")),\n \"engine\": \"%d %s engine(s) w/ %s+%s propellants and a thrust-to-weight ratio of %d\" % (rocket[\"engines\"][\"number\"], rocket[\"engines\"][\"type\"].title(), rocket[\"engines\"][\"propellant_1\"], rocket[\"engines\"][\"propellant_2\"], rocket[\"engines\"][\"thrust_to_weight\"]),\n \"payload\": \"/%s/%s/%s/%s\" % (payload_weights_leo, payload_weights_gto, payload_weights_moon, payload_weights_mars),\n\n })\n self.data[\"spacex\"][\"rockets\"] = sorted(self.data[\"spacex\"][\"rockets\"], key=lambda k: k[\"name\"])\n\n # ships\n self.data[\"spacex\"][\"ships\"] = []\n shipsjson = utils.download_json(\"https://api.spacexdata.com/v4/ships\")\n for ship in shipsjson:\n self.data[\"spacex\"][\"ships\"].append({\n \"name\": ship[\"name\"],\n \"status_emoji\": utils.to_emoji(\"good\") if ship[\"active\"] else utils.to_emoji(\"bad\"),\n \"url\": ship[\"link\"],\n \"port\": ship[\"home_port\"],\n \"mass\": \"%s lbs\" % (\"{:,.2f}\".format(float(item[\"lb\"]))),\n \"launches\": len(ship[\"launches\"]),\n \"type\": ship[\"type\"],\n \"roles\": \", \".join(ship[\"roles\"]),\n })\n self.data[\"spacex\"][\"ships\"] = sorted(self.data[\"spacex\"][\"ships\"], key=lambda k: k[\"name\"])\n\n # starlink\n self.data[\"spacex\"][\"starlink\"] = {\n \"satellites\": [],\n \"mapdata\": [],\n \"stats\": {\n \"inorbit\": 0,\n \"decayed\": 0,\n \"total\": 0,\n \"firstlaunch\": None,\n \"latestlaunch\": None,\n },\n }\n starlinkjson = utils.download_json(\"https://api.spacexdata.com/v4/starlink\")\n locs, epochs = [], []\n for starlink in starlinkjson:\n if not starlink[\"spaceTrack\"][\"LAUNCH_DATE\"]:\n break\n self.data[\"spacex\"][\"starlink\"][\"stats\"][\"total\"] += 1\n epochs.append(datetime.strptime(starlink[\"spaceTrack\"][\"LAUNCH_DATE\"], \"%Y-%m-%d\").timestamp())\n if starlink[\"latitude\"] and starlink[\"longitude\"]:\n self.data[\"spacex\"][\"starlink\"][\"stats\"][\"inorbit\"] += 1\n locs.append(\"%s,%s\" % (\"{:,.2f}\".format(float(starlink[\"latitude\"])), \"{:,.2f}\".format(float(starlink[\"longitude\"]))))\n self.data[\"spacex\"][\"starlink\"][\"mapdata\"].append([\n '<a href=\"https://www.n2yo.com/satellite/?s=%s\"><b>%s</b></a><br/><b>Launch</b>: %s<br/><b>Height</b>: %s<br/><b>Velocity</b>: %s' % (\n starlink[\"spaceTrack\"][\"NORAD_CAT_ID\"],\n starlink[\"spaceTrack\"][\"OBJECT_NAME\"],\n datetime.strptime(starlink[\"spaceTrack\"][\"LAUNCH_DATE\"], \"%Y-%m-%d\").astimezone(tz=None).strftime(\"%d/%b/%Y %Z\"),\n \"%s miles\" % (\"{:,.2f}\".format(float(starlink[\"height_km\"])*0.62137)) if starlink[\"height_km\"] else \"\",\n \"%s mph\" % (\"{:,.2f}\".format(float(starlink[\"velocity_kms\"])*0.62137*60*60)) if starlink[\"velocity_kms\"] else \"\",\n ),\n starlink[\"latitude\"],\n starlink[\"longitude\"],\n ])\n else:\n self.data[\"spacex\"][\"starlink\"][\"stats\"][\"decayed\"] += 1\n self.data[\"spacex\"][\"starlink\"][\"satellites\"].append({\n \"name\": starlink[\"spaceTrack\"][\"OBJECT_NAME\"],\n \"url\": \"https://www.n2yo.com/satellite/?s=%s\" % (starlink[\"spaceTrack\"][\"NORAD_CAT_ID\"]),\n \"launch\": datetime.strptime(starlink[\"spaceTrack\"][\"LAUNCH_DATE\"], \"%Y-%m-%d\").astimezone(tz=None).strftime(\"%d/%b/%Y %Z\"),\n \"epoch\": datetime.strptime(starlink[\"spaceTrack\"][\"LAUNCH_DATE\"], \"%Y-%m-%d\").timestamp(),\n \"latitude\": starlink[\"latitude\"] if starlink[\"latitude\"] else None,\n \"longitude\": starlink[\"longitude\"] if starlink[\"longitude\"] else None,\n \"location\": \"http://maps.google.com/maps?q=%s,%s\" % (starlink[\"latitude\"], starlink[\"longitude\"]) if starlink[\"latitude\"] and starlink[\"longitude\"] else None,\n \"height\": \"%s miles\" % (\"{:,.2f}\".format(float(starlink[\"height_km\"])*0.62137)) if starlink[\"height_km\"] else None,\n \"velocity\": \"%s mph\" % (\"{:,.2f}\".format(float(starlink[\"velocity_kms\"])*0.62137*60*60)) if starlink[\"velocity_kms\"] else None,\n })\n self.data[\"spacex\"][\"starlink\"][\"satellites\"] = sorted(self.data[\"spacex\"][\"starlink\"][\"satellites\"], key=lambda k: k[\"epoch\"])\n self.data[\"spacex\"][\"starlink\"][\"stats\"][\"firstlaunch\"] = time.strftime(\"%d/%b/%Y %Z\", time.localtime(min(epochs)))\n self.data[\"spacex\"][\"starlink\"][\"stats\"][\"latestlaunch\"] = time.strftime(\"%d/%b/%Y %Z\", time.localtime(max(epochs)))\n\n # history\n self.data[\"spacex\"][\"history\"] = []\n historyjson = utils.download_json(\"https://api.spacexdata.com/v4/history\")\n for history in historyjson:\n self.data[\"spacex\"][\"history\"].append({\n \"title\": history[\"title\"],\n \"url\": history[\"links\"][\"article\"] if history[\"links\"][\"article\"] else None,\n \"date\": datetime.fromtimestamp(history[\"event_date_unix\"], tz=timezone.utc).replace(tzinfo=timezone.utc).astimezone(tz=None).strftime(\"%d/%b/%Y %Z\"),\n \"description\": history[\"details\"],\n \"epoch\": history[\"event_date_unix\"],\n })\n self.data[\"spacex\"][\"history\"] = sorted(self.data[\"spacex\"][\"history\"], key=lambda k: k[\"epoch\"])\n\n self.data[\"spacex\"][\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n\n def satview(self):\n self.data[\"satview\"] = {\n \"date\": datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y %Z\"),\n \"fullday\": {\n \"datastore_hstack\": \"https://raw.githubusercontent.com/7h3rAm/datastore/master/earthview_hstack.gif\",\n \"datastore_vstack\": \"https://raw.githubusercontent.com/7h3rAm/datastore/master/earthview_vstack.gif\",\n \"url\": \"https://twitter.com/7h3rAm/status/1401555983373987842\",\n \"title_hstack\": \"Earth Full Day: 07/JUN/2021 (Horizontally Stacked)\",\n \"title_vstack\": \"Earth Full Day: 07/JUN/2021 (Vertically Stacked)\",\n },\n \"himawari8_naturalcolor\": {\n \"source\": \"http://rammb.cira.colostate.edu/ramsdis/online/images/latest/himawari-8/full_disk_ahi_natural_color.jpg\",\n \"datastore\": \"https://raw.githubusercontent.com/7h3rAm/datastore/master/himwari8_naturalcolor.jpg\"\n },\n \"himawari8_truecolor\": {\n \"source\": \"http://rammb.cira.colostate.edu/ramsdis/online/images/latest/himawari-8/full_disk_ahi_true_color.jpg\",\n \"datastore\": \"https://raw.githubusercontent.com/7h3rAm/datastore/master/himwari8_truecolor.jpg\"\n },\n \"goes16_geocolor\": {\n \"source\": \"https://cdn.star.nesdis.noaa.gov/GOES16/ABI/FD/GEOCOLOR/1808x1808.jpg\",\n \"datastore\": \"https://raw.githubusercontent.com/7h3rAm/datastore/master/goes16.jpg\"\n },\n \"goes17_geocolor\": {\n \"source\": \"https://cdn.star.nesdis.noaa.gov/GOES17/ABI/FD/GEOCOLOR/1808x1808.jpg\",\n \"datastore\": \"https://raw.githubusercontent.com/7h3rAm/datastore/master/goes17.jpg\"\n },\n \"meteosat0_naturalcolor\": {\n \"source\": \"https://eumetview.eumetsat.int/static-images/latestImages/EUMETSAT_MSG_RGBNatColourEnhncd_LowResolution.jpg\",\n \"datastore\": \"https://raw.githubusercontent.com/7h3rAm/datastore/master/meteosat0.jpg\"\n },\n \"meteosat415_naturalcolor\": {\n \"source\": \"https://eumetview.eumetsat.int/static-images/latestImages/EUMETSAT_MSGIODC_RGBNatColourEnhncd_LowResolution.jpg\",\n \"datastore\": \"https://raw.githubusercontent.com/7h3rAm/datastore/master/meteosat415.jpg\"\n },\n \"elektrol\": {\n \"source\": \"http://electro.ntsomz.ru/i/splash/20210529-2330.jpg\",\n \"datastore\": \"https://raw.githubusercontent.com/7h3rAm/datastore/master/elektrol.jpg\"\n },\n \"insat_fd_ir\": {\n \"source\": \"https://mausam.imd.gov.in/Satellite/3Dglobe_ir1.jpg\",\n \"datastore\": \"https://raw.githubusercontent.com/7h3rAm/datastore/master/insat_ir1.jpg\"\n },\n \"insat_fd_vis\": {\n \"source\": \"https://mausam.imd.gov.in/Satellite/3Dglobe_vis.jpg\",\n \"datastore\": \"https://raw.githubusercontent.com/7h3rAm/datastore/master/insat_vis.jpg\"\n },\n \"sdo_0171\": {\n \"source\": \"https://sdo.gsfc.nasa.gov/assets/img/latest/latest_1024_0171.jpg\",\n \"datastore\": \"https://raw.githubusercontent.com/7h3rAm/datastore/master/sdo_0171.jpg\"\n },\n \"sdo_0304\": {\n \"source\": \"https://sdo.gsfc.nasa.gov/assets/img/latest/latest_1024_0304.jpg\",\n \"datastore\": \"https://raw.githubusercontent.com/7h3rAm/datastore/master/sdo_0304.jpg\"\n },\n \"sdo_hmid\": {\n \"source\": \"https://sdo.gsfc.nasa.gov/assets/img/latest/latest_1024_HMID.jpg\",\n \"datastore\": \"https://raw.githubusercontent.com/7h3rAm/datastore/master/sdo_hmid.jpg\"\n },\n \"sdo_hmiic\": {\n \"source\": \"https://sdo.gsfc.nasa.gov/assets/img/latest/latest_1024_HMIIC.jpg\",\n \"datastore\": \"https://raw.githubusercontent.com/7h3rAm/datastore/master/sdo_hmiic.jpg\"\n },\n }\n\n epicjson = utils.download_json(\"https://epic.gsfc.nasa.gov/api/natural\")\n ids = []\n for epic in epicjson:\n ids.append(int(epic[\"identifier\"]))\n latest_id = max(ids)\n for epic in epicjson:\n if int(epic[\"identifier\"]) == latest_id:\n date_obj = datetime.strptime(\"%s GMT\" % (epic[\"date\"].replace(\" \", \"T\")), \"%Y-%m-%dT%H:%M:%S GMT\").replace(tzinfo=timezone.utc)\n self.data[\"satview\"][\"dscovr_epic\"] = {\n \"message\": \"%s on %s.\" % (epic[\"caption\"], date_obj.astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")),\n \"source\": \"https://epic.gsfc.nasa.gov/archive/natural/%s/%s/%s/jpg/%s.jpg\" % (epic[\"identifier\"][0:4], epic[\"identifier\"][4:6], epic[\"identifier\"][6:8], epic[\"image\"]),\n \"datastore\": \"https://raw.githubusercontent.com/7h3rAm/datastore/master/dscovr_epic.jpg\",\n }\n\n sats = [\"dscovr_epic\", \"himawari8_naturalcolor\", \"himawari8_truecolor\", \"goes16_geocolor\", \"goes17_geocolor\", \"meteosat0_naturalcolor\", \"meteosat415_naturalcolor\", \"elektrol\", \"insat_fd_ir\", \"insat_fd_vis\", \"sdo_0171\", \"sdo_0304\", \"sdo_hmid\", \"sdo_hmiic\"]\n total = len(sats)\n for idx, sat in enumerate(sats):\n destination_filepath = \"%s/%s\" % (self.datastore_path, self.data[\"satview\"][sat][\"datastore\"].split(\"/\")[-1])\n print(\"[%d/%d] %s\" % (idx+1, total, self.data[\"satview\"][sat][\"source\"]))\n try:\n utils.download(self.data[\"satview\"][sat][\"source\"], destination_filepath)\n except:\n print(\"[!] could not download from %s\" % (self.data[\"satview\"][sat][\"source\"]))\n\n def marsphotos(self):\n # https://github.com/chrisccerami/mars-photo-api\n return\n\n def dsn(self):\n # https://twitter.com/dsn_status\n # https://github.com/russss/pydsn/blob/master/parser.py\n return\n\n def mrn(self):\n # https://twitter.com/mrn_status\n # https://github.com/russss/mrn_status/blob/main/mrn.py\n # https://mars.nasa.gov/rss/api/?feed=marsrelay&category=all&feedtype=json\n # https://mars.nasa.gov/rss/api/?feed=marsrelay_db&category=all&feedtype=json\n # https://mars.nasa.gov/rss/api/?feed=marsrelay_oe&category=all&feedtype=json\n return\n\n def solarbody(self):\n self.data[\"spacex\"][\"solarbody\"] = []\n solarbodyjson = utils.download_json(\"https://api.le-systeme-solaire.net/rest/bodies/\")\n for solarbody in solarbodyjson:\n self.data[\"spacex\"][\"solarbody\"].append({\n \"title\": solarbody[\"title\"],\n \"url\": solarbody[\"links\"][\"article\"] if solarbody[\"links\"][\"article\"] else None,\n \"date\": datetime.fromtimestamp(solarbody[\"event_date_unix\"], tz=timezone.utc).replace(tzinfo=timezone.utc).astimezone(tz=None).strftime(\"%d/%b/%Y %Z\"),\n \"description\": solarbody[\"details\"],\n \"epoch\": solarbody[\"event_date_unix\"],\n })\n self.data[\"spacex\"][\"solarbody\"] = sorted(self.data[\"spacex\"][\"solarbody\"], key=lambda k: k[\"epoch\"])\n\n def spaceprobes(self):\n # https://github.com/spacehackers/api.spaceprob.es\n # http://murmuring-anchorage-8062.herokuapp.com/distances.json\n return\n\n def update(self):\n self.data = utils.load_json(self.datafile_path)\n\n self.apod()\n self.data[\"last_update_epoch\"] = datetime.now().timestamp(); self.data[\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n utils.save_json(self.data, self.datafile_path)\n self.earthevents()\n self.data[\"last_update_epoch\"] = datetime.now().timestamp(); self.data[\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n utils.save_json(self.data, self.datafile_path)\n self.neo()\n self.data[\"last_update_epoch\"] = datetime.now().timestamp(); self.data[\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n utils.save_json(self.data, self.datafile_path)\n self.spaceppl()\n self.data[\"last_update_epoch\"] = datetime.now().timestamp(); self.data[\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n utils.save_json(self.data, self.datafile_path)\n self.spacex()\n self.data[\"last_update_epoch\"] = datetime.now().timestamp(); self.data[\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n utils.save_json(self.data, self.datafile_path)\n self.satview()\n self.data[\"last_update_epoch\"] = datetime.now().timestamp(); self.data[\"last_update\"] = datetime.now().astimezone(tz=None).strftime(\"%d/%b/%Y @ %H:%M:%S %Z\")\n utils.save_json(self.data, self.datafile_path)\n\n\nif __name__ == \"__main__\":\n astro = Astro()\n astro.update()\n" }, { "alpha_fraction": 0.5834991335868835, "alphanum_fraction": 0.5984469652175903, "avg_line_length": 31.346939086914062, "blob_id": "fea345e603b76c6bc13c25daa4e45f938aa8af7e", "content_id": "fb825eda0979d92e609aa84318fef32c69a0ddf8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20683, "license_type": "no_license", "max_line_length": 240, "num_lines": 637, "path": "/utils.py", "repo_name": "7h3rAm/kalpi", "src_encoding": "UTF-8", "text": "import os\nimport re\nimport glob\nimport json\nimport yaml\nimport errno\nimport codecs\nimport locale\nimport fnmatch\nimport datetime\nimport urllib.parse\nimport urllib.request\n\nimport requests\nimport sparkline\nimport prettytable\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n\ndef highlight(text, color=\"black\", bold=False):\n resetcode = \"\\x1b[0m\"\n color = color.lower().strip()\n if color == \"black\":\n colorcode = \"\\x1b[0;30m\" if not bold else \"\\x1b[1;30m\"\n elif color == \"red\":\n colorcode = \"\\x1b[0;31m\" if not bold else \"\\x1b[1;31m\"\n elif color == \"green\":\n colorcode = \"\\x1b[0;32m\" if not bold else \"\\x1b[1;32m\"\n elif color == \"yellow\":\n colorcode = \"\\x1b[0;33m\" if not bold else \"\\x1b[1;33m\"\n elif color == \"blue\":\n colorcode = \"\\x1b[0;34m\" if not bold else \"\\x1b[1;34m\"\n elif color == \"magenta\":\n colorcode = \"\\x1b[0;35m\" if not bold else \"\\x1b[1;35m\"\n elif color == \"cyan\":\n colorcode = \"\\x1b[0;36m\" if not bold else \"\\x1b[1;36m\"\n else:\n colorcode = \"\\x1b[0;30m\" if not bold else \"\\x1b[1;30m\"\n return \"%s%s%s\" % (colorcode, text, resetcode)\n\ndef black(text):\n return highlight(text, color=\"black\", bold=False)\n\ndef black_bold(text):\n return highlight(text, color=\"black\", bold=True)\n\ndef red(text):\n return highlight(text, color=\"red\", bold=False)\n\ndef red_bold(text):\n return highlight(text, color=\"red\", bold=True)\n\ndef green(text):\n return highlight(text, color=\"green\", bold=False)\n\ndef green_bold(text):\n return highlight(text, color=\"green\", bold=True)\n\ndef yellow(text):\n return highlight(text, color=\"yellow\", bold=False)\n\ndef yellow_bold(text):\n return highlight(text, color=\"yellow\", bold=True)\n\ndef blue(text):\n return highlight(text, color=\"blue\", bold=False)\n\ndef blue_bold(text):\n return highlight(text, color=\"blue\", bold=True)\n\ndef magenta(text):\n return highlight(text, color=\"magenta\", bold=False)\n\ndef magenta_bold(text):\n return highlight(text, color=\"magenta\", bold=True)\n\ndef cyan(text):\n return highlight(text, color=\"cyan\", bold=False)\n\ndef cyan_bold(text):\n return highlight(text, color=\"cyan\", bold=True)\n\ndef debug(text):\n print(\"%s %s\" % (blue_bold(\"[*]\"), text))\n\ndef info(text):\n print(\"%s %s\" % (green_bold(\"[+]\"), text))\n\ndef warn(text):\n print(\"%s %s\" % (yellow_bold(\"[!]\"), text))\n\ndef error(text):\n print(\"%s %s\" % (red_bold(\"[-]\"), text))\n\ndef expand_env(var=\"$HOME\"):\n return os.environ[var.replace(\"$\", \"\")]\n\ndef trim(text, maxq=40):\n return \"%s...\" % (text[:maxq]) if len(text) > maxq else text\n\ndef mkdirp(path):\n try:\n os.makedirs(path)\n except OSError as exc:\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n\ndef search_files(dirpath=\"./\", regex=\"*\"):\n matches = []\n for root, dirnames, filenames in os.walk(dirpath):\n for filename in fnmatch.filter(filenames, regex):\n resultfile = os.path.join(root, filename)\n if os.path.exists(resultfile):\n matches.append(resultfile)\n fm = filter(lambda item: '/__pycache__' not in item and '/results' not in item and '/.git' not in item and '/summary.yml' not in item and '/techniques.yml' not in item and '/ttps.yml' not in item and '/test.ttp.yml' not in item, matches)\n return list(set(fm))\n\ndef search_files_all(dirpath):\n return search_files(dirpath, regex=\"*\")\n\ndef search_files_yml(dirpath):\n return search_files(dirpath, regex=\"*.yml\")\n\ndef search_files_md(dirpath):\n return search_files(dirpath, regex=\"*.md\")\n\ndef download_json(url):\n res = requests.get(url)\n if res.status_code == 200:\n return res.json()\n return None\n\ndef load_json(filename):\n with open(filename) as fp:\n return json.load(fp)\n\ndef save_json(datadict, filename):\n with open(filename, \"w\", encoding=\"utf-8\") as fp:\n json.dump(datadict, fp, ensure_ascii=False, indent=2, sort_keys=True)\n\ndef load_file(filename):\n lines = []\n with open(filename) as fp:\n lines = fp.read().split(\"\\n\")\n return lines\n\ndef save_file(datalist, filename):\n with open(filename, \"w\") as fp:\n fp.write(\"\\n\".join(datalist))\n fp.write(\"\\n\")\n\ndef load_yaml(filename):\n return yaml.safe_load(open(filename))\n\ndef save_yaml(datayml, filename):\n with open(filename, \"w\") as fp:\n yaml.dump(datayml, fp, default_flow_style=True)\n\ndef dict2yaml(datadict):\n return yaml.safe_dump(yaml.load(json.dumps(datadict), Loader=yaml.FullLoader), default_flow_style=False)\n\ndef file_open(filename):\n if filename and filename != \"\":\n with codecs.open(filename, mode=\"r\", encoding=\"utf-8\") as fo:\n return fo.read()\n\ndef file_save(filename, data, mode=\"w\"):\n if filename and filename != \"\":\n if \"/\" in filename:\n mkdirp(os.path.dirname(filename))\n try:\n with codecs.open(filename, mode, encoding=\"utf-8\") as fo:\n fo.write(data)\n except Exception as ex:\n with open(filename, mode) as fo:\n try:\n fo.write(data)\n except:\n fo.write(data.encode('utf-16', 'surrogatepass').decode('utf-16'))\n\ndef download(url, filename, timeout=5):\n res = requests.get(url, timeout=timeout)\n print(url, res.status_code)\n if res.status_code == 200:\n open(filename, \"wb\").write(res.content)\n return filename\n else:\n return False\n\ndef get_http_res(url, headers={}):\n res = requests.get(cleanup_url(url), headers=headers)\n print(url, res.status_code)\n return res\n\ndef get_http(url, headers={}):\n res = requests.get(cleanup_url(url), headers=headers)\n print(url, res.status_code)\n if res.status_code == 200:\n return res.json()\n else:\n return {}\n\ndef post_http(url, data={}, headers={}):\n res = requests.post(cleanup_url(url), data=json.dumps(data), headers=headers)\n print(url, res.status_code)\n if res.status_code == 200:\n return res.json()\n else:\n return {}\n\ndef strip_html(data):\n return re.sub(\"\\s+\", \" \", BeautifulSoup(data, \"lxml\").text)\n\ndef datetimefilter(datestr, format='%Y/%m/%d %H:%M:%S'):\n try:\n return datetime.datetime.strptime(str(datestr), '%Y%m%dT%H:%M:%SZ').strftime(format)\n except:\n return datetime.datetime.strptime(str(datestr), '%Y%m%d').strftime(format)\n\ndef cleanup_url(url):\n return url.replace(\"//\", \"/\").replace(\":/\", \"://\")\n\ndef cleanup_name(name):\n return re.sub(r\"[\\W_]\", \"\", name.lower())\n return name.lower().replace(\" \", \"\").replace(\":\", \"\").replace(\"_\", \"\").replace(\"-\", \"\")\n\ndef ghsearchlinks(items, repourl=\"https://github.com/7h3rAm/writeups\", delim=\", \"):\n if isinstance(items, str):\n return \"[`%s`](%s/search?q=%s&unscoped_q=%s)\" % (items, repourl, items, items)\n else:\n return delim.join([ \"[%s](%s/search?q=%s&unscoped_q=%s)\" % (x, repourl, x, x) for x in items])\n\ndef anchorformat(items, repourl=\"https://github.com/7h3rAm/writeups\", delim=\", \"):\n if isinstance(items, str):\n if items.startswith(\"enumerate_\") or items.startswith(\"exploit_\") or items.startswith(\"privesc_\"):\n return \"[`%s`](%s#%s)\" % (items, repourl, items)\n else:\n return ghsearchlinks(items, repourl)\n else:\n results = []\n for x in items:\n if x.startswith(\"enumerate_\") or x.startswith(\"exploit_\") or x.startswith(\"privesc_\"):\n results.append(\"[`%s`](%s#%s)\" % (x, repourl, x))\n else:\n results.append(ghsearchlinks(x, repourl))\n return delim.join(results)\n\ndef mdurl(datadict):\n results = []\n for item in datadict:\n results.append(\"[%s](%s)\" % (item[\"name\"], item[\"url\"]))\n return \"<br /><br />\".join(results)\n\ndef obfuscate(data, mass=0.81):\n # calculate event horizon using the given mass\n # use eh to hide remaining data forever\n if isinstance(data, str):\n eh = int(len(data) * mass)\n return \"\".join([data[:eh], len(data[eh:])*\"*\"])\n else:\n results = []\n for x in data:\n eh = int(len(x) * mass)\n results.append(\"\".join([x[:eh], len(x[eh:])*\"*\"]))\n return results\n\ndef monojoin(items):\n if isinstance(items, str):\n return \"`%s`\" % (items)\n else:\n results = []\n for x in items:\n results.append(\"`%s`\" % (x))\n return \"<br /><br />\".join(results)\n\ndef sec_to_human(secs, sep=\" and \"):\n units = dict({\n 7*24*60*60: \"week\",\n 24*60*60: \"day\",\n 60*60: \"hour\",\n 1*60: \"minute\",\n 1: \"second\"\n })\n if secs <= 0: return \"0 seconds\"\n s = list()\n for divisor, name in sorted(units.items(), reverse=True):\n quot=int(secs/divisor)\n if quot:\n if abs(quot) > 1:\n s.append(\"%s %ss\" % (quot, name))\n else:\n s.append(\"%s %s\" % (quot, name))\n secs -= quot * divisor\n return sep.join(s)\n\ndef currency_human(num):\n try:\n for unit in ['','K','M','B','T']:\n if abs(num) < 1000.0:\n return \"%d%s\" % (num, unit)\n num /= 1000.0\n return \"%d%s\" % (num, 'T')\n except:\n import traceback\n print(traceback.print_exc())\n locale.setlocale(locale.LC_ALL, \"\")\n return locale.currency(num, grouping=True)\n\ndef sizeof_fmt(num, suffix='B'):\n # https://stackoverflow.com/a/1094933/1079836\n for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:\n if abs(num) < 1024.0:\n return \"%3.1f%s%s\" % (num, unit, suffix)\n num /= 1024.0\n return \"%.1f%s%s\" % (num, 'Yi', suffix)\n\ndef customsort(items):\n return [str(y) for y in sorted([int(x) for x in items])]\n\ndef lookahead(iterable):\n # https://stackoverflow.com/a/1630350\n it = iter(iterable)\n last = next(it)\n for val in it:\n yield last, True\n last = val\n yield last, False\n\ndef yturl2verboseid(url):\n #https://www.youtube.com/watch?v=CO_g3wtC7rk&t=0\n for param in url.lower().strip().split(\"?\", 1)[1].split(\"&\"):\n if param.startswith(\"v=\"):\n return \"youtube?%s\" % (param)\n return url\n\ndef sparkify(difficulty):\n return sparkline.sparkify(difficulty)\n\ndef chunkify(l, n):\n for i in range(0, len(l), n):\n yield l[i:i + n]\n\ndef to_color_difficulty(sparkline):\n return \"\".join([green(sparkline[:3]), yellow(sparkline[3:7]), red(sparkline[7:])])\n\ndef to_emoji(text):\n text = str(text)\n # https://github.com/ikatyang/emoji-cheat-sheet\n if \"private\" == text.lower():\n return \"🔒\"\n elif \"public\" == text.lower():\n return \"🔓\"\n elif \"oscplike\" == text.lower():\n return \"⚠️\"\n elif \"access_root\" == text.lower():\n return \"🩸\"\n elif \"access_user\" == text.lower():\n return \"💧\"\n elif \"linux\" == text.lower():\n return \"🐧\"\n elif \"bsd\" in text.lower():\n return \"👹\"\n elif \"windows\" == text.lower():\n return \"🔷\"\n elif \"difficulty_unknown\" == text.lower():\n return \"⚪\"\n elif \"easy\" == text.lower():\n return \"🟢\"\n elif \"medium\" == text.lower():\n return \"🟡\"\n elif \"hard\" == text.lower():\n return \"🟠\"\n elif \"insane\" == text.lower():\n return \"🔴\"\n\n elif \"destroyed\" == text.lower():\n return \"🔴\"\n elif \"retired\" == text.lower():\n return \"🟡\"\n elif \"active\" == text.lower():\n return \"🟢\"\n elif \"unknown\" == text.lower():\n return \"⚪\"\n\n elif \"lost\" == text.lower():\n return \"🔴\"\n elif \"inactive\" == text.lower():\n return \"🟠\"\n elif \"expended\" == text.lower():\n return \"🟡\"\n\n elif \"capsule\" == text.lower():\n return \"💊\"\n elif \"satellite\" == text.lower():\n return \"🛰️\"\n elif \"dragon\" in text.lower():\n return \"🐉\"\n\n elif \"bad\" == text.lower():\n return \"🔴\"\n elif \"good\" == text.lower():\n return \"🟢\"\n\n else:\n return \"⚪\"\n\ndef to_markdown_table(pt):\n _junc = pt.junction_char\n if _junc != \"|\":\n pt.junction_char = \"|\"\n markdown = [row for row in pt.get_string().split(\"\\n\")[1:-1]]\n pt.junction_char = _junc\n return \"\\n\".join(markdown)\n\ndef get_table(header, rows, delim=\"___\", aligndict=None, markdown=False, colalign=None):\n table = prettytable.PrettyTable()\n table.field_names = header\n table.align = \"c\"; table.valign = \"m\"\n for row in rows:\n table.add_row(row.split(delim))\n if markdown:\n if colalign in [\"left\", \"center\", \"right\"]:\n if colalign == \"left\":\n return to_markdown_table(table).replace(\"|-\", \"|:\")\n elif colalign == \"center\":\n return to_markdown_table(table).replace(\"-|-\", \":|:\").replace(\"|-\", \"|:\").replace(\"-|\", \":|\")\n elif colalign == \"right\":\n return to_markdown_table(table).replace(\"-|\", \":|\")\n else:\n #return table.get_html_string()\n return to_markdown_table(table)\n else:\n if aligndict:\n for colheader in aligndict:\n table.align[colheader] = aligndict[colheader]\n else:\n table.align[\"#\"] = \"r\"\n table.align[\"ID\"] = \"r\"\n table.align[\"Name\"] = \"l\"\n table.align[\"Expires\"] = \"l\"\n table.align[\"Follow\"] = \"l\"\n table.align[\"Private\"] = \"c\"\n table.align[\"OS\"] = \"c\"\n table.align[\"Rating\"] = \"l\"\n table.align[\"Difficulty\"] = \"c\"\n table.align[\"Owned\"] = \"l\"\n table.align[\"OSCPlike\"] = \"l\"\n table.vertical_char = \" \"\n table.horizontal_char = \"-\"\n table.junction_char = \" \"\n return table.get_string()\n\ndef to_table(header, rows, delim=\"___\", aligndict=None, markdown=False):\n print(get_table(header, rows, delim=delim, aligndict=aligndict, markdown=markdown))\n\ndef to_json(data):\n print(json.dumps(data, indent=2, sort_keys=True))\n\ndef show_machines(data, sort_key=\"name\", jsonify=False):\n if not len(data):\n return\n elif \"success\" in data:\n return to_json(data)\n elif jsonify:\n to_json(data)\n else:\n rows = []\n if \"writeuppdfurl\" in data[0]:\n header = [\"#\", \"ID\", \"Name\", \"Private\", \"OS\", \"Rating\", \"Difficulty\", \"Owned\", \"OSCPlike\"]\n for idx, entry in enumerate(sorted(data, key=lambda k: k[sort_key].lower())):\n mid = \"%s%s\" % (blue(\"%s#\" % (entry[\"verbose_id\"].split(\"#\")[0])), blue_bold(\"%s\" % (entry[\"verbose_id\"].split(\"#\")[1])))\n name = black_bold(entry[\"name\"])\n os = to_emoji(entry[\"os\"])\n difficulty = to_emoji(entry[\"difficulty\"]) if entry.get(\"difficulty\") and entry[\"difficulty\"] else to_emoji(\"difficulty_unknown\")\n rating = to_color_difficulty(sparkify(entry[\"difficulty_ratings\"])) if entry.get(\"difficulty_ratings\") else \"\"\n if entry.get(\"owned_root\") and entry[\"owned_root\"]:\n owned = to_emoji(\"access_root\")\n elif entry.get(\"owned_user\") and entry[\"owned_user\"]:\n owned = to_emoji(\"access_user\")\n else:\n owned = to_emoji(\"access_none\")\n oscplike = to_emoji(\"oscplike\") if entry[\"oscplike\"] else to_emoji(\"notoscplike\")\n private = to_emoji(\"private\") if entry[\"private\"] else to_emoji(\"public\")\n rows.append(\"%s.___%s___%s___%s___%s___%s___%s___%s___%s\" % (\n idx+1,\n mid,\n name,\n private,\n os,\n rating,\n difficulty,\n owned,\n oscplike,\n ))\n\n elif \"expires_at\" in data[0]:\n header = [\"#\", \"ID\", \"Name\", \"Expires\", \"OS\", \"Difficulty\", \"Rating\", \"Owned\", \"OSCPlike\"]\n for idx, entry in enumerate(sorted(data, key=lambda k: k[sort_key].lower())):\n mid = \"%s%s\" % (blue(\"%s#\" % (entry[\"verbose_id\"].split(\"#\")[0])), blue_bold(\"%s\" % (entry[\"verbose_id\"].split(\"#\")[1])))\n name = black_bold(entry[\"name\"])\n os = to_emoji(entry[\"os\"])\n difficulty = entry[\"difficulty\"] if entry.get(\"difficulty\") and entry[\"difficulty\"] else \"difficulty_unknown\"\n rating = to_color_difficulty(sparkify(entry[\"difficulty_ratings\"])) if entry.get(\"difficulty_ratings\") else \"\"\n if entry.get(\"owned_root\") and entry[\"owned_root\"]:\n owned = \"access_root\"\n elif entry.get(\"owned_user\") and entry[\"owned_user\"]:\n owned = \"access_user\"\n else:\n owned = \"access_none\"\n oscplike = to_emoji(\"oscplike\") if entry[\"oscplike\"] else to_emoji(\"notoscplike\")\n rows.append(\"%s.___%s___%s___%s___%s___%s___%s___%s___%s\" % (\n idx+1,\n mid,\n name,\n entry[\"expires_at\"],\n os,\n to_emoji(difficulty),\n rating,\n to_emoji(owned),\n to_emoji(oscplike),\n ))\n\n elif \"search_url\" in data[0]:\n header = [\"#\", \"ID\", \"Name\", \"Follow\", \"OS\", \"Rating\", \"Difficulty\", \"Owned\", \"OSCPlike\"]\n for idx, entry in enumerate(sorted(data, key=lambda k: k[sort_key].lower())):\n mid = \"%s%s\" % (blue(\"%s#\" % (entry[\"verbose_id\"].split(\"#\")[0])), blue_bold(\"%s\" % (entry[\"verbose_id\"].split(\"#\")[1])))\n name = black_bold(entry[\"name\"])\n follow = blue(entry[\"search_url\"])\n os = to_emoji(entry[\"os\"])\n difficulty = to_emoji(entry[\"difficulty\"]) if entry.get(\"difficulty\") and entry[\"difficulty\"] else to_emoji(\"difficulty_unknown\")\n rating = to_color_difficulty(sparkify(entry[\"difficulty_ratings\"])) if entry.get(\"difficulty_ratings\") else \"\"\n if entry.get(\"owned_root\") and entry[\"owned_root\"]:\n owned = to_emoji(\"access_root\")\n elif entry.get(\"owned_user\") and entry[\"owned_user\"]:\n owned = to_emoji(\"access_user\")\n else:\n owned = to_emoji(\"access_none\")\n oscplike = to_emoji(\"oscplike\") if entry[\"oscplike\"] else to_emoji(\"notoscplike\")\n rows.append(\"%s.___%s___%s___%s___%s___%s___%s___%s___%s\" % (\n idx+1,\n mid,\n name,\n follow,\n os,\n rating,\n difficulty,\n owned,\n oscplike,\n ))\n\n else:\n header = [\"#\", \"ID\", \"Name\", \"OS\", \"Rating\", \"Difficulty\", \"Owned\", \"OSCPlike\"]\n for idx, entry in enumerate(sorted(data, key=lambda k: k[sort_key].lower())):\n mid = \"%s%s\" % (blue(\"%s#\" % (entry[\"verbose_id\"].split(\"#\")[0])), blue_bold(\"%s\" % (entry[\"verbose_id\"].split(\"#\")[1])))\n name = black_bold(entry[\"name\"])\n os = to_emoji(entry[\"os\"])\n difficulty = to_emoji(entry[\"difficulty\"]) if entry.get(\"difficulty\") and entry[\"difficulty\"] else to_emoji(\"difficulty_unknown\")\n rating = to_color_difficulty(sparkify(entry[\"difficulty_ratings\"])) if entry.get(\"difficulty_ratings\") else \"\"\n if entry.get(\"owned_root\") and entry[\"owned_root\"]:\n owned = to_emoji(\"access_root\")\n elif entry.get(\"owned_user\") and entry[\"owned_user\"]:\n owned = to_emoji(\"access_user\")\n else:\n owned = to_emoji(\"access_none\")\n oscplike = to_emoji(\"oscplike\") if entry[\"oscplike\"] else to_emoji(\"notoscplike\")\n rows.append(\"%s.___%s___%s___%s___%s___%s___%s___%s\" % (\n idx+1,\n mid,\n name,\n os,\n rating,\n difficulty,\n owned,\n oscplike,\n ))\n\n to_table(header=header, rows=rows, delim=\"___\", aligndict=None, markdown=False)\n\ndef to_xkcd(plotdict, filename, title, rotate=True, trimlength=20):\n datadict = {}\n for key in plotdict:\n datadict[key] = [[key], [plotdict[key]]]\n with plt.xkcd():\n for idx, label in enumerate(sorted(datadict)):\n plt.bar(datadict[label][0], datadict[label][1])\n text = \"%s... (%d)\" % (\"\".join(datadict[label][0][0][:trimlength]), datadict[label][1][0]) if len(label) >= trimlength else \"%s (%d)\" % (datadict[label][0][0], datadict[label][1][0])\n if rotate:\n angle = 90\n x, y = idx, 0.5\n else:\n angle = 0\n padding = (len(label)/2)/10\n x, y = idx-padding, datadict[label][1][0]-1\n plt.text(s=text, x=x, y=y, color=\"black\", verticalalignment=\"center\", horizontalalignment=\"left\", size=15, rotation=angle, rotation_mode=\"anchor\")\n plt.suptitle(title, fontsize=18, color=\"black\")\n plt.gca().spines[\"left\"].set_color(\"black\")\n plt.gca().spines[\"bottom\"].set_color(\"black\")\n plt.gca().spines[\"left\"].set_visible(False)\n plt.gca().spines[\"right\"].set_visible(False)\n plt.gca().spines[\"top\"].set_visible(False)\n plt.xticks([]); plt.yticks([])\n plt.tight_layout()\n plt.savefig(filename, dpi=300)\n plt.close()\n\ndef to_sparklines(items, filename, transparent=True):\n colormap = [\"#9acc14\", \"#9acc14\", \"#9acc14\", \"#f7af3e\", \"#f7af3e\", \"#f7af3e\", \"#f7af3e\", \"#db524b\", \"#db524b\", \"#db524b\"]\n barlist = plt.bar([str(x) for x in range(len(items))], items, width=0.95)\n for i in range(len(items)):\n barlist[i].set_color(colormap[i])\n ax = plt.gca()\n ax.spines[\"bottom\"].set_visible(False)\n ax.spines[\"left\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n ax.spines[\"top\"].set_visible(False)\n plt.xticks([]); plt.yticks([])\n plt.tight_layout()\n plt.savefig(filename, dpi=300, transparent=transparent)\n plt.close()\n\ndef hex2rgb(hexstr=\"#ffcb6b\"):\n if hexstr and hexstr != \"\":\n return tuple(int(hexstr.replace(\"#\", \"\")[i:i+2], 16) for i in (0, 2, 4))\n\ndef rgb2hex(rgb=(255, 0, 0)):\n if rgb:\n return \"#%s\" % (\"\".join([\"%x\" % (x) for x in rgb]))\n\ndef tint(color, factor=0.35):\n # https://stackoverflow.com/a/6615053/1079836\n # (tint)factor range: 0.1 (dark) - 0.9 (light)\n rgb = hex2rgb(color)\n trgb = (int(rgb[0] + (factor * (255 - rgb[0]))), int(rgb[1] + (factor * (255 - rgb[1]))), int(rgb[2] + (factor * (255 - rgb[2]))))\n return rgb2hex(trgb)\n" } ]
6
doublepi123/demo
https://github.com/doublepi123/demo
7c7ba1e5ef3d946af694e2354e1a45d0472a4424
24b913a2a5ddae9dacaf1cef8fd02967d9149b6f
5d2f639abb93f698dec7436d8aa46d2b1e96a714
refs/heads/master
2023-03-22T03:21:23.745347
2021-03-20T18:01:53
2021-03-20T18:01:53
349,776,431
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6492146849632263, "alphanum_fraction": 0.6492146849632263, "avg_line_length": 21.52941131591797, "blob_id": "feceea21051046ccd52da1cd5f376e30409060d2", "content_id": "7378ac43e8ff6bf455c5343f85fe5854e10566f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 382, "license_type": "no_license", "max_line_length": 44, "num_lines": 17, "path": "/mgr/views.py", "repo_name": "doublepi123/demo", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\n\n# Create your views here.\nfrom common.models import Student\n\n\ndef liststudent(request):\n qs = Student.objects.values()\n\n retStr = ''\n for student in qs:\n for name, value in student.items():\n retStr += f'{name} : {value} | '\n\n retStr += '<br>'\n return HttpResponse(retStr)" }, { "alpha_fraction": 0.4615384638309479, "alphanum_fraction": 0.4615384638309479, "avg_line_length": 15.714285850524902, "blob_id": "f59805af39d25bac8f590ea5a5fcea91bdbec69b", "content_id": "c68a36cf02385451a768bfb1d9569ac87e823d15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 117, "license_type": "no_license", "max_line_length": 21, "num_lines": 7, "path": "/model/Student.py", "repo_name": "doublepi123/demo", "src_encoding": "UTF-8", "text": "class Student:\n name = ''\n id = ''\n age = ''\n homeIncome = ''\n costForFood = ''\n costForOther = ''\n" }, { "alpha_fraction": 0.6564885377883911, "alphanum_fraction": 0.6736640930175781, "avg_line_length": 21.782608032226562, "blob_id": "9f16fd1f710db96fcfd9736a984ea1e0a07c1313", "content_id": "4d00befd83144f5df99c22465c8dfcba5e201374", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 572, "license_type": "no_license", "max_line_length": 62, "num_lines": 23, "path": "/common/models.py", "repo_name": "doublepi123/demo", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib import admin\n\n\n# Create your models here.\nclass Student(models.Model):\n # 姓名\n name = models.CharField(max_length=20)\n # 学号\n stu_id = models.CharField(max_length=20, primary_key=True)\n # 电话号码\n phone = models.CharField(max_length=20)\n # 出生日期\n birthdate = models.DateField()\n # 家庭人数\n people = models.IntegerField()\n # 家庭收入\n income = models.FloatField()\n # 特殊情况\n special = models.CharField(max_length=200)\n\n\nadmin.site.register(Student)\n" } ]
3
deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI
https://github.com/deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI
d4c2b6d70e9faaa2de287ef040d3f98b2e20b359
57f656150da66075db85747591c950512c0ae0a5
283b3b00f6aceecf7a97b186ba2656472403455f
refs/heads/master
2021-05-27T03:03:02.078344
2014-09-23T17:11:31
2014-09-23T17:11:31
16,050,555
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6275100111961365, "alphanum_fraction": 0.6285140514373779, "avg_line_length": 28.294116973876953, "blob_id": "efed7937d7434cf12b412f4abab33859a6b00d19", "content_id": "5108f34a97cedde577490a090968fab78953567c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1992, "license_type": "no_license", "max_line_length": 86, "num_lines": 68, "path": "/BuildMessenger/src/main/java/messenger/util/FileUtil.java", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "package messenger.util;\n\nimport java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\n\nimport javax.xml.bind.JAXBContext;\nimport javax.xml.bind.JAXBException;\nimport javax.xml.bind.Unmarshaller;\n\npublic class FileUtil {\n\n public static String readFile(String file) throws IOException {\n BufferedReader reader = new BufferedReader(new FileReader(file));\n String line = null;\n StringBuilder stringBuilder = new StringBuilder();\n\n while ((line = reader.readLine()) != null) {\n stringBuilder.append(line);\n stringBuilder.append(\"\\n\");\n }\n reader.close();\n return stringBuilder.toString();\n }\n\n public static void writeToFile(String fileName, String content, boolean append) {\n try {\n File file = new File(fileName);\n if (!append) {\n \tfile.delete();\n }\n if (!file.exists()) {\n file.createNewFile();\n }\n \n FileWriter fileWritter = new FileWriter(file.getAbsolutePath(), true);\n BufferedWriter bufferWritter = new BufferedWriter(fileWritter);\n bufferWritter.append(content);\n\n bufferWritter.close();\n\n// System.out.println(\"Done at \" + file.getAbsolutePath());\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public static void deleteFile(String path) {\n File file = new File(path);\n file.delete();\n }\n\n @SuppressWarnings(\"rawtypes\")\n public static Object readXml(String pathname, Class class1) throws JAXBException {\n File file = new File(pathname);\n JAXBContext jaxbContext = JAXBContext.newInstance(class1);\n\n Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();\n Object unmarshal = jaxbUnmarshaller.unmarshal(file);\n return unmarshal;\n }\n\n\n}\n" }, { "alpha_fraction": 0.7309941649436951, "alphanum_fraction": 0.7719298005104065, "avg_line_length": 42, "blob_id": "18a979899325bd83bb2320616ca46aa7f5c231d1", "content_id": "8fcc946937c8c9e757cf7f6b66520cdff32f8818", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 171, "license_type": "no_license", "max_line_length": 71, "num_lines": 4, "path": "/BuildMessenger/src/main/resources/config/Urls.properties", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "jenkins.url=http://ci.humaninference.com\nstatus.url={jenkins.url}/api/xml?xpath=hudson/job[name=%22{0}%22]/color\nbuild.url={jenkins.url}/job/{0}/build\nminRefreshInterval=3" }, { "alpha_fraction": 0.7048208713531494, "alphanum_fraction": 0.7082949876785278, "avg_line_length": 33.00278091430664, "blob_id": "3314a95e586e4fddf1b37e9b8395540286d8c1a1", "content_id": "a4a7369200b143788cc022a4878e8b829cdb08c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 48933, "license_type": "permissive", "max_line_length": 189, "num_lines": 1439, "path": "/resources/Yowsup/Yowsup/connectionmanager.py", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "'''\nCopyright (c) <2012> Tarek Galal <[email protected]>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this \nsoftware and associated documentation files (the \"Software\"), to deal in the Software \nwithout restriction, including without limitation the rights to use, copy, modify, \nmerge, publish, distribute, sublicense, and/or sell copies of the Software, and to \npermit persons to whom the Software is furnished to do so, subject to the following \nconditions:\n\nThe above copyright notice and this permission notice shall be included in all \ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, \nINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR \nA PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT \nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF \nCONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE \nOR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n'''\n\nfrom Yowsup.ConnectionIO.protocoltreenode import ProtocolTreeNode\nfrom Yowsup.ConnectionIO.ioexceptions import ConnectionClosedException\nfrom Yowsup.ConnectionIO.connectionengine import ConnectionEngine\nfrom Yowsup.Common.utilities import Utilities\n\nfrom Yowsup.Common.debugger import Debugger\nimport threading, select, time\nfrom Yowsup.Common.watime import WATime\nfrom .Auth.auth import YowsupAuth\nfrom Yowsup.Common.constants import Constants\nfrom Yowsup.Interfaces.Lib.LibInterface import LibMethodInterface, LibSignalInterface\nimport tempfile\nfrom random import randrange\nimport socket\nimport hashlib\nimport base64\nimport sys\n\n\n\nimport traceback\nclass YowsupConnectionManager:\n\t\n\tdef __init__(self):\n\t\tDebugger.attach(self)\n\t\tself.currKeyId = 1\n\t\tself.iqId = 0\n\t\tself.verbose = True\n\t\tself.state = 0\n\t\tself.lock = threading.Lock()\n\t\tself.autoPong = True\n\t\t\n\t\tself.domain = \"s.whatsapp.net\"\n\t\n\t\t#self.methodInterface = MethodInterface(authenticatedSocketConnection.getId())\n\t\t#self.signalInterface = SignalInterface(authenticatedSocketConnection.getId())\n\t\tself.readerThread = None\n\t\t\n\t\tself.methodInterface = LibMethodInterface()\n\t\tself.signalInterface = LibSignalInterface()\n\t\tself.readerThread = ReaderThread()\n\t\tself.readerThread.setSignalInterface(self.signalInterface)\n\t\t\n\n\t\tself.bindMethods()\n\t\n\t\n\tdef setInterfaces(self, signalInterface, methodInterface):\n\t\tself.methodInterface = methodInterface\n\t\tself.signalInterface = signalInterface\n\t\t\n\t\tself.readerThread.setSignalInterface(self.signalInterface)\n\t\t\n\t\tself.bindMethods()\n\t\t\n\tdef getSignalsInterface(self):\n\t\treturn self.signalInterface\n\t\n\tdef getMethodsInterface(self):\n\t\treturn self.methodInterface\n\n\tdef setAutoPong(self, autoPong):\n\t\tself.autoPong = self.readerThread.autoPong = autoPong\n\t\n\tdef startReader(self):\n\t\tif self.readerThread.isAlive():\n\t\t\tself._d(\"Reader already started\")\n\t\t\treturn 0\n\n\t\tself._d(\"starting reader\")\n\t\ttry:\n\t\t\tself.readerThread.start()\n\t\t\tself._d(\"started\")\n\t\texcept RuntimeError:\n\t\t\tself._d(\"Reader already started before\")\n\t\t\tself.readerThread.sendDisconnected()\n\t\t\treturn 0\n\t\t\n\t\treturn 1\n\t\n\t\n\tdef block(self):\n\t\tself.readerThread.join()\n\n\tdef bindMethods(self):\n\t\tself.methodInterface.registerCallback(\"getVersion\", lambda: Constants.v)\n\t\tself.methodInterface.registerCallback(\"message_send\",self.sendText)\n\t\tself.methodInterface.registerCallback(\"message_imageSend\",self.sendImage)\n\t\tself.methodInterface.registerCallback(\"message_audioSend\",self.sendAudio)\n\t\tself.methodInterface.registerCallback(\"message_videoSend\",self.sendVideo)\n\t\tself.methodInterface.registerCallback(\"message_locationSend\",self.sendLocation)\n\t\tself.methodInterface.registerCallback(\"message_vcardSend\",self.sendVCard)\n\t\t\n\t\tself.methodInterface.registerCallback(\"message_broadcast\",self.sendBroadcast)\n\n\t\tself.methodInterface.registerCallback(\"message_ack\",self.sendMessageReceipt)\n\n\t\tself.methodInterface.registerCallback(\"notification_ack\", self.sendNotificationReceipt)\n\t\t\n\t\tself.methodInterface.registerCallback(\"clientconfig_send\",self.sendClientConfig)\n\n\t\tself.methodInterface.registerCallback(\"delivered_ack\",self.sendDeliveredReceiptAck)\n\n\t\tself.methodInterface.registerCallback(\"visible_ack\",self.sendVisibleReceiptAck)\n\n\t\tself.methodInterface.registerCallback(\"ping\",self.sendPing)\n\t\tself.methodInterface.registerCallback(\"pong\",self.sendPong)\n\n\t\tself.methodInterface.registerCallback(\"typing_send\",self.sendTyping)\n\t\tself.methodInterface.registerCallback(\"typing_paused\",self.sendPaused)\n\n\t\tself.methodInterface.registerCallback(\"subject_ack\",self.sendSubjectReceived)\n\n\t\tself.methodInterface.registerCallback(\"group_getGroups\", self.sendGetGroups)\n\t\tself.methodInterface.registerCallback(\"group_getInfo\",self.sendGetGroupInfo)\n\t\tself.methodInterface.registerCallback(\"group_create\",self.sendCreateGroupChat)\n\t\tself.methodInterface.registerCallback(\"group_addParticipants\",self.sendAddParticipants)\n\t\tself.methodInterface.registerCallback(\"group_removeParticipants\",self.sendRemoveParticipants)\n\t\tself.methodInterface.registerCallback(\"group_end\",self.sendEndGroupChat)\n\t\tself.methodInterface.registerCallback(\"group_setSubject\",self.sendSetGroupSubject)\n\t\tself.methodInterface.registerCallback(\"group_setPicture\", self.sendSetPicture)\n\t\tself.methodInterface.registerCallback(\"group_getPicture\", self.sendGetPicture)\n\t\t\n\t\tself.methodInterface.registerCallback(\"group_getParticipants\",self.sendGetParticipants)\n\n\t\tself.methodInterface.registerCallback(\"picture_get\",self.sendGetPicture)\n\t\tself.methodInterface.registerCallback(\"picture_getIds\",self.sendGetPictureIds)\n\n\t\tself.methodInterface.registerCallback(\"contact_getProfilePicture\", self.sendGetPicture)\n\n\t\tself.methodInterface.registerCallback(\"status_update\",self.sendChangeStatus)\n\n\t\tself.methodInterface.registerCallback(\"presence_request\",self.getLastOnline)\n\t\t#self.methodInterface.registerCallback(\"presence_unsubscribe\",self.sendUnsubscribe)#@@TODO implement method\n\t\tself.methodInterface.registerCallback(\"presence_subscribe\",self.sendSubscribe)\n\t\tself.methodInterface.registerCallback(\"presence_sendAvailableForChat\",self.sendAvailableForChat)\n\t\tself.methodInterface.registerCallback(\"presence_sendAvailable\",self.sendAvailable)\n\t\tself.methodInterface.registerCallback(\"presence_sendUnavailable\",self.sendUnavailable)\n\t\t\n\t\t\n\t\tself.methodInterface.registerCallback(\"profile_setPicture\", self.sendSetProfilePicture)\n\t\tself.methodInterface.registerCallback(\"profile_getPicture\", self.sendGetProfilePicture)\n\t\t\n\t\tself.methodInterface.registerCallback(\"profile_setStatus\", self.sendChangeStatus)\n\n\t\tself.methodInterface.registerCallback(\"disconnect\", self.disconnect)\n\t\tself.methodInterface.registerCallback(\"ready\", self.startReader)\n\t\t\n\t\tself.methodInterface.registerCallback(\"auth_login\", self.auth )\n\t\t#self.methodInterface.registerCallback(\"auth_login\", self.auth)\n\t\t\n\t\tself.methodInterface.registerCallback(\"media_requestUpload\", self.sendRequestUpload)\n\n\n\tdef disconnect(self, reason=\"\"):\n\t\tself._d(\"Disconnect sequence initiated\")\n\t\tself._d(\"Sending term signal to reader thread\")\n\t\tif self.readerThread.isAlive():\n\t\t\tself.readerThread.terminate()\n\t\t\tself._d(\"Shutting down socket\")\n\t\t\tself.socket.close()\n\t\t\tself._d(\"Waiting for readerThread to die\")\n\t\t\tself.readerThread.join()\n\t\tself._d(\"Disconnected!\")\n\t\tself._d(reason)\n\t\tself.state = 0\n\t\tself.readerThread.sendDisconnected(reason)\n\n\n\tdef getConnection(self):\n\t\treturn self.socket\n\n\tdef triggerEvent(self, eventName, stanza):\n\t\tif eventName in self.events and self.events[eventName] is not None:\n\t\t\tself.events[eventName](stanza)\n\n\tdef bindEvent(self, eventName, callback):\n\t\tif eventName in self.events:\n\t\t\tself.events[eventName] = callback\n\n\t##########################################################\n\n\tdef _writeNode(self, node):\n\t\tif self.state == 2:\n\t\t\ttry:\n\t\t\t\tself.out.write(node)\n\t\t\t\treturn True\n\t\t\texcept ConnectionClosedException:\n\t\t\t\tself._d(\"CONNECTION DOWN\")\n\t\t\t\t#self.disconnect(\"closed\")\n\t\t\t\tif self.readerThread.isAlive():\n\t\t\t\t\tself.readerThread.terminate()\n\t\t\t\t\tself.readerThread.join()\n\t\t\t\t\tself.readerThread.sendDisconnected(\"closed\")\n\t\t\n\t\treturn False\n\t\t\n\tdef onDisconnected(self):\n\t\tself._d(\"Setting state to 0\")\n\t\tself.state = 0\n\n\tdef auth(self, username, password):\n\t\tself._d(\">>>>>>>> AUTH CALLED\")\n\t\tusername = str(username)\n\t\t#password = str(password)\n\t\t#traceback.print_stack()\n\t\t\n\t\tself.lock.acquire()\n\t\tif self.state == 0 :\n\t\t\n\t\t\t\n\t\t\tif self.readerThread.isAlive():\n\t\t\t\traise Exception(\"TWO READER THREADS ON BOARD!!\")\n\t\t\t\n\t\t\tself.readerThread = ReaderThread()\n\t\t\tself.readerThread.autoPong = self.autoPong\n\t\t\tself.readerThread.setSignalInterface(self.signalInterface)\n\t\t\tyAuth = YowsupAuth(ConnectionEngine())\n\t\t\ttry:\n\t\t\t\tself.state = 1\n\t\t\t\ttokenData = Utilities.readToken()\n\t\t\t\tresource = tokenData[\"r\"] if tokenData else Constants.tokenData[\"r\"]\n\t\t\t\tconnection = yAuth.authenticate(username, password, Constants.domain, resource)\n\t\t\texcept socket.gaierror:\n\t\t\t\tself._d(\"DNS ERROR\")\n\t\t\t\tself.readerThread.sendDisconnected(\"dns\")\n\t\t\t\t#self.signalInterface.send(\"disconnected\", (\"dns\",))\n\t\t\t\tself.lock.release()\n\t\t\t\tself.state = 0\n\t\t\t\t\n\t\t\t\treturn 0\n\t\t\texcept socket.error:\n\t\t\t\tself._d(\"Socket error, connection timed out\")\n\t\t\t\tself.readerThread.sendDisconnected(\"closed\")\n\t\t\t\t#self.signalInterface.send(\"disconnected\", (\"closed\",))\n\t\t\t\tself.lock.release()\n\t\t\t\tself.state = 0\n\t\t\t\t\n\t\t\t\treturn 0\n\t\t\texcept ConnectionClosedException:\n\t\t\t\tself._d(\"Conn closed Exception\")\n\t\t\t\tself.readerThread.sendDisconnected(\"closed\")\n\t\t\t\t#self.signalInterface.send(\"disconnected\", (\"closed\",))\n\t\t\t\tself.lock.release()\n\t\t\t\tself.state = 0\n\t\t\t\t\n\t\t\t\treturn 0\n\t\t\n\t\t\tif not connection:\n\t\t\t\tself.state = 0\n\t\t\t\tself.signalInterface.send(\"auth_fail\", (username, \"invalid\"))\n\t\t\t\tself.lock.release()\n\t\t\t\treturn 0\n\t\t\t\n\t\t\tself.state = 2\n\t\t\t\n\t\t\t\n\t\n\t\t\tself.socket = connection\n\t\t\tself.jid = self.socket.jid\n\t\t\t#@@TODO REPLACE PROPERLY\n\t\t\tself.out = self.socket.writer\n\t\t\t\n\t\t\tself.readerThread.setSocket(self.socket)\n\t\t\tself.readerThread.disconnectedCallback = self.onDisconnected\n\t\t\tself.readerThread.onPing = self.sendPong\n\t\t\tself.readerThread.ping = self.sendPing\n\t\t\t\n\t\n\t\t\tself.signalInterface.send(\"auth_success\", (username,))\n\t\tself.lock.release()\n\t\t\t\n\t\t\n\t\t\n\t\t\n\tdef sendTyping(self,jid):\n\t\tself._d(\"SEND TYPING TO JID\")\n\t\tcomposing = ProtocolTreeNode(\"composing\",{\"xmlns\":\"http://jabber.org/protocol/chatstates\"})\n\t\tmessage = ProtocolTreeNode(\"message\",{\"to\":jid,\"type\":\"chat\"},[composing]);\n\t\tself._writeNode(message);\n\n\n\n\tdef sendPaused(self,jid):\n\t\tself._d(\"SEND PAUSED TO JID\")\n\t\tcomposing = ProtocolTreeNode(\"paused\",{\"xmlns\":\"http://jabber.org/protocol/chatstates\"})\n\t\tmessage = ProtocolTreeNode(\"message\",{\"to\":jid,\"type\":\"chat\"},[composing]);\n\t\tself._writeNode(message);\n\n\n\n\tdef getSubjectMessage(self,to,msg_id,child):\n\t\tmessageNode = ProtocolTreeNode(\"message\",{\"to\":to,\"type\":\"subject\",\"id\":msg_id},[child]);\n\n\t\treturn messageNode\n\n\tdef sendSubjectReceived(self,to,msg_id):\n\t\tself._d(\"Sending subject recv receipt\")\n\t\treceivedNode = ProtocolTreeNode(\"received\",{\"xmlns\": \"urn:xmpp:receipts\"});\n\t\tmessageNode = self.getSubjectMessage(to,msg_id,receivedNode);\n\t\tself._writeNode(messageNode);\n\n\n\n\tdef sendMessageReceipt(self, jid, msgId):\n\t\tself.sendReceipt(jid, \"chat\", msgId)\n\n\tdef sendNotificationReceipt(self, jid, notificationId):\n\t\tself.sendReceipt(jid, \"notification\", notificationId)\n\n\tdef sendReceipt(self,jid,mtype,mid):\n\t\tself._d(\"sending message received to \"+jid+\" - type:\"+mtype+\" - id:\"+mid)\n\t\treceivedNode = ProtocolTreeNode(\"received\",{\"xmlns\": \"urn:xmpp:receipts\"})\n\t\tmessageNode = ProtocolTreeNode(\"message\",{\"to\":jid,\"type\":mtype,\"id\":mid},[receivedNode]);\n\t\tself._writeNode(messageNode);\n\n\n\tdef sendDeliveredReceiptAck(self,to,msg_id):\n\t\tself._writeNode(self.getReceiptAck(to,msg_id,\"delivered\"));\n\n\tdef sendVisibleReceiptAck(self,to,msg_id):\n\t\tself._writeNode(self.getReceiptAck(to,msg_id,\"visible\"));\n\n\tdef getReceiptAck(self,to,msg_id,receiptType):\n\t\tackNode = ProtocolTreeNode(\"ack\",{\"xmlns\":\"urn:xmpp:receipts\",\"type\":receiptType})\n\t\tmessageNode = ProtocolTreeNode(\"message\",{\"to\":to,\"type\":\"chat\",\"id\":msg_id},[ackNode]);\n\t\treturn messageNode;\n\n\tdef makeId(self,prefix):\n\t\tself.iqId += 1\n\t\tidx = \"\"\n\t\tif self.verbose:\n\t\t\tidx += prefix + str(self.iqId);\n\t\telse:\n\t\t\tidx = \"%x\" % self.iqId\n\n\t\treturn idx\n\n\tdef sendPing(self):\n\n\t\tidx = self.makeId(\"ping_\")\n\n\t\tself.readerThread.requests[idx] = self.readerThread.parsePingResponse;\n\n\t\tpingNode = ProtocolTreeNode(\"ping\",{\"xmlns\":\"w:p\"});\n\t\tiqNode = ProtocolTreeNode(\"iq\",{\"id\":idx,\"type\":\"get\",\"to\":self.domain},[pingNode]);\n\t\tself._writeNode(iqNode);\n\t\treturn idx\n\n\n\tdef sendPong(self,idx):\n\t\tiqNode = ProtocolTreeNode(\"iq\",{\"type\":\"result\",\"to\":self.domain,\"id\":idx})\n\t\tself._writeNode(iqNode);\n\n\tdef getLastOnline(self,jid):\n\n\t\tif len(jid.split('-')) == 2 or jid == \"[email protected]\": #SUPER CANCEL SUBSCRIBE TO GROUP AND SERVER\n\t\t\treturn\n\n\t\tself.sendSubscribe(jid);\n\n\t\tself._d(\"presence request Initiated for %s\"%(jid))\n\t\tidx = self.makeId(\"last_\")\n\t\tself.readerThread.requests[idx] = self.readerThread.parseLastOnline;\n\n\t\tquery = ProtocolTreeNode(\"query\",{\"xmlns\":\"jabber:iq:last\"});\n\t\tiqNode = ProtocolTreeNode(\"iq\",{\"id\":idx,\"type\":\"get\",\"to\":jid},[query]);\n\t\tself._writeNode(iqNode)\n\n\n\tdef sendIq(self):\n\t\tnode = ProtocolTreeNode(\"iq\",{\"to\":\"g.us\",\"type\":\"get\",\"id\":str(int(time.time()))+\"-0\"},None,'expired');\n\t\tself._writeNode(node);\n\n\t\tnode = ProtocolTreeNode(\"iq\",{\"to\":\"s.whatsapp.net\",\"type\":\"set\",\"id\":str(int(time.time()))+\"-1\"},None,'expired');\n\t\tself._writeNode(node);\n\n\tdef sendAvailableForChat(self, pushname):\n\t\tpresenceNode = ProtocolTreeNode(\"presence\",{\"name\":pushname})\n\t\tself._writeNode(presenceNode);\n\n\tdef sendAvailable(self):\n\t\tpresenceNode = ProtocolTreeNode(\"presence\",{\"type\":\"available\"})\n\t\tself._writeNode(presenceNode);\n\n\n\tdef sendUnavailable(self):\n\t\tpresenceNode = ProtocolTreeNode(\"presence\",{\"type\":\"unavailable\"})\n\t\tself._writeNode(presenceNode);\n\n\n\tdef sendSubscribe(self,to):\n\t\tpresenceNode = ProtocolTreeNode(\"presence\",{\"type\":\"subscribe\",\"to\":to});\n\n\t\tself._writeNode(presenceNode);\n\n\n\tdef mediaNode(fn):\n\t\tdef wrapped(self, *args):\n\t\t\t\tmediaType = fn(self, *args)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\turl = args[1]\n\t\t\t\tname = args[2]\n\t\t\t\tsize = args[3]\n\t\t\t\t\n\t\t\t\tmmNode = ProtocolTreeNode(\"media\", {\"xmlns\":\"urn:xmpp:whatsapp:mms\",\"type\":mediaType,\"file\":name,\"size\":size,\"url\":url},None, args[4:][0] if args[4:] else None);\n\t\t\t\treturn mmNode\n\t\t\t\n\t\treturn wrapped\n\t\n\tdef sendMessage(fn):\n\t\t\tdef wrapped(self, *args):\n\t\t\t\tnode = fn(self, *args)\n\t\t\t\tjid = \"broadcast\" if type(args[0]) == list else args[0]\n\t\t\t\tmessageNode = self.getMessageNode(jid, node)\n\t\t\t\t\n\t\t\t\tself._writeNode(messageNode);\n\n\t\t\t\treturn messageNode.getAttributeValue(\"id\")\n\t\t\t\n\t\t\treturn wrapped\n\t\t\n\tdef sendChangeStatus(self,status):\n\t\tself._d(\"updating status to: %s\"%(status))\n\t\t\n\t\tbodyNode = ProtocolTreeNode(\"body\",None,None,status);\n\t\tmessageNode = self.getMessageNode(\"s.us\",bodyNode)\n\t\tself._writeNode(messageNode);\n\t\t\n\t\treturn messageNode.getAttributeValue(\"id\")\n\t\t\n\t\t\n\t\n\t@sendMessage\n\tdef sendText(self,jid, content):\n\t\treturn ProtocolTreeNode(\"body\",None,None,content);\n\n\t@sendMessage\n\t@mediaNode\n\tdef sendImage(self, jid, url, name, size, preview):\n\t\treturn \"image\"\n\t\n\t@sendMessage\n\t@mediaNode\n\tdef sendVideo(self, jid, url, name, size, preview):\n\t\treturn \"video\"\n\t\n\t@sendMessage\n\t@mediaNode\n\tdef sendAudio(self, jid, url, name, size):\n\t\treturn \"audio\"\n\n\t@sendMessage\n\tdef sendLocation(self, jid, latitude, longitude, preview):\n\t\tself._d(\"sending location (\" + latitude + \":\" + longitude + \")\")\n\n\t\treturn ProtocolTreeNode(\"media\", {\"xmlns\":\"urn:xmpp:whatsapp:mms\",\"type\":\"location\",\"latitude\":latitude,\"longitude\":longitude},None,preview)\n\t\t\n\t@sendMessage\n\tdef sendVCard(self, jid, data, name):\n\t\t\n\t\tcardNode = ProtocolTreeNode(\"vcard\",{\"name\":name},None,data);\n\t\treturn ProtocolTreeNode(\"media\", {\"xmlns\":\"urn:xmpp:whatsapp:mms\",\"type\":\"vcard\"},[cardNode])\n\t\n\t@sendMessage\n\tdef sendBroadcast(self, jids, content):\n\t\t\n\t\tbroadcastNode = ProtocolTreeNode(\"broadcast\", None, [ProtocolTreeNode(\"to\", {\"jid\": jid}) for jid in jids])\n\t\t\n\t\tmessageNode = ProtocolTreeNode(\"body\",None,None,content);\n\t\t\n\t\treturn [broadcastNode, messageNode]\n\n\tdef sendClientConfig(self,sound,pushID,preview,platform):\n\t\tidx = self.makeId(\"config_\");\n\t\tconfigNode = ProtocolTreeNode(\"config\",{\"xmlns\":\"urn:xmpp:whatsapp:push\",\"sound\":sound,\"id\":pushID,\"preview\":\"1\" if preview else \"0\",\"platform\":platform})\n\t\tiqNode = ProtocolTreeNode(\"iq\",{\"id\":idx,\"type\":\"set\",\"to\":self.domain},[configNode]);\n\n\t\tself._writeNode(iqNode);\n\n\n\t# gtype should be either \"participating\" or \"owning\"\n\tdef sendGetGroups(self,gtype):\n\t\tself._d(\"getting groups %s\"%(gtype))\n\t\tidx = self.makeId(\"get_groups_\")\n\t\tself.readerThread.requests[idx] = self.readerThread.parseGroups;\n\n\t\tqueryNode = ProtocolTreeNode(\"list\",{\"xmlns\":\"w:g\",\"type\":gtype})\n\t\tiqNode = ProtocolTreeNode(\"iq\",{\"id\":idx,\"type\":\"get\",\"to\":\"g.us\"},[queryNode])\n\n\t\tself._writeNode(iqNode)\n\n\n\tdef sendGetGroupInfo(self,jid):\n\t\tself._d(\"getting group info for %s\"%(jid))\n\t\tidx = self.makeId(\"get_g_info_\")\n\t\tself.readerThread.requests[idx] = self.readerThread.parseGroupInfo;\n\n\t\tqueryNode = ProtocolTreeNode(\"query\",{\"xmlns\":\"w:g\"})\n\t\tiqNode = ProtocolTreeNode(\"iq\",{\"id\":idx,\"type\":\"get\",\"to\":jid},[queryNode])\n\n\t\tself._writeNode(iqNode)\n\n\n\tdef sendCreateGroupChat(self,subject):\n\t\tself._d(\"creating group: %s\"%(subject))\n\t\tidx = self.makeId(\"create_group_\")\n\t\tself.readerThread.requests[idx] = self.readerThread.parseGroupCreated;\n\n\t\tqueryNode = ProtocolTreeNode(\"group\",{\"xmlns\":\"w:g\",\"action\":\"create\",\"subject\":subject})\n\t\tiqNode = ProtocolTreeNode(\"iq\",{\"id\":idx,\"type\":\"set\",\"to\":\"g.us\"},[queryNode])\n\n\t\tself._writeNode(iqNode)\n\n\n\tdef sendAddParticipants(self, gjid, participants):\n\t\tself._d(\"opening group: %s\"%(gjid))\n\t\tself._d(\"adding participants: %s\"%(participants))\n\t\tidx = self.makeId(\"add_group_participants_\")\n\t\tself.readerThread.requests[idx] = self.readerThread.parseAddedParticipants;\n\t\t\n\t\tinnerNodeChildren = []\n\n\t\tfor part in participants:\n\t\t\tinnerNodeChildren.append( ProtocolTreeNode(\"participant\",{\"jid\":part}) )\n\n\t\tqueryNode = ProtocolTreeNode(\"add\",{\"xmlns\":\"w:g\"},innerNodeChildren)\n\t\tiqNode = ProtocolTreeNode(\"iq\",{\"id\":idx,\"type\":\"set\",\"to\":gjid},[queryNode])\n\n\t\tself._writeNode(iqNode)\n\n\n\tdef sendRemoveParticipants(self,gjid, participants):\n\t\tself._d(\"opening group: %s\"%(gjid))\n\t\tself._d(\"removing participants: %s\"%(participants))\n\t\tidx = self.makeId(\"remove_group_participants_\")\n\t\tself.readerThread.requests[idx] = self.readerThread.parseRemovedParticipants;\n\n\t\tinnerNodeChildren = []\n\t\tfor part in participants:\n\t\t\tinnerNodeChildren.append( ProtocolTreeNode(\"participant\",{\"jid\":part}) )\n\n\t\tqueryNode = ProtocolTreeNode(\"remove\",{\"xmlns\":\"w:g\"},innerNodeChildren)\n\t\tiqNode = ProtocolTreeNode(\"iq\",{\"id\":idx,\"type\":\"set\",\"to\":gjid},[queryNode])\n\n\t\tself._writeNode(iqNode)\n\n\n\tdef sendEndGroupChat(self,gjid):\n\t\tself._d(\"removing group: %s\"%(gjid))\n\t\tidx = self.makeId(\"leave_group_\")\n\t\tself.readerThread.requests[idx] = self.readerThread.parseGroupEnded;\n\n\t\tinnerNodeChildren = []\n\t\tinnerNodeChildren.append( ProtocolTreeNode(\"group\",{\"id\":gjid}) )\n\n\t\tqueryNode = ProtocolTreeNode(\"leave\",{\"xmlns\":\"w:g\"},innerNodeChildren)\n\t\tiqNode = ProtocolTreeNode(\"iq\",{\"id\":idx,\"type\":\"set\",\"to\":\"g.us\"},[queryNode])\n\n\t\tself._writeNode(iqNode)\n\n\tdef sendSetGroupSubject(self,gjid,subject):\n\t\t#subject = subject.encode('utf-8')\n\t\t#self._d(\"setting group subject of \" + gjid + \" to \" + subject)\n\t\tidx = self.makeId(\"set_group_subject_\")\n\t\tself.readerThread.requests[idx] = self.readerThread.parseGroupSubject\n\n\t\tqueryNode = ProtocolTreeNode(\"subject\",{\"xmlns\":\"w:g\",\"value\":subject})\n\t\tiqNode = ProtocolTreeNode(\"iq\",{\"id\":idx,\"type\":\"set\",\"to\":gjid},[queryNode]);\n\n\t\tself._writeNode(iqNode)\n\n\n\tdef sendGetParticipants(self,jid):\n\t\tidx = self.makeId(\"get_participants_\")\n\t\tself.readerThread.requests[idx] = self.readerThread.parseParticipants\n\n\t\tlistNode = ProtocolTreeNode(\"list\",{\"xmlns\":\"w:g\"})\n\t\tiqNode = ProtocolTreeNode(\"iq\",{\"id\":idx,\"type\":\"get\",\"to\":jid},[listNode]);\n\n\t\tself._writeNode(iqNode)\n\n\n\tdef sendGetPicture(self,jid):\n\t\tself._d(\"GETTING PICTURE FROM \" + jid)\n\t\tidx = self.makeId(\"get_picture_\")\n\n\t\t#@@TODO, ?!\n\t\tself.readerThread.requests[idx] = self.readerThread.parseGetPicture\n\n\t\tlistNode = ProtocolTreeNode(\"picture\",{\"xmlns\":\"w:profile:picture\",\"type\":\"image\"})\n\t\tiqNode = ProtocolTreeNode(\"iq\",{\"id\":idx,\"to\":jid,\"type\":\"get\"},[listNode]);\n\n\t\tself._writeNode(iqNode)\n\n\n\n\tdef sendGetPictureIds(self,jids):\n\t\tidx = self.makeId(\"get_picture_ids_\")\n\t\tself.readerThread.requests[idx] = self.readerThread.parseGetPictureIds\n\n\t\tinnerNodeChildren = []\n\t\tfor jid in jids:\n\t\t\tinnerNodeChildren.append( ProtocolTreeNode(\"user\",{\"jid\": jid}) )\n\n\t\tqueryNode = ProtocolTreeNode(\"list\",{\"xmlns\":\"w:profile:picture\"},innerNodeChildren)\n\t\tiqNode = ProtocolTreeNode(\"iq\",{\"id\":idx,\"type\":\"get\"},[queryNode])\n\n\t\tself._writeNode(iqNode)\n\n\t\n\tdef sendGetProfilePicture(self):\n\t\treturn self.sendGetPicture(self.jid)\n\t\n\tdef sendSetProfilePicture(self, filepath):\n\t\treturn self.sendSetPicture(self.jid, filepath)\n\t\n\tdef sendSetPicture(self, jid, imagePath):\n\n\t\tf = open(imagePath, 'rb')\n\t\timageData = f.read()\n\t\timageData = bytearray(imageData)\n\t\tf.close()\n\t\t\n\t\tidx = self.makeId(\"set_picture_\")\n\t\tself.readerThread.requests[idx] = self.readerThread.parseSetPicture\n\n\t\tlistNode = ProtocolTreeNode(\"picture\",{\"xmlns\":\"w:profile:picture\",\"type\":\"image\"}, None, imageData)\n\n\t\tiqNode = ProtocolTreeNode(\"iq\",{\"id\":idx,\"to\":jid,\"type\":\"set\"},[listNode])\n\n\t\tself._writeNode(iqNode)\n\n\t\n\tdef sendRequestUpload(self, b64Hash, t, size, b64OrigHash = None):\n\t\tidx = self.makeId(\"upload_\")\n\t\t\n\t\tself.readerThread.requests[idx] = lambda iqresnode: self.readerThread.parseRequestUpload(iqresnode, b64Hash)\n\n\t\tif type(size) is not str:\n\t\t\tsize = str(size)\n\n\t\tattribs = {\"xmlns\":\"w:m\",\"hash\":b64Hash, \"type\":t, \"size\":size}\n\n\t\tif b64OrigHash:\n\t\t\tattribs[\"orighash\"] = b64OrigHash\n\n\t\tmediaNode = ProtocolTreeNode(\"media\", attribs)\n\t\tiqNode = ProtocolTreeNode(\"iq\",{\"id\":idx,\"to\":\"s.whatsapp.net\",\"type\":\"set\"},[mediaNode])\n\t\t\n\t\t\n\t\tself._writeNode(iqNode)\n\n\tdef getMessageNode(self, jid, child):\n\t\t\trequestNode = None;\n\t\t\tserverNode = ProtocolTreeNode(\"server\",None);\n\t\t\txNode = ProtocolTreeNode(\"x\",{\"xmlns\":\"jabber:x:event\"},[serverNode]);\n\t\t\tchildCount = (0 if requestNode is None else 1) +2;\n\t\t\tmessageChildren = []#[None]*childCount;\n\t\t\tif requestNode is not None:\n\t\t\t\tmessageChildren.append(requestNode);\n\t\t\t#System.currentTimeMillis() / 1000L + \"-\"+1\n\t\t\tmessageChildren.append(xNode)\n\t\t\t\n\t\t\tif type(child) == list:\n\t\t\t\tmessageChildren.extend(child)\n\t\t\telse:\n\t\t\t\tmessageChildren.append(child)\n\t\t\t\t\n\t\t\tmsgId = str(int(time.time()))+\"-\"+ str(self.currKeyId)\n\t\t\t\n\t\t\tmessageNode = ProtocolTreeNode(\"message\",{\"to\":jid,\"type\":\"chat\",\"id\":msgId},messageChildren)\n\t\t\t\n\t\t\tself.currKeyId += 1\n\n\n\t\t\treturn messageNode;\n\n\nclass ReaderThread(threading.Thread):\n\tdef __init__(self):\n\t\tDebugger.attach(self);\n\n\t\tself.signalInterface = None\n\t\t#self.socket = connection\n\t\tself.terminateRequested = False\n\t\tself.disconnectedSent = False\n\t\tself.timeout = 180\n\t\tself.selectTimeout = 3\n\t\tself.requests = {};\n\t\tself.lock = threading.Lock()\n\t\tself.disconnectedCallback = None\n\t\tself.autoPong = True\n\t\tself.onPing = self.ping = None\n\n\t\tself.lastPongTime = int(time.time())\n\t\tsuper(ReaderThread,self).__init__();\n\n\t\tself.daemon = True\n\tdef setSocket(self, connection):\n\t\tself.socket = connection\n\n\tdef setSignalInterface(self, signalInterface):\n\t\tself.signalInterface = signalInterface\n\n\tdef terminate(self):\n\t\tself._d(\"attempting to exit gracefully\")\n\t\tself.terminateRequested = True\n\t\t\n\n\tdef sendDisconnected(self, reason=\"noreason\"):\n\t\tself._d(\"Sending disconnected because of %s\" % reason)\n\t\tself.lock.acquire()\n\t\tif not self.disconnectedSent:\n\t\t\tself.disconnectedSent = True\n\t\t\tif self.disconnectedCallback:\n\t\t\t\tself.disconnectedCallback()\n\t\t\tself.lock.release()\n\t\t\tself.signalInterface.send(\"disconnected\", (reason,))\n\n\tdef run(self):\n\t\tself._d(\"Read thread startedX\");\n\t\twhile True:\n\n\t\t\t\n\t\t\tcountdown = self.timeout - ((int(time.time()) - self.lastPongTime))\n\t\t\t\n\t\t\tremainder = countdown % self.selectTimeout\n\t\t\tcountdown = countdown - remainder\n\t\t\t\t\t\n\t\t\tif countdown <= 0:\n\t\t\t\tself._d(\"No hope, dying!\")\n\t\t\t\tself.sendDisconnected(\"closed\")\n\t\t\t\treturn\n\t\t\telse:\n\t\t\t\tif countdown % (self.selectTimeout*10) == 0 or countdown < 11:\n\t\t\t\t\tself._d(\"Waiting, time to die: T-%i seconds\" % countdown )\n\t\t\t\t\t\n\t\t\t\tif self.timeout-countdown == 150 and self.ping and self.autoPong:\n\t\t\t\t\tself.ping()\n\n\t\t\t\tself.selectTimeout = 1 if countdown < 11 else 3\n\n\n\t\t\ttry:\n\t\t\t\tready = select.select([self.socket.reader.rawIn], [], [], self.selectTimeout)\n\t\t\texcept:\n\t\t\t\tself._d(\"Error in ready\")\n\t\t\t\traise\n\t\t\t\treturn\n\t\t\t\n\t\t\tif self.terminateRequested:\n\t\t\t\treturn\n\n\t\t\tif ready[0]:\n\t\t\t\ttry:\n\t\t\t\t\tnode = self.socket.reader.nextTree()\n\t\t\t\texcept ConnectionClosedException:\n\t\t\t\t\t#print traceback.format_exc()\n\t\t\t\t\tself._d(\"Socket closed, got 0 bytes!\")\n\t\t\t\t\t#self.signalInterface.send(\"disconnected\", (\"closed\",))\n\t\t\t\t\tself.sendDisconnected(\"closed\")\n\t\t\t\t\treturn\n\n\t\t\t\tself.lastPongTime = int(time.time());\n\n\t\t\t\tif node is not None:\n\t\t\t\t\tif ProtocolTreeNode.tagEquals(node,\"iq\"):\n\t\t\t\t\t\tiqType = node.getAttributeValue(\"type\")\n\t\t\t\t\t\tidx = node.getAttributeValue(\"id\")\n\n\t\t\t\t\t\tif iqType is None:\n\t\t\t\t\t\t\traise Exception(\"iq doesn't have type\")\n\n\t\t\t\t\t\tif iqType == \"result\":\n\t\t\t\t\t\t\tif idx in self.requests:\n\t\t\t\t\t\t\t\tself.requests[idx](node)\n\t\t\t\t\t\t\t\tdel self.requests[idx]\n\t\t\t\t\t\t\telif idx.startswith(self.connection.user):\n\t\t\t\t\t\t\t\taccountNode = node.getChild(0)\n\t\t\t\t\t\t\t\tProtocolTreeNode.require(accountNode,\"account\")\n\t\t\t\t\t\t\t\tkind = accountNode.getAttributeValue(\"kind\")\n\n\t\t\t\t\t\t\t\tif kind == \"paid\":\n\t\t\t\t\t\t\t\t\tself.connection.account_kind = 1\n\t\t\t\t\t\t\t\telif kind == \"free\":\n\t\t\t\t\t\t\t\t\tself.connection.account_kind = 0\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tself.connection.account_kind = -1\n\n\t\t\t\t\t\t\t\texpiration = accountNode.getAttributeValue(\"expiration\")\n\n\t\t\t\t\t\t\t\tif expiration is None:\n\t\t\t\t\t\t\t\t\traise Exception(\"no expiration\")\n\n\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\tself.connection.expire_date = long(expiration)\n\t\t\t\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\t\t\t\traise IOError(\"invalid expire date %s\"%(expiration))\n\n\t\t\t\t\t\t\t\tself.eventHandler.onAccountChanged(self.connection.account_kind,self.connection.expire_date)\n\t\t\t\t\t\telif iqType == \"error\":\n\t\t\t\t\t\t\tif idx in self.requests:\n\t\t\t\t\t\t\t\tself.requests[idx](node)\n\t\t\t\t\t\t\t\tdel self.requests[idx]\n\t\t\t\t\t\telif iqType == \"get\":\n\t\t\t\t\t\t\tchildNode = node.getChild(0)\n\t\t\t\t\t\t\tif ProtocolTreeNode.tagEquals(childNode,\"ping\"):\n\t\t\t\t\t\t\t\tif self.autoPong:\n\t\t\t\t\t\t\t\t\tself.onPing(idx)\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tself.signalInterface.send(\"ping\", (idx,))\t\n\t\t\t\t\t\t\telif ProtocolTreeNode.tagEquals(childNode,\"query\") and node.getAttributeValue(\"from\") is not None and \"http://jabber.org/protocol/disco#info\" == childNode.getAttributeValue(\"xmlns\"):\n\t\t\t\t\t\t\t\tpin = childNode.getAttributeValue(\"pin\");\n\t\t\t\t\t\t\t\ttimeoutString = childNode.getAttributeValue(\"timeout\");\n\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\ttimeoutSeconds = int(timeoutString) if timeoutString is not None else None\n\t\t\t\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\t\t\t\traise Exception(\"relay-iq exception parsing timeout %s \"%(timeoutString))\n\n\t\t\t\t\t\t\t\tif pin is not None:\n\t\t\t\t\t\t\t\t\tself.eventHandler.onRelayRequest(pin,timeoutSeconds,idx)\n\t\t\t\t\t\telif iqType == \"set\":\n\t\t\t\t\t\t\tchildNode = node.getChild(0)\n\t\t\t\t\t\t\tif ProtocolTreeNode.tagEquals(childNode,\"query\"):\n\t\t\t\t\t\t\t\txmlns = childNode.getAttributeValue(\"xmlns\")\n\n\t\t\t\t\t\t\t\tif xmlns == \"jabber:iq:roster\":\n\t\t\t\t\t\t\t\t\titemNodes = childNode.getAllChildren(\"item\");\n\t\t\t\t\t\t\t\t\task = \"\"\n\t\t\t\t\t\t\t\t\tfor itemNode in itemNodes:\n\t\t\t\t\t\t\t\t\t\tjid = itemNode.getAttributeValue(\"jid\")\n\t\t\t\t\t\t\t\t\t\tsubscription = itemNode.getAttributeValue(\"subscription\")\n\t\t\t\t\t\t\t\t\t\task = itemNode.getAttributeValue(\"ask\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\traise Exception(\"Unkown iq type %s\"%(iqType))\n\n\t\t\t\t\telif ProtocolTreeNode.tagEquals(node,\"presence\"):\n\t\t\t\t\t\txmlns = node.getAttributeValue(\"xmlns\")\n\t\t\t\t\t\tjid = node.getAttributeValue(\"from\")\n\n\t\t\t\t\t\tif (xmlns is None or xmlns == \"urn:xmpp\") and jid is not None:\n\t\t\t\t\t\t\tpresenceType = node.getAttributeValue(\"type\")\n\t\t\t\t\t\t\tif presenceType == \"unavailable\":\n\t\t\t\t\t\t\t\tself.signalInterface.send(\"presence_unavailable\", (jid,))\n\t\t\t\t\t\t\telif presenceType is None or presenceType == \"available\":\n\t\t\t\t\t\t\t\tself.signalInterface.send(\"presence_available\", (jid,))\n\n\t\t\t\t\t\telif xmlns == \"w\" and jid is not None:\n\t\t\t\t\t\t\tstatus = node.getAttributeValue(\"status\")\n\n\t\t\t\t\t\t\tif status == \"dirty\":\n\t\t\t\t\t\t\t\t#categories = self.parseCategories(node); #@@TODO, send along with signal\n\t\t\t\t\t\t\t\tself._d(\"WILL SEND DIRTY\")\n\t\t\t\t\t\t\t\tself.signalInterface.send(\"status_dirty\")\n\t\t\t\t\t\t\t\tself._d(\"SENT DIRTY\")\n\n\t\t\t\t\telif ProtocolTreeNode.tagEquals(node,\"message\"):\n\t\t\t\t\t\tself.parseMessage(node)\n\t\t\t\t\t\n\n\t\tself._d(\"Reader thread terminating now!\")\n\t\t\t\t\t\n\tdef parseOfflineMessageStamp(self,stamp):\n\n\t\twatime = WATime();\n\t\tparsed = watime.parseIso(stamp)\n\t\tlocal = watime.utcToLocal(parsed)\n\t\tstamp = watime.datetimeToTimestamp(local)\n\n\t\treturn stamp\n\n\n\tdef parsePingResponse(self, node):\n\t\tidx = node.getAttributeValue(\"id\")\n\t\tself.lastPongTime = int(time.time())\n\t\t\n\t\t\n\n\tdef parseLastOnline(self,node):\n\t\tjid = node.getAttributeValue(\"from\");\n\t\tfirstChild = node.getChild(0);\n\n\t\tif \"error\" in firstChild.toString():\n\t\t\treturn\n\n\t\tProtocolTreeNode.require(firstChild,\"query\");\n\t\tseconds = firstChild.getAttributeValue(\"seconds\");\n\t\tstatus = None\n\t\tstatus = firstChild.data #@@TODO discarded?\n\n\t\ttry:\n\t\t\tif seconds is not None and jid is not None:\n\t\t\t\tself.signalInterface.send(\"presence_updated\", (jid, int(seconds)))\n\t\texcept:\n\t\t\tself._d(\"Ignored exception in handleLastOnline \"+ sys.exc_info()[1])\n\n\n\tdef parseGroups(self,node):\n\t\tchildren = node.getAllChildren(\"group\");\n\t\tfor groupNode in children:\n\t\t\tjid = groupNode.getAttributeValue(\"id\") + \"@g.us\"\n\t\t\towner = groupNode.getAttributeValue(\"owner\")\n\t\t\tsubject = groupNode.getAttributeValue(\"subject\") if sys.version_info < (3, 0) else groupNode.getAttributeValue(\"subject\").encode('latin-1').decode() \n\t\t\tsubjectT = groupNode.getAttributeValue(\"s_t\")\n\t\t\tsubjectOwner = groupNode.getAttributeValue(\"s_o\")\n\t\t\tcreation = groupNode.getAttributeValue(\"creation\")\n\n\t\t\tself.signalInterface.send(\"group_gotInfo\",(jid, owner, subject, subjectOwner, int(subjectT),int(creation)))\n\n\n\tdef parseGroupInfo(self,node):\n\t\tjid = node.getAttributeValue(\"from\");\n\t\tgroupNode = node.getChild(0)\n\t\tif \"error code\" in groupNode.toString():\n\t\t\tself.signalInterface.send(\"group_infoError\",(0,)) #@@TODO replace with real error code\n\t\telse:\n\t\t\tProtocolTreeNode.require(groupNode,\"group\")\n\t\t\t#gid = groupNode.getAttributeValue(\"id\")\n\t\t\towner = groupNode.getAttributeValue(\"owner\")\n\t\t\tsubject = groupNode.getAttributeValue(\"subject\") if sys.version_info < (3, 0) else groupNode.getAttributeValue(\"subject\").encode('latin-1').decode();\n\t\t\tsubjectT = groupNode.getAttributeValue(\"s_t\")\n\t\t\tsubjectOwner = groupNode.getAttributeValue(\"s_o\")\n\t\t\tcreation = groupNode.getAttributeValue(\"creation\")\n\t\t\n\t\t\tself.signalInterface.send(\"group_gotInfo\",(jid, owner, subject, subjectOwner, int(subjectT),int(creation)))\n\n\tdef parseAddedParticipants(self, node):\n\t\tjid = node.getAttributeValue(\"from\");\n\t\tjids = []\n\t\t\n\t\taddNodes = node.getAllChildren(\"add\")\n\n\t\tfor a in addNodes:\n\t\t\tt = a.getAttributeValue(\"type\")\n\t\t\tif t == \"success\":\n\t\t\t\tjids.append(a.getAttributeValue(\"participant\"))\n\t\t\telse:\n\t\t\t\tself._d(\"Failed to add %s\" % jids.append(a.getAttributeValue(\"participant\")))\n\t\t\n\t\tself.signalInterface.send(\"group_addParticipantsSuccess\", (jid, jids))\n\n\n\tdef parseRemovedParticipants(self,node): #fromm, successVector=None,failTable=None\n\t\tjid = node.getAttributeValue(\"from\");\n\t\tjids = []\n\t\t\n\t\taddNodes = node.getAllChildren(\"remove\")\n\n\t\tfor a in addNodes:\n\t\t\tt = a.getAttributeValue(\"type\")\n\t\t\tif t == \"success\":\n\t\t\t\tjids.append(a.getAttributeValue(\"participant\"))\n\t\t\telse:\n\t\t\t\tself._d(\"Failed to add %s\" % jids.append(a.getAttributeValue(\"participant\")))\n\t\tself._d(\"handleRemovedParticipants DONE!\");\n\n\t\tself.signalInterface.send(\"group_removeParticipantsSuccess\", (jid, jids))\n\n\tdef parseGroupCreated(self,node):\n\t\tjid = node.getAttributeValue(\"from\");\n\t\tgroupNode = node.getChild(0)\n\t\t\n\t\tif ProtocolTreeNode.tagEquals(groupNode,\"error\"):\n\t\t\terrorCode = groupNode.getAttributeValue(\"code\")\n\t\t\tself.signalInterface.send(\"group_createFail\", (errorCode,))\n\t\t\treturn\n\n\t\tProtocolTreeNode.require(groupNode,\"group\")\n\t\tgroup_id = groupNode.getAttributeValue(\"id\")\n\t\tself.signalInterface.send(\"group_createSuccess\", (group_id + \"@g.us\",))\n\n\tdef parseGroupEnded(self,node):\n\t\t#jid = node.getAttributeValue(\"from\");\n\t\t\n\t\tleaveNode = node.getChild(0)\n\t\tgroupNode = leaveNode.getChild(0)\n\t\t\n\t\tjid = groupNode.getAttributeValue(\"id\")\n\t\t\n\t\tself.signalInterface.send(\"group_endSuccess\", (jid,))\n\n\tdef parseGroupSubject(self,node):\n\t\tjid = node.getAttributeValue(\"from\");\n\t\tself.signalInterface.send(\"group_setSubjectSuccess\", (jid,))\n\n\tdef parseParticipants(self,node):\n\t\tjid = node.getAttributeValue(\"from\");\n\t\tchildren = node.getAllChildren(\"participant\");\n\t\tjids = []\n\t\tfor c in children:\n\t\t\tjids.append(c.getAttributeValue(\"jid\"))\n\n\t\tself.signalInterface.send(\"group_gotParticipants\", (jid, jids))\n\n\t#@@TODO PICTURE STUFF\n\n\n\tdef createTmpFile(self, data, mode = \"w\"):\n\t\t\n\t\ttmp = tempfile.mkstemp()[1]\n\t\t\n\t\ttmpfile = open(tmp, mode)\n\t\ttmpfile.write(data)\n\t\ttmpfile.close()\n\n\t\treturn tmp\n\t\n\tdef parseGetPicture(self,node):\n\t\tjid = node.getAttributeValue(\"from\");\n\t\tif \"error code\" in node.toString():\n\t\t\treturn;\n\n\t\tpictureNode = node.getChild(\"picture\")\n\t\tif pictureNode.data is not None:\n\t\t\ttmp = self.createTmpFile(pictureNode.data if sys.version_info < (3, 0) else pictureNode.data.encode('latin-1'), \"wb\")\n\n\t\t\tpictureId = int(pictureNode.getAttributeValue('id'))\n\t\t\ttry:\n\t\t\t\tjid.index('-')\n\t\t\t\tself.signalInterface.send(\"group_gotPicture\", (jid, pictureId, tmp))\n\t\t\texcept ValueError:\n\t\t\t\tself.signalInterface.send(\"contact_gotProfilePicture\", (jid, pictureId, tmp))\n\n\n\tdef parseGetPictureIds(self,node):\n\t\tjid = node.getAttributeValue(\"from\");\n\t\tgroupNode = node.getChild(\"list\")\n\t\t#self._d(groupNode.toString())\n\t\tchildren = groupNode.getAllChildren(\"user\");\n\t\t#pids = []\n\t\tfor c in children:\n\t\t\tif c.getAttributeValue(\"id\") is not None:\n\t\t\t\t#pids.append({\"jid\":c.getAttributeValue(\"jid\"),\"id\":c.getAttributeValue(\"id\")})\n\t\t\t\tself.signalInterface.send(\"contact_gotProfilePictureId\", (c.getAttributeValue(\"jid\"), c.getAttributeValue(\"id\")))\n\t\t#self.signalInterface.send(\"contact_gotProfilePictureIds\", (pids,))\n\n\n\tdef parseSetPicture(self,node):\n\t\tjid = node.getAttributeValue(\"from\");\n\t\tpicNode = node.getChild(\"picture\")\n\t\t\n\t\ttry:\n\t\t\tjid.index('-')\n\t\t\t\n\t\t\tif picNode is None:\n\t\t\t\tself.signalInterface.send(\"group_setPictureError\", (jid,0)) #@@TODO SEND correct error code\n\t\t\telse:\n\t\t\t\tpictureId = int(picNode.getAttributeValue(\"id\"))\n\t\t\t\tself.signalInterface.send(\"group_setPictureSuccess\", (jid, pictureId))\n\t\texcept ValueError:\n\t\t\tif picNode is None:\n\t\t\t\tself.signalInterface.send(\"profile_setPictureError\", (0,)) #@@TODO SEND correct error code\n\t\t\telse:\n\t\t\t\tpictureId = int(picNode.getAttributeValue(\"id\"))\n\t\t\t\tself.signalInterface.send(\"profile_setPictureSuccess\", (pictureId,))\n\t\n\t\n\tdef parseRequestUpload(self, iqNode, _hash):\n\n\t\tmediaNode = iqNode.getChild(\"media\")\n\t\t\n\t\t\n\t\tif mediaNode:\n\n\t\t\turl = mediaNode.getAttributeValue(\"url\")\n\t\t\t\n\t\t\tresumeFrom = mediaNode.getAttributeValue(\"resume\")\n\t\t\t\n\t\t\tif not resumeFrom:\n\t\t\t\tresumeFrom = 0\n\t\n\t\t\tif url:\n\t\t\t\tself.signalInterface.send(\"media_uploadRequestSuccess\", (_hash, url, resumeFrom))\n\t\t\telse:\n\t\t\t\tself.signalInterface.send(\"media_uploadRequestFailed\", (_hash,))\n\t\telse:\n\t\t\tduplicateNode = iqNode.getChild(\"duplicate\")\n\t\t\t\n\t\t\tif duplicateNode:\n\t\t\t\t\n\t\t\t\turl = duplicateNode.getAttributeValue(\"url\")\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tself.signalInterface.send(\"media_uploadRequestDuplicate\", (_hash, url))\n\t\t\n\t\t\telse:\n\t\t\t\tself.signalInterface.send(\"media_uploadRequestFailed\", (_hash,))\n\t\t\t\t\n\n\tdef parseMessage(self,messageNode):\n\n\n\t\tbodyNode = messageNode.getChild(\"body\");\n#\t\tofflineNode = messageNode.getChild(\"offline\")\n\n\t\t\n\t\tnewSubject = \"\" if bodyNode is None else bodyNode.data;\n\t\tmsgData = None\n#\t\ttimestamp =long(time.time()*1000) if not offlineNode else int(messageNode.getAttributeValue(\"t\"))*1000;\n\t\ttimestamp =int(messageNode.getAttributeValue(\"t\"))\n\t\tisGroup = False\n\t\tisBroadcast = False\n\t\t\n\t\tif newSubject.find(\"New version of WhatsApp Messenger is now available\")>-1:\n\t\t\tself._d(\"Rejecting whatsapp server message\")\n\t\t\treturn #REJECT THIS FUCKING MESSAGE!\n\n\n\t\tfromAttribute = messageNode.getAttributeValue(\"from\");\n\n\t\ttry:\n\t\t\tfromAttribute.index('-')\n\t\t\tisGroup = True\n\t\texcept:\n\t\t\tpass\n\n\t\tauthor = messageNode.getAttributeValue(\"author\");\n\t\t#@@TODO reactivate blocked contacts check from client\n\t\t'''if fromAttribute is not None and fromAttribute in self.eventHandler.blockedContacts:\n\t\t\tself._d(\"CONTACT BLOCKED!\")\n\t\t\treturn\n\n\t\tif author is not None and author in self.eventHandler.blockedContacts:\n\t\t\tself._d(\"CONTACT BLOCKED!\")\n\t\t\treturn\n\t\t'''\n\n\t\tpushName = None\n\t\tnotifNode = messageNode.getChild(\"notify\")\n\t\tif notifNode is not None:\n\t\t\tpushName = notifNode.getAttributeValue(\"name\");\n\t\t\t#pushName = pushName.decode(\"utf8\")\n\n\n\t\tmsgId = messageNode.getAttributeValue(\"id\");\n\t\tattribute_t = messageNode.getAttributeValue(\"t\");\n\n\t\ttypeAttribute = messageNode.getAttributeValue(\"type\");\n\n\t\tif typeAttribute == \"error\":\n\t\t\terrorCode = 0;\n\t\t\terrorNodes = messageNode.getAllChildren(\"error\");\n\t\t\tfor errorNode in errorNodes:\n\t\t\t\tcodeString = errorNode.getAttributeValue(\"code\")\n\t\t\t\ttry:\n\t\t\t\t\terrorCode = int(codeString);\n\t\t\t\texcept ValueError:\n\t\t\t\t\t'''catch value error'''\n\t\t\t\tself.signalInterface.send(\"message_error\", (msgId, fromAttribute, errorCode))\n\n\t\telif typeAttribute == \"notification\":\n\n\t\t\treceiptRequested = False;\n\t\t\tpictureUpdated = None\n\n\t\t\tpictureUpdated = messageNode.getChild(\"notification\").getAttributeValue(\"type\");\n\n\t\t\twr = None\n\t\t\twr = messageNode.getChild(\"request\").getAttributeValue(\"xmlns\");\n\t\t\tif wr == \"urn:xmpp:receipts\":\n\t\t\t\treceiptRequested = True\n\t\t\t\t\n\t\t\tif pictureUpdated == \"picture\":\n\t\t\t\tnotifNode = messageNode.getChild(\"notification\");\n\t\t\t\t#bodyNode = messageNode.getChild(\"notification\").getChild(\"set\") or messageNode.getChild(\"notification\").getChild(\"delete\")\n\n\t\t\t\tbodyNode = notifNode.getChild(\"set\")\n\t\t\t\t\n\t\t\t\tif bodyNode:\n\t\t\t\t\tpictureId = int(bodyNode.getAttributeValue(\"id\"))\n\t\t\t\t\tif isGroup:\n\t\t\t\t\t\tself.signalInterface.send(\"notification_groupPictureUpdated\",(bodyNode.getAttributeValue(\"jid\"), bodyNode.getAttributeValue(\"author\"), timestamp, msgId, pictureId, receiptRequested))\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.signalInterface.send(\"notification_contactProfilePictureUpdated\",(bodyNode.getAttributeValue(\"jid\"), timestamp, msgId, pictureId, receiptRequested))\n\n\t\t\t\telse:\n\t\t\t\t\tbodyNode = notifNode.getChild(\"delete\")\n\n\t\t\t\t\tif bodyNode:\n\t\t\t\t\t\tif isGroup:\n\t\t\t\t\t\t\tself.signalInterface.send(\"notification_groupPictureRemoved\",(bodyNode.getAttributeValue(\"jid\"), bodyNode.getAttributeValue(\"author\"), timestamp, msgId, receiptRequested))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.signalInterface.send(\"notification_contactProfilePictureRemoved\",(bodyNode.getAttributeValue(\"jid\"), timestamp, msgId, receiptRequested))\n\n\t\t\t\t#if isGroup:\n\t\t\t\t#\t\n\t\t\t\t#\tself.signalInterface.send(\"notification_groupPictureUpdated\",(bodyNode.getAttributeValue(\"jid\"), bodyNode.getAttributeValue(\"author\"), timestamp, msgId, receiptRequested))\n\t\t\t\t#else:\n\t\t\t\t#\tself.signalInterface.send(\"notification_contactProfilePictureUpdated\",(bodyNode.getAttributeValue(\"jid\"), timestamp, msgId, receiptRequested))\n\n\t\t\telse:\n\t\t\t\taddSubject = None\n\t\t\t\tremoveSubject = None\n\t\t\t\tauthor = None\n\n\t\t\t\tbodyNode = messageNode.getChild(\"notification\").getChild(\"add\");\n\t\t\t\tif bodyNode is not None:\n\t\t\t\t\taddSubject = bodyNode.getAttributeValue(\"jid\");\n\t\t\t\t\tauthor = bodyNode.getAttributeValue(\"author\") or addSubject\n\n\t\t\t\tbodyNode = messageNode.getChild(\"notification\").getChild(\"remove\");\n\t\t\t\tif bodyNode is not None:\n\t\t\t\t\tremoveSubject = bodyNode.getAttributeValue(\"jid\");\n\t\t\t\t\tauthor = bodyNode.getAttributeValue(\"author\") or removeSubject\n\n\t\t\t\tif addSubject is not None:\n\t\t\t\t\t\n\t\t\t\t\tself.signalInterface.send(\"notification_groupParticipantAdded\", (fromAttribute, addSubject, author, timestamp, msgId, receiptRequested))\n\t\t\t\t\t\n\t\t\t\tif removeSubject is not None:\n\t\t\t\t\tself.signalInterface.send(\"notification_groupParticipantRemoved\", (fromAttribute, removeSubject, author, timestamp, msgId, receiptRequested))\n\n\n\t\telif typeAttribute == \"subject\":\n\t\t\treceiptRequested = False;\n\t\t\trequestNodes = messageNode.getAllChildren(\"request\");\n\t\t\tfor requestNode in requestNodes:\n\t\t\t\tif requestNode.getAttributeValue(\"xmlns\") == \"urn:xmpp:receipts\":\n\t\t\t\t\treceiptRequested = True;\n\n\t\t\tbodyNode = messageNode.getChild(\"body\");\n\t\t\tnewSubject = None if bodyNode is None else (bodyNode.data if sys.version_info < (3, 0) else bodyNode.data.encode('latin-1').decode());\n\t\t\t\n\t\t\tif newSubject is not None:\n\t\t\t\tself.signalInterface.send(\"group_subjectReceived\",(msgId, fromAttribute, author, newSubject, int(attribute_t), receiptRequested))\n\n\t\telif typeAttribute == \"chat\":\n\t\t\twantsReceipt = False;\n\t\t\tmessageChildren = [] if messageNode.children is None else messageNode.children\n\n\t\t\tfor childNode in messageChildren:\n\t\t\t\tif ProtocolTreeNode.tagEquals(childNode,\"request\"):\n\t\t\t\t\twantsReceipt = True;\n\t\t\t\t\n\t\t\t\tif ProtocolTreeNode.tagEquals(childNode,\"broadcast\"):\n\t\t\t\t\tisBroadcast = True\n\t\t\t\telif ProtocolTreeNode.tagEquals(childNode,\"composing\"):\n\t\t\t\t\t\tself.signalInterface.send(\"contact_typing\", (fromAttribute,))\n\t\t\t\telif ProtocolTreeNode.tagEquals(childNode,\"paused\"):\n\t\t\t\t\t\tself.signalInterface.send(\"contact_paused\",(fromAttribute,))\n\n\t\t\t\telif ProtocolTreeNode.tagEquals(childNode,\"media\") and msgId is not None:\n\t\n\t\t\t\t\tself._d(\"MULTIMEDIA MESSAGE!\");\n\t\t\t\t\t\n\t\t\t\t\tmediaUrl = messageNode.getChild(\"media\").getAttributeValue(\"url\");\n\t\t\t\t\tmediaType = messageNode.getChild(\"media\").getAttributeValue(\"type\")\n\t\t\t\t\tmediaSize = messageNode.getChild(\"media\").getAttributeValue(\"size\")\n\t\t\t\t\tencoding = messageNode.getChild(\"media\").getAttributeValue(\"encoding\")\n\t\t\t\t\tmediaPreview = None\n\n\n\t\t\t\t\tif mediaType == \"image\":\n\t\t\t\t\t\tmediaPreview = messageNode.getChild(\"media\").data\n\t\t\t\t\t\t\n\t\t\t\t\t\tif encoding == \"raw\" and mediaPreview:\n\t\t\t\t\t\t\tmediaPreview = base64.b64encode(mediaPreview) if sys.version_info < (3, 0) else base64.b64encode(mediaPreview.encode('latin-1')).decode()\n\n\t\t\t\t\t\tif isGroup:\n\t\t\t\t\t\t\tself.signalInterface.send(\"group_imageReceived\", (msgId, fromAttribute, author, mediaPreview, mediaUrl, mediaSize, wantsReceipt))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.signalInterface.send(\"image_received\", (msgId, fromAttribute, mediaPreview, mediaUrl, mediaSize, wantsReceipt, isBroadcast))\n\n\t\t\t\t\telif mediaType == \"video\":\n\t\t\t\t\t\tmediaPreview = messageNode.getChild(\"media\").data\n\t\t\t\t\t\t\n\t\t\t\t\t\tif encoding == \"raw\" and mediaPreview:\n\t\t\t\t\t\t\tmediaPreview = base64.b64encode(mediaPreview) if sys.version_info < (3, 0) else base64.b64encode(mediaPreview.encode('latin-1')).decode()\n\n\t\t\t\t\t\tif isGroup:\n\t\t\t\t\t\t\tself.signalInterface.send(\"group_videoReceived\", (msgId, fromAttribute, author, mediaPreview, mediaUrl, mediaSize, wantsReceipt))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.signalInterface.send(\"video_received\", (msgId, fromAttribute, mediaPreview, mediaUrl, mediaSize, wantsReceipt, isBroadcast))\n\n\t\t\t\t\telif mediaType == \"audio\":\n\t\t\t\t\t\tmediaPreview = messageNode.getChild(\"media\").data\n\n\t\t\t\t\t\tif isGroup:\n\t\t\t\t\t\t\tself.signalInterface.send(\"group_audioReceived\", (msgId, fromAttribute, author, mediaUrl, mediaSize, wantsReceipt))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.signalInterface.send(\"audio_received\", (msgId, fromAttribute, mediaUrl, mediaSize, wantsReceipt, isBroadcast))\n\n\t\t\t\t\telif mediaType == \"location\":\n\t\t\t\t\t\tmlatitude = messageNode.getChild(\"media\").getAttributeValue(\"latitude\")\n\t\t\t\t\t\tmlongitude = messageNode.getChild(\"media\").getAttributeValue(\"longitude\")\n\t\t\t\t\t\tname = messageNode.getChild(\"media\").getAttributeValue(\"name\")\n\t\t\t\t\t\t\n\t\t\t\t\t\tif name and not sys.version_info < (3, 0):\n\t\t\t\t\t\t\tname = name.encode('latin-1').decode()\n\t\t\t\t\t\t\n\t\t\t\t\t\tmediaPreview = messageNode.getChild(\"media\").data\n\t\t\t\t\t\t\n\t\t\t\t\t\tif encoding == \"raw\" and mediaPreview:\n\t\t\t\t\t\t\tmediaPreview = base64.b64encode(mediaPreview) if sys.version_info < (3, 0) else base64.b64encode(mediaPreview.encode('latin-1')).decode()\n\n\t\t\t\t\t\tif isGroup:\n\t\t\t\t\t\t\tself.signalInterface.send(\"group_locationReceived\", (msgId, fromAttribute, author, name or \"\", mediaPreview, mlatitude, mlongitude, wantsReceipt))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.signalInterface.send(\"location_received\", (msgId, fromAttribute, name or \"\", mediaPreview, mlatitude, mlongitude, wantsReceipt, isBroadcast))\n\t\t\n\t\t\t\t\telif mediaType ==\"vcard\":\n\t\t\t\t\t\t#return\n\t\t\t\t\t\t#mediaItem.preview = messageNode.getChild(\"media\").data\n\t\t\t\t\t\tvcardData = messageNode.getChild(\"media\").getChild(\"vcard\").toString()\n\t\t\t\t\t\tvcardName = messageNode.getChild(\"media\").getChild(\"vcard\").getAttributeValue(\"name\")\n\t\t\t\t\t\t\n\t\t\t\t\t\tif vcardName and not sys.version_info < (3, 0):\n\t\t\t\t\t\t\tvcardName = vcardName.encode('latin-1').decode()\n\t\t\t\t\t\t\n\t\t\t\t\t\tif vcardData is not None:\n\t\t\t\t\t\t\tn = vcardData.find(\">\") +1\n\t\t\t\t\t\t\tvcardData = vcardData[n:]\n\t\t\t\t\t\t\tvcardData = vcardData.replace(\"</vcard>\",\"\")\n\n\t\t\t\t\t\t\tif isGroup:\n\t\t\t\t\t\t\t\tself.signalInterface.send(\"group_vcardReceived\", (msgId, fromAttribute, author, vcardName, vcardData, wantsReceipt))\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tself.signalInterface.send(\"vcard_received\", (msgId, fromAttribute, vcardName, vcardData, wantsReceipt, isBroadcast))\n\t\t\t\t\t\t\t\n\t\t\t\t\telse:\n\t\t\t\t\t\tself._d(\"Unknown media type\")\n\t\t\t\t\t\treturn\n\n\t\t\t\telif ProtocolTreeNode.tagEquals(childNode,\"body\") and msgId is not None:\n\t\t\t\t\tmsgData = childNode.data;\n\t\t\t\t\t\n\t\t\t\t\t#fmsg.setData({\"status\":0,\"key\":key.toString(),\"content\":msgdata,\"type\":WAXMPP.message_store.store.Message.TYPE_RECEIVED});\n\n\t\t\t\telif ProtocolTreeNode.tagEquals(childNode,\"received\") and fromAttribute is not None and msgId is not None:\n\n\t\t\t\t\tif fromAttribute == \"s.us\":\n\t\t\t\t\t\tself.signalInterface.send(\"profile_setStatusSuccess\", (\"s.us\", msgId,))\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\t#@@TODO autosend ack from client\n\t\t\t\t\t#print \"NEW MESSAGE RECEIVED NOTIFICATION!!!\"\n\t\t\t\t\t#self.connection.sendDeliveredReceiptAck(fromAttribute,msg_id);\n\t\t\t\t\tself.signalInterface.send(\"receipt_messageDelivered\", (fromAttribute, msgId))\n\t\t\t\t\t\n\t\t\t\t\treturn\n\n\n\t\t\t\telif not (ProtocolTreeNode.tagEquals(childNode,\"active\")):\n\t\t\t\t\tif ProtocolTreeNode.tagEquals(childNode,\"request\"):\n\t\t\t\t\t\twantsReceipt = True;\n\n\t\t\t\t\telif ProtocolTreeNode.tagEquals(childNode,\"notify\"):\n\t\t\t\t\t\tnotify_name = childNode.getAttributeValue(\"name\");\n\n\n\t\t\t\t\telif ProtocolTreeNode.tagEquals(childNode,\"delay\"):\n\t\t\t\t\t\txmlns = childNode.getAttributeValue(\"xmlns\");\n\t\t\t\t\t\tif \"urn:xmpp:delay\" == xmlns:\n\t\t\t\t\t\t\tstamp_str = childNode.getAttributeValue(\"stamp\");\n\t\t\t\t\t\t\tif stamp_str is not None:\n\t\t\t\t\t\t\t\tstamp = stamp_str\n\t\t\t\t\t\t\t\ttimestamp = self.parseOfflineMessageStamp(stamp)*1000;\n\n\t\t\t\t\telif ProtocolTreeNode.tagEquals(childNode,\"x\"):\n\t\t\t\t\t\txmlns = childNode.getAttributeValue(\"xmlns\");\n\t\t\t\t\t\tif \"jabber:x:event\" == xmlns and msgId is not None:\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif fromAttribute == \"broadcast\":\n\t\t\t\t\t\t\t\tself.signalInterface.send(\"receipt_broadcastSent\", (msgId,))\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tself.signalInterface.send(\"receipt_messageSent\", (fromAttribute, msgId))\n\n\t\t\t\t\t\telif \"jabber:x:delay\" == xmlns:\n\t\t\t\t\t\t\tcontinue; #@@TODO FORCED CONTINUE, WHAT SHOULD I DO HERE? #wtf?\n\t\t\t\t\t\t\tstamp_str = childNode.getAttributeValue(\"stamp\");\n\t\t\t\t\t\t\tif stamp_str is not None:\n\t\t\t\t\t\t\t\tstamp = stamp_str\n\t\t\t\t\t\t\t\ttimestamp = stamp;\n\t\t\t\t\telse:\n\t\t\t\t\t\tif ProtocolTreeNode.tagEquals(childNode,\"delay\") or not ProtocolTreeNode.tagEquals(childNode,\"received\") or msgId is None:\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\treceipt_type = childNode.getAttributeValue(\"type\");\n\t\t\t\t\t\t\tif receipt_type is None or receipt_type == \"delivered\":\n\t\t\t\t\t\t\t\tself.signalInterface.send(\"receipt_messageDelivered\", (fromAttribute, msgId))\n\t\t\t\t\t\t\telif receipt_type == \"visible\":\n\t\t\t\t\t\t\t\tself.signalInterface.send(\"receipt_visible\", (fromAttribute, msgId))\n\t\t\t\t\t\t\t\n\n\n\n\n\t\t\tif msgData:\n\t\t\t\tmsgData = msgData if sys.version_info < (3, 0) else msgData.encode('latin-1').decode()\n\t\t\t\tif isGroup:\n\t\t\t\t\tself.signalInterface.send(\"group_messageReceived\", (msgId, fromAttribute, author, msgData, timestamp, wantsReceipt, pushName))\n\n\t\t\t\telse:\n\t\t\t\t\tself.signalInterface.send(\"message_received\", (msgId, fromAttribute, msgData, timestamp, wantsReceipt, pushName, isBroadcast))\n\n\t\t\t\t##@@TODO FROM CLIENT\n\t\t\t\t'''if conversation.type == \"group\":\n\t\t\t\t\tif conversation.subject is None:\n\t\t\t\t\t\tsignal = False\n\t\t\t\t\t\tself._d(\"GETTING GROUP INFO\")\n\t\t\t\t\t\tself.connection.sendGetGroupInfo(fromAttribute)\n\t\t\t\t'''\n\t\t\t\t\t#if not len(conversation.getContacts()):\n\t\t\t\t\t#\tself._d(\"GETTING GROUP CONTACTS\")\n\t\t\t\t\t#\tself.connection.sendGetParticipants(fromAttribute)\n\n\t\t\t\t'''@@TODO FROM CLIENT\n\t\t\t\tif ret is None:\n\t\t\t\t\tconversation.incrementNew();\n\t\t\t\t\tWAXMPP.message_store.pushMessage(fromAttribute,fmsg)\n\t\t\t\t\tfmsg.key = key\n\t\t\t\telse:\n\t\t\t\t\tfmsg.key = eval(ret.key)\n\t\t\t\t\tduplicate = True;\n\t\t\t\t'''\n\t\t\t" }, { "alpha_fraction": 0.7224891185760498, "alphanum_fraction": 0.7231754660606384, "avg_line_length": 38.02678680419922, "blob_id": "7cc14fc6b280e705ad62fbe6c8346d1c0419623d", "content_id": "fcaf1f5ea24218fa7e58d94ef77aa5950f443a5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4371, "license_type": "no_license", "max_line_length": 123, "num_lines": 112, "path": "/BuildMessenger/src/main/java/messenger/messaging/MessageAPI.java", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "package messenger.messaging;\n\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.LinkedBlockingQueue;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport messenger.messaging.interfaces.MessageReciever;\nimport messenger.util.FileUtil;\n\npublic class MessageAPI extends Thread{\n\n private static MessageAPI messageAPI;\n\n private final List<MessageReciever> messageRecievers = new ArrayList<MessageReciever>();\n private final BlockingQueue<String> incomingMessageQueue;\n private final BlockingQueue<ComposedMessage> outgoingMessageQueue;\n private final Set<ComposedMessage> receipts;\n private final BlockingQueue<String> errorMessageQueue;\n private final MessageServerContext context;\n private final ServerMessageProducer successMessageProducer;\n private final ServerMessageProducer errorMessageProducer;\n private final ServerMessageConsumer successMessageConsumer;\n private final ServerMessageConsumer errorMessageConsumer;\n private final MessageSender messageSender;\n private final AtomicInteger fileNameInteger;\n private Process whatsAppClient;\n\n private MessageAPI() {\n incomingMessageQueue = new LinkedBlockingQueue<String>();\n outgoingMessageQueue = new LinkedBlockingQueue<ComposedMessage>();\n errorMessageQueue = new LinkedBlockingQueue<String>();\n receipts = new HashSet<ComposedMessage>();\n context = new MessageServerContext();\n OutputStream outputStream;\n try {\n \n whatsAppClient = ProcessFactory.getProcessMessageListener();\n outputStream = new FileOutputStream(context.getCommanFile());\n } catch (IOException e) {\n System.out.println(\"Could Not start WhatsApp Client\");\n e.printStackTrace();\n throw new RuntimeException(e);\n }\n context.setServerUp(true);\n successMessageProducer = new ServerMessageProducer(incomingMessageQueue, whatsAppClient.getInputStream(), context);\n errorMessageProducer = new ServerMessageProducer(errorMessageQueue, whatsAppClient.getErrorStream(), context);\n successMessageConsumer = new SuccessMessageConsumer(messageRecievers, incomingMessageQueue, context);\n errorMessageConsumer = new ErrorMessageConsumer(errorMessageQueue, context);\n messageSender = new MessageSender(outgoingMessageQueue, outputStream, context, receipts);\n fileNameInteger = new AtomicInteger();\n startThreads();\n }\n\n private void startThreads() {\n new Thread(successMessageProducer).start();\n new Thread(errorMessageProducer).start();\n new Thread(successMessageConsumer).start();\n new Thread(errorMessageConsumer).start();\n new Thread(messageSender).start();\n }\n\n public void registerMessageReciever(MessageReciever messageReciever) {\n messageRecievers.add(messageReciever);\n }\n\n public static synchronized MessageAPI getInstance() {\n if (messageAPI == null) {\n messageAPI = new MessageAPI();\n }\n return messageAPI;\n }\n\n public void killServer() throws InterruptedException {\n context.requestKill();\n outgoingMessageQueue.put(new ComposedMessage(\"\", \"\", null));\n }\n\n public boolean isListening() {\n return context.isServerListening();\n }\n\n public ComposedMessage sendMessage(List<String> numbers, String message) throws IOException, InterruptedException {\n String fileName = \"\" + fileNameInteger.incrementAndGet();\n ComposedMessage composedMessage = new ComposedMessage(fileName, message, numbers);\n fileName = Configurations.TEMP_DIR + fileName;\n\n FileUtil.writeToFile(fileName, message, false);\n outgoingMessageQueue.put(composedMessage);\n while (!receipts.contains(composedMessage))\n Thread.sleep(100);\n return composedMessage;\n }\n @Override\n public void run() {\n \tSystem.out.println(\"Destroying whatsapp Client\");\n// \twhatsAppClient.destroy();\n \ttry {\n \t\tkillServer();\n\t\t\twhatsAppClient.waitFor();\n\t\t} catch (InterruptedException e) {\n\t\t\te.printStackTrace();\n\t\t\twhatsAppClient.destroy();\n\t\t}\n }\n}\n" }, { "alpha_fraction": 0.7404844164848328, "alphanum_fraction": 0.7854671478271484, "avg_line_length": 47.33333206176758, "blob_id": "8a725deb4f9de47aa8b83998925b8874a091719b", "content_id": "0ec8cfd3ee9685929479a3b893e119fef50311ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 289, "license_type": "no_license", "max_line_length": 71, "num_lines": 6, "path": "/resources/config/Urls.properties", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "jenkins.url=http://localhost:8181/jenkins\nstatus.url={jenkins.url}/api/xml?xpath=hudson/job[name=%22{0}%22]/color\nstatusWeb.url=https://vibo.easydq.com/build.xml\nbuild.url={jenkins.url}/job/{0}/build\nbuildWithParameters.url={jenkins.url}/job/{0}/buildWithParameters{1}\nminRefreshInterval=3" }, { "alpha_fraction": 0.6673893928527832, "alphanum_fraction": 0.6721596121788025, "avg_line_length": 38.75862121582031, "blob_id": "38f306b3518f93fd703d6a91bbfe3f8b0c1e6f13", "content_id": "73e21a60d99ec0913d3acba6f50fe3bc8be7ac9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2306, "license_type": "no_license", "max_line_length": 130, "num_lines": 58, "path": "/BuildMessenger/src/main/java/messenger/controller/Controller.java", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "package messenger.controller;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport messenger.controller.configurations.Configurations;\nimport messenger.controller.dto.JobDto;\nimport messenger.controller.dto.JobsDto;\nimport messenger.controller.dto.User;\nimport messenger.jobs.JobsAPI;\nimport messenger.jobs.interfaces.StatusChangeHandler;\nimport messenger.messaging.MessageAPI;\nimport messenger.messaging.interfaces.MessageReciever;\n\npublic class Controller {\n public static void main(String[] args) throws InterruptedException {\n MessageAPI messageAPI = MessageAPI.getInstance();\n Runtime.getRuntime().addShutdownHook(messageAPI);\n JobsDto jobsDto = Configurations.getJobs();\n List<JobDto> jobList = jobsDto.getJobDtos();\n Map<JobDto, StatusChangeHandler> jobStatusChangeHandlerMap = populateJobStatusChangeHandlers(messageAPI, jobList);\n JobsAPI jobsAPI = JobsAPI.getInstance(jobStatusChangeHandlerMap);\n MessageReciever messageReciever = new JobMessageReciever(jobsAPI, messageAPI);\n messageAPI.registerMessageReciever(messageReciever);\n int timeout = 25;\n while (!messageAPI.isListening()) {\n Thread.sleep(1000);\n if (--timeout <= 0)\n {\n System.err.println(\"Could not start Message Processor\");\n messageAPI.killServer();\n return;\n }\n }\n try {\n while (messageAPI.isListening()) {\n jobsAPI.refreshAll();\n Thread.sleep(1000);\n }\n } catch (Exception e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n messageAPI.killServer();\n }\n }\n\n private static Map<JobDto, StatusChangeHandler> populateJobStatusChangeHandlers(MessageAPI messageAPI, List<JobDto> jobList) {\n Map<JobDto, StatusChangeHandler> jobStatusHandlerMap = new HashMap<JobDto, StatusChangeHandler>();\n for (JobDto jobDto : jobList) {\n List<User> users = Configurations.getRegisteredUsers(jobDto);\n if (users != null && !users.isEmpty())\n jobStatusHandlerMap.put(jobDto, new StatusChangeHandlerImpl(users, messageAPI));\n }\n return jobStatusHandlerMap;\n }\n\n}\n" }, { "alpha_fraction": 0.6241509914398193, "alphanum_fraction": 0.6293421387672424, "avg_line_length": 42.669490814208984, "blob_id": "7fcbd182e9a8af5cb0317071e8e4d81c526358a6", "content_id": "8529b6ad262239c4242d388f766edf3c9820f8f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20612, "license_type": "permissive", "max_line_length": 218, "num_lines": 472, "path": "/resources/Yowsup/Examples/Main-Cli.py", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport os, re, json\nparentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nos.sys.path.insert(0,parentdir)\nimport time, datetime, readline, cmd\nimport threading,time, base64\n\nfrom Yowsup.Common.utilities import Utilities\nfrom Yowsup.Common.debugger import Debugger\nfrom Yowsup.Common.constants import Constants\nfrom Examples.CmdClient import WhatsappCmdClient\nfrom Examples.EchoClient import WhatsappEchoClient\nfrom Examples.ListenerClient import WhatsappListenerClient\nfrom Yowsup.Registration.v1.coderequest import WACodeRequest\nfrom Yowsup.Registration.v1.regrequest import WARegRequest\nfrom Yowsup.Registration.v1.existsrequest import WAExistsRequest\nfrom Yowsup.Registration.v2.existsrequest import WAExistsRequest as WAExistsRequestV2\nfrom Yowsup.Registration.v2.coderequest import WACodeRequest as WACodeRequestV2\nfrom Yowsup.Registration.v2.regrequest import WARegRequest as WARegRequestV2\nfrom Yowsup.connectionmanager import YowsupConnectionManager\n\nCONFIG_PATH = os.path.expanduser(\"~/.whatsapp\")\nCONFIG_FILE = CONFIG_PATH + \"/config.json\"\nALIASES_FILE = CONFIG_PATH + \"/aliases.json\"\nLOG_FILE = CONFIG_PATH + \"/chat.log\"\n\nGENERAL_DOC = \"\"\"\nWhatsapp desktop client, interactive mode\n=========================================\nType '/help send' to get information on sending messages.\nType '/help alias' to get information on using aliases.\nCommands can be invoked by typing '/CMD' where CMD is one of the following.\nType '/help CMD' to get help on a command. \n\"\"\"\n\ndef readJSON(path):\n with open(path) as fp:\n return json.load(fp)\n\ndef writeJSON(path, config):\n with open(path, \"w\") as fp:\n json.dump(config, fp, indent=2)\n\n_eventBindings = {}\n \ndef bind(event):\n def wrap(func):\n _eventBindings[event] = func\n return func\n return wrap\n\nclass WhatsappClient(cmd.Cmd):\n \n def __init__(self, configFile):\n cmd.Cmd.__init__(self)\n self.prompt = \"@???:> \"\n self.identchars += \"/\"\n readline.set_completer_delims(\" \") \n \n self.configFile = configFile\n self.config = readJSON(self.configFile)\n self._loadAliases()\n self.jid = \"%[email protected]\" % self.config[\"phone\"]\n \n self.logfile = open(LOG_FILE, \"a\")\n \n connectionManager = YowsupConnectionManager()\n connectionManager.setAutoPong(True)\n self.cm = connectionManager\n self.signalsInterface = connectionManager.getSignalsInterface()\n self.methodsInterface = connectionManager.getMethodsInterface()\n for event, func in _eventBindings.iteritems():\n self.signalsInterface.registerListener(event, func.__get__(self))\n self.defaultReceiver = None\n self._login()\n \n def close(self):\n self.methodsInterface.call(\"presence_sendUnavailable\")\n self.logfile.close()\n \n def _loadAliases(self):\n if os.path.exists(ALIASES_FILE):\n self.aliases = readJSON(ALIASES_FILE)\n self.aliasesRev = dict([(self.aliases[k], k) for k in self.aliases])\n else:\n self.aliases = {}\n self.aliasesRev = {}\n \n def _saveAliases(self):\n writeJSON(ALIASES_FILE, self.aliases)\n\n def _login(self):\n self.username = self.config[\"phone\"]\n password = base64.b64decode(self.config[\"password\"])\n self.methodsInterface.call(\"auth_login\", (self.username, password))\n\n def _name2jid(self, name):\n if name in self.aliases:\n name = self.aliases[name]\n if name.startswith(\"#\"):\n return \"%[email protected]\" % name[1:]\n else:\n return \"%[email protected]\" % name\n\n def _jid2name(self, jid):\n name, server = jid.split(\"@\")\n if server == \"g.us\":\n name = \"#\" + name\n if name in self.aliasesRev:\n name = self.aliasesRev[name]\n return name\n \n def parseline(self, line):\n if not line.startswith(\"/\"):\n return (None, None, line)\n return cmd.Cmd.parseline(self, line[1:])\n \n def default(self, line):\n match = re.match(\"@([^:]*):[ ]*(.*)\", line)\n if match:\n addr, msg = match.groups()\n self.do_send(addr, msg)\n return\n match = re.match(\"@([^:]*)\", line)\n if match:\n addr = match.groups()[0]\n self.defaultReceiver = addr\n self.prompt = \"@%s:> \" % self.defaultReceiver\n return\n if line and self.defaultReceiver:\n msg = line.strip()\n self.do_send(self.defaultReceiver, msg)\n return\n print \"Warning: line ignored (type /help to see a help message)\"\n \n def postloop(self):\n print\n \n def do_EOF(self):\n return self.do_exit()\n \n def do_quit(self):\n return self.do_exit()\n\n def do_exit(self):\n self.close()\n return True\n \n def onecmd(self, line):\n cmd, args, line = self.parseline(line)\n if args:\n args = args.split()\n if line == \"EOF\":\n return self.do_EOF()\n if not line:\n return\n if not cmd:\n return self.default(line)\n if cmd == \"help\":\n return self.do_help(\" \".join(args))\n else:\n try:\n func = getattr(self, 'do_' + cmd)\n except AttributeError:\n return self.default(line)\n try:\n return func(*args)\n except Exception, exc:\n print exc\n \n def complete(self, text, nr):\n tokens = [\"/%s\" % c for c in self.completenames(\"\")]\n tokens.remove(\"/EOF\")\n for alias in self.aliases:\n tokens.append(\"@%s:\" % alias)\n tokens.append(alias)\n matching = filter(lambda t: t.startswith(text), tokens)\n return matching[nr] if len(matching) >= nr else None\n \n def do_alias(self, *args):\n \"\"\"\n Syntax: /alias alias=destination\n \n Assigns an alias to a destination.\n \n Instead of destination ids, the client can also use named aliases. If an alias exists for a\n destination id, it can be used instead of the destination id and it will be displayed on incoming\n messages.\n \"\"\"\n alias, name = (\" \".join(args)).split(\"=\")\n print alias\n print name\n if name:\n self.aliases[alias] = name\n self.aliasesRev[name] = alias\n else:\n del self.aliasesRev[self.alias[alias]]\n del self.aliases[alias]\n self._saveAliases()\n\n def do_aliases(self):\n print \", \".join([\"%s=%s\" % (k, v) for k, v in self.aliases.iteritems()])\n \n def do_group_info(self, group):\n self.methodsInterface.call(\"group_getInfo\", (self._name2jid(group),))\n\n @bind(\"group_gotInfo\")\n def onGroupInfo(self, jid, owner, subject, subjectOwner, subjectTimestamp, creationTimestamp):\n creationTimestamp = datetime.datetime.fromtimestamp(creationTimestamp).strftime('%d-%m-%Y %H:%M')\n subjectTimestamp = datetime.datetime.fromtimestamp(subjectTimestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"Information on group %s: created by %s at %s, subject '%s' set by %s at %s\" % (self._jid2name(jid), self._jid2name(owner), creationTimestamp, subject, self._jid2name(subjectOwner), subjectTimestamp))\n \n def do_group_invite(self, group, user):\n self.methodsInterface.call(\"group_addParticipant\", (self._name2jid(group), self._name2jid(user)))\n \n def do_group_kick(self, group, user):\n self.methodsInterface.call(\"group_removeParticipant\", (self._name2jid(group), self._name2jid(user)))\n \n def do_group_create(self, subject):\n self.methodsInterface.call(\"group_create\", (subject,))\n \n @bind(\"group_createSuccess\")\n def onGroupCreated(self, jid, groupJid):\n groupJid = \"%s@%s\" % (groupJid, jid) \n self._out(\"New group: %s\" % self._jid2name(groupJid))\n\n def do_group_destroy(self, group):\n self.methodsInterface.call(\"group_end\", (self._name2jid(group),))\n \n @bind(\"group_endSuccess\")\n def onGroupDestroyed(self, jid):\n pass #jid contains only \"g.us\" ????\n\n def do_group_subject(self, group, subject):\n self.methodsInterface.call(\"group_subject\", (self._name2jid(group), subject))\n \n @bind(\"group_subjectReceived\")\n def onGroupSubjectReceived(self, messageId, jid, author, subject, timestamp, wantsReceipt):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s changed subject of %s to '%s'\" % (self._jid2name(author), self._jid2name(jid), subject), timestamp)\n if wantsReceipt:\n self.methodsInterface.call(\"subject_ack\", (jid, messageId))\n\n def do_group_members(self, group):\n self.methodsInterface.call(\"group_getParticipants\", (self._name2jid(group),))\n\n @bind(\"group_gotParticipants\")\n def onGroupGotParticipants(self, groupJid, participants):\n self._out(\"Members of group %s: %s\" % (self._jid2name(groupJid), [self._jid2name(p) for p in participants]))\n \n def do_status(self, user):\n self.methodsInterface.call(\"presence_request\", (self._name2jid(user),))\n \n @bind(\"presence_updated\")\n def onPresenceUpdated(self, jid, lastseen):\n self._out(\"%s was last seen %s seconds ago\" % (self._jid2name(jid), lastseen))\n \n @bind(\"notification_groupParticipantAdded\")\n def onGroupParticipantAdded(self, groupJid, jid, author, timestamp, messageId, receiptRequested):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s added %s to %s'\" % (self._jid2name(author), self._jid2name(jid), self._jid2name(groupJid)), timestamp)\n if receiptRequested:\n self.methodsInterface.call(\"notification_ack\", (groupJid, messageId))\n \n @bind(\"notification_groupParticipantRemoved\")\n def onGroupParticipantRemoved(self, groupJid, jid, author, timestamp, messageId, receiptRequested):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s removed %s from %s'\" % (self._jid2name(author), self._jid2name(jid), self._jid2name(groupJid)), timestamp)\n if receiptRequested:\n self.methodsInterface.call(\"notification_ack\", (groupJid, messageId))\n \n @bind(\"notification_contactProfilePictureUpdated\")\n def onContactProfilePictureUpdated(self, jid, timestamp, messageId, receiptRequested):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s updated his contact picture\" % self._jid2name(jid), timestamp)\n if receiptRequested:\n self.methodsInterface.call(\"notification_ack\", (jid, messageId))\n\n @bind(\"notification_groupPictureUpdated\")\n def onGroupPictureUpdated(self, groupJid, author, timestamp, messageId, receiptRequested):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s updated the picture for group %s\" % (self._jid2name(author), self._jid2name(groupJid)), timestamp)\n if receiptRequested:\n self.methodsInterface.call(\"notification_ack\", (groupJid, messageId))\n \n @bind(\"image_received\")\n def onImageReceived(self, messageId, jid, preview, url, size, receiptRequested):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s sends an image file (size: %d, url: %s)\" % (self._jid2name(jid), size, url), timestamp)\n if receiptRequested:\n self.methodsInterface.call(\"notification_ack\", (jid, messageId))\n\n @bind(\"video_received\")\n def onVideoReceived(self, messageId, jid, preview, url, size, receiptRequested):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s sends a video file (size: %d, url: %s)\" % (self._jid2name(jid), size, url), timestamp)\n if receiptRequested:\n self.methodsInterface.call(\"notification_ack\", (jid, messageId))\n\n @bind(\"audio_received\")\n def onAudioReceived(self, messageId, jid, url, size, receiptRequested):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s sends an audio file (size: %d, url: %s)\" % (self._jid2name(jid), size, url), timestamp)\n if receiptRequested:\n self.methodsInterface.call(\"notification_ack\", (jid, messageId))\n\n @bind(\"location_received\")\n def onLocationReceived(self, messageId, jid, name, preview, latitude, longitude, receiptRequested):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s sends a location '%s' (lat: %f, long: %f)\" % (self._jid2name(jid), name, latitude, longitude), timestamp)\n if receiptRequested:\n self.methodsInterface.call(\"notification_ack\", (jid, messageId))\n\n @bind(\"vcard_received\")\n def onVCardReceived(self, messageId, jid, name, data, receiptRequested):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s sends contact information: %s\" % (self._jid2name(jid), name), timestamp)\n if receiptRequested:\n self.methodsInterface.call(\"notification_ack\", (jid, messageId))\n\n @bind(\"group_imageReceived\")\n def onGroupImageReceived(self, messageId, groupJid, author, preview, url, size, receiptRequested):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s sends an image file to %s (size: %d, url: %s)\" % (self._jid2name(author), self._jid2name(groupJid), size, url), timestamp)\n if receiptRequested:\n self.methodsInterface.call(\"notification_ack\", (groupJid, messageId))\n\n @bind(\"group_videoReceived\")\n def onGroupVideoReceived(self, messageId, groupJid, author, preview, url, size, receiptRequested):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s sends a video file to %s (size: %d, url: %s)\" % (self._jid2name(author), self._jid2name(groupJid), size, url), timestamp)\n if receiptRequested:\n self.methodsInterface.call(\"notification_ack\", (groupJid, messageId))\n\n @bind(\"group_audioReceived\")\n def onGroupAudioReceived(self, messageId, groupJid, author, url, size, receiptRequested):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s sends an audio file to %s (size: %d, url: %s)\" % (self._jid2name(author), self._jid2name(groupJid), size, url), timestamp)\n if receiptRequested:\n self.methodsInterface.call(\"notification_ack\", (groupJid, messageId))\n\n @bind(\"group_locationReceived\")\n def onGroupLocationReceived(self, messageId, groupJid, author, name, preview, latitude, longitude, receiptRequested):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s sends a location to %s: '%s' (lat: %f, long: %f)\" % (self._jid2name(author), self._jid2name(groupJid), name, latitude, longitude), timestamp)\n if receiptRequested:\n self.methodsInterface.call(\"notification_ack\", (groupJid, messageId))\n\n @bind(\"group_vcardReceived\")\n def onGroupVCardReceived(self, messageId, groupJid, author, name, data, receiptRequested):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s sends contact information to %s: %s\" % (self._jid2name(author), self._jid2name(groupJid), name), timestamp)\n if receiptRequested:\n self.methodsInterface.call(\"notification_ack\", (groupJid, messageId))\n\n def do_debug(self, debug):\n Debugger.enabled = debug.lower() in [\"true\", \"1\", \"yes\"]\n \n def do_send(self, receiver, msg):\n \"\"\"\n Syntax: /send destination message\n \n Sends a message to a destination. There are two types of destinations:\n * Users can be addressed by their phone number (with country code and without any special \n characters, e.g. 49179....)\n * Group chats can be addressed by prepending a # sign to the group chat id \n (e.g. #491...-130...)\n \n Messages can also be sent to a destination by typing:\n @DESTINATION: MESSAGE\n A default destination ca be set by typing:\n @DESTINATION\n Any text that is neither an @DESTINATION nor a command will be sent to the default destination.\n \"\"\"\n if not \"@\" in receiver:\n receiver = self._name2jid(receiver)\n self.methodsInterface.call(\"message_send\", (receiver, msg))\n self._out(\"%s -> %s: %s\" % (self._jid2name(self.jid), self._jid2name(receiver), msg), noOut=True)\n\n @bind(\"auth_success\")\n def onAuthSuccess(self, username):\n self._out(\"Logged in as %s\" % username)\n self.methodsInterface.call(\"ready\")\n self.methodsInterface.call(\"presence_sendAvailable\")\n\n @bind(\"auth_fail\")\n def onAuthFailed(self, username, err):\n self._out(\"Auth Failed!\")\n\n @bind(\"disconnected\")\n def onDisconnected(self, reason):\n self._out(\"Disconnected because %s\" %reason)\n try:\n self._login()\n except:\n pass\n\n def do_help(self, topic):\n if not topic:\n print GENERAL_DOC\n cmd.Cmd.do_help(self, topic)\n \n def _out(self, msg, timestamp=None, noOut=False):\n if not timestamp:\n timestamp = time.time()\n timestamp = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self.logfile.write(\"[%s] %s\\n\" % (timestamp, msg))\n self.logfile.flush()\n if not noOut:\n print \"[%s] %s\" % (timestamp, msg)\n \n @bind(\"message_received\")\n def onMessageReceived(self, messageId, jid, messageContent, timestamp, wantsReceipt, pushName):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s: %s\" % (self._jid2name(jid), messageContent), timestamp)\n if wantsReceipt:\n self.methodsInterface.call(\"message_ack\", (jid, messageId))\n \n @bind(\"group_messageReceived\")\n def onGroupMessageReceived(self, messageId, jid, author, messageContent, timestamp, wantsReceipt, pushName):\n formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M')\n self._out(\"%s -> %s: %s\" % (self._jid2name(author), self._jid2name(jid), messageContent), timestamp)\n if wantsReceipt:\n self.methodsInterface.call(\"message_ack\", (jid, messageId))\n \n @bind(\"presence_available\")\n def onPresenceAvailable(self, jid):\n self._out(\"%s is now available\" % self._jid2name(jid))\n \n @bind(\"presence_unavailable\")\n def onPresenceUnavailable(self, jid):\n self._out(\"%s is now unavailable\" % self._jid2name(jid))\n\n\ndef configure(CONFIG_FILE):\n phoneNumber = raw_input(\"Phone number (without country code, no leading 0): \")\n countryCode = raw_input(\"Country code (no leading +): \")\n phone = countryCode + phoneNumber\n password = raw_input(\"Password (base64 encoded, leave empty to register): \")\n if not password:\n identity = raw_input(\"Identity (leave empty if unknown): \") or \"0000000000\"\n method = raw_input(\"Verification method (sms or voice): \") or \"sms\"\n req = WACodeRequestV2(countryCode, phoneNumber, identity, method)\n res = req.send()\n print \"-\"*25\n print res\n print \"-\"*25\n code = raw_input(\"Received verification code: \")\n code = \"\".join(code.split('-'))\n req = WARegRequestV2(countryCode, phoneNumber, code, identity)\n res = req.send()\n print \"-\"*25\n print res\n print \"-\"*25\n password = res[\"pw\"]\n config = {\"phone\": phone, \"password\": password}\n writeJSON(CONFIG_FILE, config)\n \nif __name__ == \"__main__\":\n if not os.path.exists(CONFIG_PATH):\n os.mkdir(CONFIG_PATH)\n if not os.path.exists(CONFIG_FILE):\n configure(CONFIG_FILE)\n wa = WhatsappClient(CONFIG_FILE)\n print GENERAL_DOC\n try:\n wa.cmdloop()\n except:\n import traceback\n traceback.print_exc()\n wa.close()\n" }, { "alpha_fraction": 0.8205128312110901, "alphanum_fraction": 0.8205128312110901, "avg_line_length": 25, "blob_id": "9b1022d6fb9c2d164f0d674c8dd1dd2ad0f5ed1b", "content_id": "d05f54d920299516fca0863c952d0f3b3050e4b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 156, "license_type": "no_license", "max_line_length": 76, "num_lines": 6, "path": "/BuildMessenger/src/main/java/messenger/messaging/interfaces/MessageReciever.java", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "package messenger.messaging.interfaces;\n\npublic interface MessageReciever {\n\n\tpublic void commandRecieved(String from, String message, String messageId);\n}\n" }, { "alpha_fraction": 0.7007919549942017, "alphanum_fraction": 0.7058141827583313, "avg_line_length": 25.146465301513672, "blob_id": "98353e7d44632a8041e1673fb2b43c4f09a59b40", "content_id": "e08406d09db81703850b1e8c40026412b008cc99", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5177, "license_type": "permissive", "max_line_length": 99, "num_lines": 198, "path": "/resources/Yowsup/Yowsup/Common/Http/warequest.py", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "'''\nCopyright (c) <2012> Tarek Galal <[email protected]>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this\nsoftware and associated documentation files (the \"Software\"), to deal in the Software\nwithout restriction, including without limitation the rights to use, copy, modify,\nmerge, publish, distribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\nINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR\nA PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\nCONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\nOR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n'''\n\nimport urllib,sys, os\n\nif sys.version_info < (3, 0):\n\timport httplib\n\tfrom urllib import urlencode\n# else:\n# \tfrom http import client as httplib\n# \tfrom urllib.parse import urlencode\n\nimport hashlib\nfrom .waresponseparser import ResponseParser\nfrom Yowsup.Common.debugger import Debugger as WADebug\nfrom Yowsup.Common.constants import Constants\nfrom Yowsup.Common.utilities import Utilities\n\nclass WARequest(object):\n\n\tOK = 200\n\n\t#moved to Constants\n\n\tdef __init__(self):\n\t\tWADebug.attach(self)\n\n\t\tself.pvars = [];\n\t\tself.port = 443;\n\t\tself.type = \"GET\"\n\t\tself.parser = None\n\t\tself.params = []\n\t\tself.headers = {}\n\n\t\tself.sent = False\n\t\tself.response = None\n\n\n\n\tdef setParsableVariables(self, pvars):\n\t\tself.pvars = pvars;\n\n\tdef onResponse(self, name, value):\n\t\tif name == \"status\":\n\t\t\tself.status = value\n\t\telif name == \"result\":\n\t\t\tself.result = value\n\n\tdef addParam(self,name,value):\n\t\tself.params.append((name,value.encode('utf-8')))\n\n\tdef removeParam(self, name):\n\t\tfor i in range(0, len(self.params)):\n\t\t\tif self.params[i][0] == name:\n\t\t\t\tdel self.params[i]\n\n\n\tdef addHeaderField(self, name, value):\n\t\tself.headers[name] = value;\n\n\tdef clearParams(self):\n\t\tself.params = []\n\n\tdef getUserAgent(self):\n\n\t\ttokenData = Utilities.readToken()\n\n\t\tif tokenData:\n\t\t\tagent = tokenData[\"u\"]\n\t\telse:\n\t\t\tagent = Constants.tokenData[\"u\"]\n\t\treturn agent\n\n\tdef getToken(self, phone, token):\n\t\treturn hashlib.md5(token.format(phone=phone).encode()).hexdigest()\n\n\tdef send(self, parser = None):\n\n\t\tif self.type == \"POST\":\n\t\t\treturn self.sendPostRequest(parser)\n\n\t\treturn self.sendGetRequest(parser)\n\n\tdef setParser(self, parser):\n\t\tif isinstance(parser, ResponseParser):\n\t\t\tself.parser = parser\n\t\telse:\n\t\t\tself._d(\"Invalid parser\")\n\n\tdef getConnectionParameters(self):\n\n\t\tif not self.url:\n\t\t\treturn (\"\", \"\", self.port)\n\n\t\ttry:\n\t\t\turl = self.url.split(\"://\", 1)\n\t\t\turl = url[0] if len(url) == 1 else url[1]\n\n\t\t\thost, path = url.split('/', 1)\n\t\texcept ValueError:\n\t\t\thost = url\n\t\t\tpath = \"\"\n\n\t\tpath = \"/\" + path\n\n\t\treturn (host, self.port, path)\n\n\tdef sendGetRequest(self, parser = None):\n\t\tself.response = None\n\t\tparams = self.params#[param.items()[0] for param in self.params];\n\n\t\tparser = parser or self.parser or ResponseParser()\n\n\t\theaders = dict(list({\"User-Agent\":self.getUserAgent(),\n\t\t\t\t\"Accept\": parser.getMeta()\n\t\t\t}.items()) + list(self.headers.items()));\n\n\t\thost,port,path = self.getConnectionParameters()\n\t\tself.response = WARequest.sendRequest(host, port, path, headers, params, \"GET\")\n\n\t\tif not self.response.status == WARequest.OK:\n\t\t\tself._d(\"Request not success, status was %s\"%self.response.status)\n\t\t\treturn {}\n\n\t\tdata = self.response.read()\n\t\tself._d(data);\n\n\t\tself.sent = True\n\t\treturn parser.parse(data.decode(), self.pvars)\n\n\tdef sendPostRequest(self, parser = None):\n\t\tself.response = None\n\t\tparams = self.params #[param.items()[0] for param in self.params];\n\n\t\tparser = parser or self.parser or ResponseParser()\n\n\t\theaders = dict(list({\"User-Agent\":self.getUserAgent(),\n\t\t\t\t\"Accept\": parser.getMeta(),\n\t\t\t\t\"Content-Type\":\"application/x-www-form-urlencoded\"\n\t\t\t}.items()) + list(self.headers.items()));\n\n\t\thost,port,path = self.getConnectionParameters()\n\t\tself.response = WARequest.sendRequest(host, port, path, headers, params, \"POST\")\n\n\n\t\tif not self.response.status == WARequest.OK:\n\t\t\tself._d(\"Request not success, status was %s\"%self.response.status)\n\t\t\treturn {}\n\n\t\tdata = self.response.read()\n\n\t\tself._d(data);\n\n\t\tself.sent = True\n\t\treturn parser.parse(data.decode(), self.pvars)\n\n\n\t@staticmethod\n\tdef sendRequest(host, port, path, headers, params, reqType=\"GET\"):\n\n\t\tparams = urlencode(params);\n\n\n\t\tpath = path + \"?\"+ params if reqType == \"GET\" and params else path\n\n\t\tif len(headers):\n\t\t\tWADebug.stdDebug(headers)\n\t\tif len(params):\n\t\t\tWADebug.stdDebug(params)\n\n\t\tWADebug.stdDebug(\"Opening connection to %s\" % host);\n\n\t\tconn = httplib.HTTPSConnection(host ,port) if port == 443 else httplib.HTTPConnection(host ,port)\n\n\t\tWADebug.stdDebug(\"Sending %s request to %s\" % (reqType, path))\n\t\tconn.request(reqType, path, params, headers);\n\n\t\tresponse = conn.getresponse()\n\n\t\treturn response\n" }, { "alpha_fraction": 0.7368420958518982, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 18.052631378173828, "blob_id": "a36b32a129485a8c2699ec9354b464414e3530fa", "content_id": "267ee1c010aa89a0f1493c5dad5e751b78f8ef0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 361, "license_type": "no_license", "max_line_length": 46, "num_lines": 19, "path": "/BuildMessenger/src/main/java/messenger/jobs/interfaces/StatusChangeEvent.java", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "package messenger.jobs.interfaces;\n\nimport java.util.Date;\n\npublic interface StatusChangeEvent {\n\n public abstract String getFrom();\n\n public abstract String getJobId();\n\n public abstract String getTo();\n\n public abstract Date getPrevStatusTime();\n\n public abstract Date getCurrStatusTime();\n \n public abstract String getChangeMessage();\n\n}" }, { "alpha_fraction": 0.6184210777282715, "alphanum_fraction": 0.6184210777282715, "avg_line_length": 14, "blob_id": "f65f4d86efc343454450decc75c6a777e60b34f6", "content_id": "1524c9538401a8883388eb023b623dd58921ff8b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 76, "license_type": "permissive", "max_line_length": 18, "num_lines": 5, "path": "/resources/Yowsup/test.py", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "text=raw_input()\nif text == \"Done\":\n\tprint(\"Done\")\nelse:\n\tprint(\"NotDone\")\n\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 16.81818199157715, "blob_id": "0e78f3d095b87ba836c30475d00301b049b85d3f", "content_id": "74d549907d9650ab271b31bedc0f3b0d2ceb31d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 392, "license_type": "no_license", "max_line_length": 48, "num_lines": 22, "path": "/BuildMessenger/src/main/java/messenger/dto/JobsDto.java", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "package messenger.dto;\n\nimport java.util.List;\n\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\n\n@XmlRootElement(name=\"SupportedJobs\")\npublic class JobsDto{\n\n\tList<JobDto> jobDtos;\n\t\n\t@XmlElement(name=\"Job\")\n\tpublic List<JobDto> getJobDtos() {\n\t\treturn jobDtos;\n\t}\n\n\n\tpublic void setJobDtos(List<JobDto> jobDtos) {\n\t\tthis.jobDtos = jobDtos;\n\t}\n}\n" }, { "alpha_fraction": 0.5889894366264343, "alphanum_fraction": 0.5889894366264343, "avg_line_length": 29.837209701538086, "blob_id": "1c5e2ed4de979cb26d373e664e98344f37b1d98c", "content_id": "94cce2e5f2d1ad855ef1f064caebf4791a1b2ed9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1326, "license_type": "no_license", "max_line_length": 118, "num_lines": 43, "path": "/BuildMessenger/src/main/java/messenger/messaging/ServerMessageProducer.java", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "package messenger.messaging;\n\nimport java.io.BufferedReader;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.concurrent.BlockingQueue;\n\npublic class ServerMessageProducer implements Runnable {\n\n private BlockingQueue<String> queue;\n private InputStream inputStream;\n private MessageServerContext context;\n\n public ServerMessageProducer(BlockingQueue<String> queue, InputStream inputStream, MessageServerContext context) {\n super();\n this.queue = queue;\n this.inputStream = inputStream;\n this.context = context;\n }\n\n @Override\n public void run() {\n try {\n BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));\n String str;\n while (!context.isRequestedToKill() && !Thread.interrupted()) {\n if (br.ready()) {\n str = br.readLine();\n System.out.println(\"MessageFromServer:\" + str);\n queue.put(str);\n// System.out.println(\"Producer:\" + queue);\n }\n }\n br.close();\n queue.put(\"\");\n System.out.println(\"Killing \" + this);\n } catch (Exception e) {\n e.printStackTrace();\n new RuntimeException(e);\n }\n }\n\n}\n" }, { "alpha_fraction": 0.6028369069099426, "alphanum_fraction": 0.6043566465377808, "avg_line_length": 34.890907287597656, "blob_id": "fc52d2f5bab92195fbf601c8d18a8d4a8533b649", "content_id": "f9737063a5e23c8484c9dd8fe97deef070307fdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1974, "license_type": "no_license", "max_line_length": 134, "num_lines": 55, "path": "/BuildMessenger/src/main/java/messenger/messaging/SuccessMessageConsumer.java", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "package messenger.messaging;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.concurrent.BlockingQueue;\n\nimport messenger.messaging.interfaces.MessageReciever;\nimport messenger.util.FileUtil;\n\npublic class SuccessMessageConsumer extends ServerMessageConsumer {\n\n private List<MessageReciever> messageRecievers;\n private MessageServerContext context;\n\n public SuccessMessageConsumer(List<MessageReciever> messageRecievers, BlockingQueue<String> queue, MessageServerContext context) {\n super(queue, context);\n this.messageRecievers = messageRecievers;\n this.context = context;\n }\n\n @Override\n protected void consume(String rawMessage) {\n// System.out.println(\"Rawmessage:\" + rawMessage);\n if (!rawMessage.equals(\"\")) {\n if (rawMessage.startsWith(\"Disconnected because\")) {\n context.setAuthed(false);\n context.setServerUp(false);\n throw new RuntimeException(\"Disconnected:\" + rawMessage);\n }\n if (!context.isAuthed()) {\n if (rawMessage.contains(\"Authed\")) {\n context.setAuthed(true);\n System.out.println(\"Message Lisetner started.\");\n }\n return;\n }\n String fileName = rawMessage.substring(rawMessage.lastIndexOf('\\\\') + 1);\n System.out.println(fileName);\n String[] split = fileName.split(\"_\");\n String from = split[1];\n String messageId = split[2];\n String message;\n try {\n message = FileUtil.readFile(rawMessage);\n FileUtil.deleteFile(rawMessage);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n for (MessageReciever messageReciver : messageRecievers) {\n messageReciver.commandRecieved(from, message, messageId);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.7088644504547119, "alphanum_fraction": 0.712920069694519, "avg_line_length": 32.843135833740234, "blob_id": "b8253263a4fbfa125e03a7471c54636a7b8ced01", "content_id": "a478c7d52ef62c5025d5a8d4f3d53b698e350817", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6904, "license_type": "permissive", "max_line_length": 109, "num_lines": 204, "path": "/resources/Yowsup/Examples/ListenerClient.py", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "'''\nCopyright (c) <2012> Tarek Galal <[email protected]>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this\nsoftware and associated documentation files (the \"Software\"), to deal in the Software\nwithout restriction, including without limitation the rights to use, copy, modify,\nmerge, publish, distribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\nINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR\nA PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\nCONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\nOR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n'''\n\nimport os\nparentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nos.sys.path.insert(0,parentdir)\nimport datetime, sys\nimport time\nimport traceback\nimport threading\nfrom Examples.stracktrace import trace_start\n\nif sys.version_info >= (3, 0):\n\traw_input = input\n\nfrom Yowsup.connectionmanager import YowsupConnectionManager\n\nclass WhatsappListenerClient:\n\n\tdef startConnection(self):\n\t\ttrace_start(\"trace.html\")\n\t\tconnectionManager = YowsupConnectionManager()\n\t\tconnectionManager.setAutoPong(True)\n\n\t\tself.signalsInterface = connectionManager.getSignalsInterface()\n\t\tself.methodsInterface = connectionManager.getMethodsInterface()\n\n\t\tself.signalsInterface.registerListener(\"message_received\", self.onMessageReceived)\n\t\tself.signalsInterface.registerListener(\"auth_success\", self.onAuthSuccess)\n\t\tself.signalsInterface.registerListener(\"auth_fail\", self.onAuthFailed)\n\t\tself.signalsInterface.registerListener(\"disconnected\", self.onDisconnected)\n\t\tself.signalsInterface.registerListener(\"receipt_messageSent\", self.onMessageSent)\n\t\tself.signalsInterface.registerListener(\"ping\", self.onPing)\n\t\tself.gotReceipt = 0\n\t\tself.cm = connectionManager\n\t\tself.fileName=\"defaultFileName\"\n\n\tdef __init__(self, resourceLocation):\n\t\tself.firstConnection = True\n\t\tself.resourceLocation = resourceLocation\n\t\tself.lock = threading.Lock()\n\t\tself.startConnection()\n\n\tdef checkAndMakeConnection(self):\n\t\twhile not self.authed:\n\t\t\t# print(\"Not Connected\")\n\t\t\tself.lock.acquire()\n\t\t\tif not self.authorizing and not self.authed:\n\t\t\t\tself.methodsInterface.call(\"auth_login\", (self.username, self.password))\n\t\t\t\tself.authorizing = True\n\t\t\t# print(\"Authorizing\")\n\t\t\ttime.sleep(1)\n\t\t\tself.lock.release()\n\n\tdef login(self, username, password):\n\t\tself.username = username\n\t\tself.password = password\n\t\tself.authed = False\n\t\t#commandFile=\"/home/deepak/HI/WS_BuildMessenger/BuildMessenger/src/main/resources/commandFile\"\n\t\tcommandFile=\"%s/tmp/commandFile\"%self.resourceLocation\n\t\tself.commandFileObj=open(commandFile)\n\t\tdone = False\n\t\tself.authorizing = False\n\t\tself.checkAndMakeConnection()\n\t\twhile not done:\n\t\t\tinputLine = self.commandFileObj.readline()\n\t\t\tif not inputLine:\n\t\t\t\ttime.sleep(1)\n\t\t\t\tself.checkAndMakeConnection()\n\t\t\t\tcontinue\n\t\t\t#logfileName=\"/home/deepak/HI/WS_BuildMessenger/BuildMessenger/src/main/resources/log\"\n\t\t\tif inputLine == \"Done\":\n\t\t\t\tdone = True\n\t\t\t\tself.methodsInterface.call(\"disconnect\",(\"Exiting\"))\n\t\t\t\tcontinue\n\t\t\t# print(inputLine)\n\t\t\tinputLine=inputLine.split(\"\\n\",1)[0]\n\t\t\t# print(inputLine)\n\t\t\tsplits=inputLine.split('|',1)\n\t\t\tself.fileName=\"%s/tmp/%s\"%(self.resourceLocation,splits[0])\n\t\t\ttarget=splits[1]\n\t\t\tfobj=open(self.fileName,\"r+\")\n\t\t\tmessage=fobj.read()\n\t\t\tnow_text = datetime.datetime.now().strftime(\"%c\")\n\t\t\tlogfileName=\"%s/logs/To.log\"%self.resourceLocation\n\t\t\tlogFileObj=open(logfileName,\"a+\")\n\t\t\tlogFileObj.write(\"------------------------------------\\n\")\n\t\t\tlogFileObj.write(\"To:%s:\\t At: %s\\nMessage:\\n%s\\n\"%(target,now_text,message))\n\t\t\tlogFileObj.write(\"------------------------------------\\n\")\n\t\t\tlogFileObj.close()\n\t\t\tfobj.seek(0)\n\t\t\tfobj.truncate()\n\t\t\tfobj.close()\n\t\t\t#print(target)\n\t\t\tif '-' in target:\n\t\t\t\tjids = [\"%[email protected]\" % target]\n\t\t\telse:\n\t\t\t\tjids = [\"%[email protected]\" % t for t in target.split(',')]\n\n\t\t\t#print(jids)\n\t\t\tlength = len(jids)\n\t\t\ti = 0\n\t\t\twhile i < length:\n\t\t\t\tself.checkAndMakeConnection()\n\t\t\t\t# print(\"Sending Message\")\n\t\t\t\tself.methodsInterface.call(\"message_send\", (jids[i], message))\n\t\t\t\ti+=1\n\t\t\t#print(\"Sent message\")\n\t\t\t#if self.waitForReceipt:\n\t\t\ttimeout = 5\n\t\t\tt = 0;\n\t\t\tself.lock.acquire()\n\t\t\tself.gotReceipt = 0\n\t\t\tself.lock.release()\n\t\t\twhile t < timeout and self.gotReceipt < length:\n\t\t\t\ttime.sleep(1)\n\t\t\t\tt+=1\n\t\t\tfobj=open(self.fileName,\"a+\")\n\t\t\trecieptResult=\"Done\"\n\t\t\tif self.gotReceipt < length:\n\t\t\t\trecieptResult=\"Timed Out\"\n\t\t\tfobj.write(recieptResult)\n\t\t\tfobj.close()\n\t\tself.commandFileObj.close()\n\n\tdef onAuthSuccess(self, username):\n\t\tif self.firstConnection:\n\t\t\tprint(\"Authed %s\" % username)\n\t\t\tsys.stdout.flush()\n\t\t\tself.firstConnection = False\n\t\t# self.methodsInterface.call(\"ready\")\n\t\tself.lock.acquire()\n\t\tself.authed = True\n\t\tself.authorizing = False\n\t\tself.lock.release()\n\n\n\tdef onAuthFailed(self, username, err):\n\t\tself.lock.acquire()\n\t\tprint(\"Auth Failed!\")\n\t\tsys.stdout.flush()\n\t\tself.authed = True\n\t\tself.authorizing = False\n\t\tself.lock.release()\n\n\tdef onDisconnected(self, reason):\n\t\tself.lock.acquire()\n\t\tif reason == \"Exiting\":\n\t\t\tprint(\"Disconnected because %s\" %reason)\n\t\t# traceback.print_stack()\n\t\tsys.stdout.flush()\n\t\tself.authed=False\n\t\tself.authorizing = False\n\t\tself.lock.release()\n\n\tdef onMessageSent(self, jid, messageId):\n\t\tprint(\"Message Sent\")\n\t\treportContent=\"Jid_MessageID:%s_%s\\n\"%(jid,messageId)\n\t\tfobj=open(self.fileName,\"a+\")\n\t\tfobj.write(reportContent)\n\t\tfobj.close()\n\t\tself.gotReceipt+=1\n\n\tdef onMessageReceived(self, messageId, jid, messageContent, timestamp, wantsReceipt, pushName, isBroadCast):\n\t##\t\tprint(\"On messageReceived \")\n\t##\t\tprint(\"TimeStamp:%s\"%timestamp)\n\t##\t\tsentTime=datetime.datetime.fromtimestamp(timestamp)\n\t##\t\tprint(sentTime)\n\t##\t\tprint(sentTime.strftime('%s'))\n\t\tself.methodsInterface.call(\"message_ack\", (jid, messageId))\n\t\tfileName=\"%s/tmp/%s_%s_%s\"%(self.resourceLocation,timestamp,jid.split(\"@\",1)[0],messageId)\n\t\tfobj=open(fileName,\"w\")\n\t\tfobj.write(messageContent)\n\t\tfobj.close()\n\t\tlogfileName=\"%s/logs/From.log\"%self.resourceLocation\n\t\tlogFileObj=open(logfileName,\"a+\")\n\t\tlogFileObj.write(\"------------------------------------\\n\")\n\t\tnow_text = datetime.datetime.now().strftime(\"%c\")\n\t\tlogFileObj.write(\"From:%s:\\t At: %s\\nMessage:\\n%s\\n\"%(jid.split(\"@\",1)[0],now_text,messageContent))\n\t\tlogFileObj.write(\"------------------------------------\\n\")\n\t\tlogFileObj.close()\n\t\tprint(os.path.abspath(fobj.name))\n\t\tsys.stdout.flush()\n\n\tdef onPing(pingId):\n\t\tself.methodsInterface.call(\"pong\", pingId)\n" }, { "alpha_fraction": 0.5879501104354858, "alphanum_fraction": 0.5879501104354858, "avg_line_length": 20.55223846435547, "blob_id": "6315f06cd5d675dcdd09719f4c2dbb08c3c20e04", "content_id": "f3741fb477c7d4cae2877c0f0eacf6ca5ccd5ccb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1444, "license_type": "no_license", "max_line_length": 74, "num_lines": 67, "path": "/BuildMessenger/src/main/java/messenger/controller/dto/JobDto.java", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "package messenger.controller.dto;\n\nimport javax.xml.bind.annotation.XmlElement;\n\npublic class JobDto {\n\n private String jobId;\n \n private boolean isParameterizedJob;\n\n @XmlElement(name = \"JobId\")\n public String getJobId() {\n return jobId;\n }\n\n public void setJobId(String jobId) {\n this.jobId = jobId;\n }\n\n\n \n @Override\n public int hashCode() {\n // TODO Auto-generated method stub\n return this.jobId.length();\n }\n \n @Override\n public boolean equals(Object obj) {\n if (obj instanceof JobDto) {\n JobDto jobObject = (JobDto) obj;\n return jobObject.getJobId().equalsIgnoreCase(this.getJobId());\n }\n return false;\n }\n // public void setName(String name) {\n // this.name = name;\n // }\n // public void setNumber(String number) {\n // this.number = number;\n // }\n //\n //\n //\n // @XmlElement(name=\"Name\")\n // public String getName() {\n // return name;\n // }\n //\n // @XmlElement(name=\"Number\")\n // public String getNumber() {\n // return number;\n // }\n @Override\n public String toString() {\n return jobId;\n }\n\n @XmlElement(name = \"IsParameterizedJob\")\n public boolean isParameterizedJob() {\n return isParameterizedJob;\n }\n\n public void setParameterizedJob(boolean isParameterizedJob) {\n this.isParameterizedJob = isParameterizedJob;\n }\n}\n" }, { "alpha_fraction": 0.5683202743530273, "alphanum_fraction": 0.5687554478645325, "avg_line_length": 38.620689392089844, "blob_id": "917a52aa3343ae6bdb6b2fdcd686f511de00d1dc", "content_id": "a7b7d109c28d545fcfc1eff0342ef46189fa1a38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2298, "license_type": "no_license", "max_line_length": 147, "num_lines": 58, "path": "/BuildMessenger/src/main/java/messenger/util/HttpUtil.java", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "package messenger.util;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\n\nimport javax.xml.xpath.XPath;\nimport javax.xml.xpath.XPathExpressionException;\nimport javax.xml.xpath.XPathFactory;\n\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.client.methods.HttpUriRequest;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.util.EntityUtils;\nimport org.xml.sax.InputSource;\n\npublic class HttpUtil {\n\n public static String getResponse(String[] urls, String jobName) throws IOException {\n String status = \"\";\n for (int i = 0; i < urls.length; i++) {\n try {\n String url = urls[i];\n\n if (status.equals(\"\") && url.contains(\"api/xml\")) {\n HttpClient client = HttpClientBuilder.create().build();\n System.out.println(url);\n HttpUriRequest request = new HttpGet(url);\n HttpResponse httpResponse = client.execute(request);\n status = EntityUtils.toString(httpResponse.getEntity());\n\n }\n else\n {\n System.out.println(url);\n HttpClient client = HttpClientBuilder.create().build();\n HttpUriRequest request = new HttpGet(url);\n HttpResponse httpResponse = client.execute(request);\n XPathFactory factory = XPathFactory.newInstance();\n XPath xPath = factory.newXPath();\n InputSource inputSource = new InputSource(new ByteArrayInputStream(EntityUtils.toString(httpResponse.getEntity()).getBytes()));\n String evaluate = \"\";\n try {\n evaluate = xPath.evaluate(\"/hudson/job[name='\" + jobName + \"']/color\", inputSource);\n status = evaluate.trim();\n } catch (XPathExpressionException e) {\n e.printStackTrace();\n }\n }\n } catch (Exception e) {\n // TODO Auto-generated catch block\n e.getMessage();\n }\n }\n return status;\n }\n}\n" }, { "alpha_fraction": 0.7319587469100952, "alphanum_fraction": 0.7319587469100952, "avg_line_length": 18.399999618530273, "blob_id": "306b052c9f0eb3c23fdcc3f054fedf81067bb8fe", "content_id": "48bfd8044ebbefde75b146eec854933d3ed7b231", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 97, "license_type": "no_license", "max_line_length": 45, "num_lines": 5, "path": "/BuildMessenger/src/main/java/messenger/jobs/JobStatus.java", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "package messenger.jobs;\n\npublic enum JobStatus {\n OFF, SUCCESS, FAILURE, PROGRESS, UNKNOWN \n}\n" }, { "alpha_fraction": 0.636112630367279, "alphanum_fraction": 0.636112630367279, "avg_line_length": 28.20967674255371, "blob_id": "aaccc93ecfb9f367caa5ad4bb6e51249bcefab65", "content_id": "4ca747383800540d44fa0ae30669791f91b2bb6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1811, "license_type": "no_license", "max_line_length": 96, "num_lines": 62, "path": "/BuildMessenger/src/main/java/messenger/controller/configurations/Configurations.java", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "package messenger.controller.configurations;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.xml.bind.JAXBException;\n\nimport messenger.controller.dto.JobDto;\nimport messenger.controller.dto.JobsDto;\nimport messenger.controller.dto.User;\nimport messenger.controller.dto.Users;\nimport messenger.util.FileUtil;\n\npublic class Configurations {\n\n private final static String CONFIG_DIR = new File(\"../resources/config/\").getAbsolutePath();\n private static final String USER_XML = CONFIG_DIR + \"/Users.xml\";\n private static final String JOB_XML = CONFIG_DIR + \"/Jobs.xml\";\n private final static Users users;\n private final static JobsDto jobsDto;\n\n static {\n try {\n users = (Users) FileUtil.readXml(USER_XML, Users.class);\n jobsDto = (JobsDto) FileUtil.readXml(JOB_XML, JobsDto.class);\n } catch (JAXBException e) {\n e.printStackTrace();\n throw new IllegalStateException(e.getMessage());\n }\n }\n\n public static User getUser(String number) {\n List<User> list = users.getUsers();\n for (User user : list) {\n if (user.getNumber().equals(number)) {\n return user;\n }\n }\n return null;\n }\n\n public static List<User> getRegisteredUsers(JobDto jobDto) {\n List<User> list = users.getUsers();\n List<User> registered = new ArrayList<User>();\n for (User user : list) {\n if (user.getRegisteredJobs().contains(jobDto)) {\n registered.add(user);\n }\n }\n return registered;\n }\n\n public static JobsDto getJobs() {\n return jobsDto;\n }\n\n\tpublic static String getDefaultJob(User user) {\n\t\treturn user.getRegisteredJobs().iterator().next().getJobId();\n\t}\n\n}\n" }, { "alpha_fraction": 0.7615384459495544, "alphanum_fraction": 0.7615384459495544, "avg_line_length": 31.5, "blob_id": "40c5633341e0b59323f738b4f7bd67a854065a51", "content_id": "eb7b97b14fd465455029891ada303709a68fb0c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 130, "license_type": "no_license", "max_line_length": 98, "num_lines": 4, "path": "/README.md", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "BuildMessenger\n==============\n\nBuildMessenger is a notification and communication tool between jenkins server and whatsapp users.\n" }, { "alpha_fraction": 0.6440251469612122, "alphanum_fraction": 0.6440251469612122, "avg_line_length": 19.384614944458008, "blob_id": "85a3fefef65e18197cb4f94d861c797fc1f4336c", "content_id": "ff80ff6c992e501dc3d8006a7203629576f49fc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 795, "license_type": "no_license", "max_line_length": 63, "num_lines": 39, "path": "/BuildMessenger/src/main/java/messenger/controller/dto/User.java", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "package messenger.controller.dto;\n\nimport java.util.Set;\n\nimport javax.xml.bind.annotation.XmlElement;\n\npublic class User {\n\n private String number;\n private String name;\n private Set<JobDto> registeredJobs;\n\n public void setName(String name) {\n this.name = name;\n }\n\n public void setRegisteredJobs(Set<JobDto> registeredJobs) {\n this.registeredJobs = registeredJobs;\n }\n\n public void setNumber(String number) {\n this.number = number;\n }\n\n @XmlElement(name = \"Name\")\n public String getName() {\n return name;\n }\n\n @XmlElement(name = \"Number\")\n public String getNumber() {\n return number;\n }\n\n @XmlElement(name = \"RegisteredJob\")\n public Set<JobDto> getRegisteredJobs() {\n return registeredJobs;\n }\n}\n" }, { "alpha_fraction": 0.686274528503418, "alphanum_fraction": 0.686274528503418, "avg_line_length": 13.068965911865234, "blob_id": "7b9df38b251ce4c9880882bf9e3f2f3777e1c100", "content_id": "6bc405330ba18cda44aca8e1fbdbc3cc852cd7bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 408, "license_type": "no_license", "max_line_length": 44, "num_lines": 29, "path": "/BuildMessenger/src/main/java/messenger/dto/User.java", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "package messenger.dto;\n\nimport javax.xml.bind.annotation.XmlElement;\n\n\n\npublic class User {\n\t\n\tString number;\n\tString name;\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\tpublic void setNumber(String number) {\n\t\tthis.number = number;\n\t}\n\t\n\t\n\t\n\t@XmlElement(name=\"Name\")\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\t\n\t@XmlElement(name=\"Number\")\n\tpublic String getNumber() {\n\t\treturn number;\n\t}\n}\n" }, { "alpha_fraction": 0.6794509291648865, "alphanum_fraction": 0.6851029396057129, "avg_line_length": 35.970149993896484, "blob_id": "37a5dafd94f6e26959ec4290ae59925266170e6d", "content_id": "e6cacd8a7aae8df85f5a31092e6c3abf76103649", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2477, "license_type": "no_license", "max_line_length": 134, "num_lines": 67, "path": "/BuildMessenger/src/main/java/messenger/jobs/JenkinsConfiguration.java", "repo_name": "deepubansal/BuildMessenger-Python-Whatsapp-JenkinsAPI", "src_encoding": "UTF-8", "text": "package messenger.jobs;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.text.MessageFormat;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport messenger.util.XProperties;\n\npublic class JenkinsConfiguration\n{\n\n // private static final String buildURL =\n // \"http://localhost:8181/jenkins/job/Build%20Local/build\";\n // private static final String statusURL =\n // \"http://localhost:8181/jenkins/api/xml?xpath=hudson/job[name=\\\"Build Local\\\"]/color/text()\";\n private static final String buildURL;\n private static final String buildWithParametersURL;\n private static final String statusURL;\n private static final String statusWebURL;\n private static Properties properties = null;\n private final static String CONFIG_DIR = new File(\"../resources/config/\").getAbsolutePath();\n\n static {\n try {\n properties = new XProperties();\n properties.load(new FileInputStream(new File(CONFIG_DIR + \"/Urls.properties\")));\n buildURL = properties.getProperty(\"build.url\");\n buildWithParametersURL = properties.getProperty(\"buildWithParameters.url\");\n statusURL = properties.getProperty(\"status.url\");\n statusWebURL = properties.getProperty(\"statusWeb.url\");\n minRefreshInterval = Integer.valueOf(properties.getProperty(\"minRefreshInterval\")) * 1000L;\n\n } catch (Exception e) {\n e.printStackTrace();\n throw new RuntimeException(e);\n }\n\n }\n\n public static final String BUILD = \"Build\";\n public static final String STATUS = \"Status\";\n public static final long minRefreshInterval;\n\n public static String getBuildUrl(String jobId) {\n return MessageFormat.format(buildURL, jobId);\n }\n\n public static String getBuildWithParametersUrl(String jobId, Map<String, String> parameters) throws UnsupportedEncodingException {\n Set<String> keySet = parameters.keySet();\n String parametersString = \"\";\n char delimiter = '?';\n for (String key : keySet) {\n parametersString += (delimiter + key + \"=\" + parameters.get(key));\n delimiter = '&';\n }\n return MessageFormat.format(buildWithParametersURL, jobId, parametersString);\n }\n\n public static String[] getStatusUrls(String jobId) {\n return new String[]{statusWebURL, MessageFormat.format(statusURL, jobId)};\n }\n\n}\n" } ]
23
avinetworks/avi-corp-demo
https://github.com/avinetworks/avi-corp-demo
58cdb07b539604dc278a0e75b7084c26916f9c18
c7a4320bc04e74b72677a0fca4f0a9e049d49cf9
22bb4cde2bea8a5ab2f91ee9ebd0e24c34f5ff4c
refs/heads/master
2018-09-29T18:15:55.294581
2018-09-24T17:31:16
2018-09-24T17:31:16
127,461,167
2
0
MIT
2018-03-30T18:38:30
2018-05-30T03:04:41
2018-05-30T17:30:57
HTML
[ { "alpha_fraction": 0.4874924421310425, "alphanum_fraction": 0.49293050169944763, "avg_line_length": 54.648284912109375, "blob_id": "0eaed028a9f3f90ea6a6725cd7dafc73b956dbf1", "content_id": "bf855552471ec8119ce038dd627bfcb7689acd71", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 82750, "license_type": "permissive", "max_line_length": 241, "num_lines": 1487, "path": "/metrics/avimetrics/avimetrics.py", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n\nversion = 'v2018-04-12'\n\n#########################################################################################\n# #\n# #\n# #\n# REQUIREMENTS: #\n# 1. python 2.7 #\n# 2. python requests #\n# #\n# #\n# #\n# #\n# @author: Matthew Karnowski ([email protected]) #\n# #\n# #\n# #\n#########################################################################################\n#########################################################################################\n\n#----- Import Libraries\n\nimport requests\nrequests.packages.urllib3.disable_warnings()\nimport json\nimport time\nimport syslog\nimport socket\nfrom multiprocessing import Process\nfrom datetime import datetime\nimport base64\nimport logging\nimport traceback\nimport argparse\nimport sys\nimport os\nfrom metrics_endpoints import *\nimport cPickle as pickle\n\n\n\n#----- Command line Arguments\nparser = argparse.ArgumentParser(description='Avi Metrics Script')\nparser.add_argument('-v', '--version', action='version', version='%(prog)s '+version)\nrequired_args = parser.add_argument_group('required named arguments')\nparser.add_argument('--brief', help='Print Exceptions Only', required=False, action='store_true')\nparser.add_argument('--debug', help='Print All Output, this the DEFAULT setting', required=False, action='store_true')\nparser.add_argument('-m', '--metrics', help='Metrics Endpoint for Sending the data', action='append', required=False, default=None)\nargs = parser.parse_args()\n\n\n\n\n#----- Determine Metrics Endpoint Type Info\ndef determine_endpoint_type():\n endpoint_types = [\n 'graphite',\n 'appdynamics_http',\n 'appdynamics_machine',\n 'splunk',\n 'datadog'\n ]\n if args.metrics == None:\n print '=====>ERROR: No metric type defined, acceptable types are: '+str(endpoint_types)\n sys.exit(1)\n else:\n endpoint_list = []\n for a in args.metrics:\n if a.lower() not in endpoint_types:\n print '=====>ERROR: Invalid metrics type, acceptable types are: '+str(endpoint_types)\n sys.exit(1)\n elif a.lower() == 'graphite':\n with open(os.path.join(fdir,'graphite_host.json')) as gr:\n endpoint_info = json.load(gr)['graphite']\n endpoint_info['type'] = 'graphite'\n endpoint_list.append(endpoint_info)\n elif a.lower() == 'appdynamics_machine':\n endpoint_info={'type': 'appdynamics_machine'}\n endpoint_list.append(endpoint_info)\n elif a.lower() == 'appdynamics_http':\n with open(os.path.join(fdir,'appdynamics_http.json')) as appd:\n endpoint_info = json.load(appd)['appdynamics']\n endpoint_info['type'] = 'appdynamics_http'\n endpoint_list.append(endpoint_info)\n elif a.lower() == 'splunk':\n with open(os.path.join(fdir,'splunk_host.json')) as spl:\n endpoint_info = json.load(spl)['splunk_server']\n endpoint_info['type'] = 'splunk'\n endpoint_list.append(endpoint_info)\n elif a.lower() == 'datadog':\n with open(os.path.join(fdir,'datadog.json')) as dd:\n endpoint_info = json.load(dd)['datadog']\n endpoint_info['type'] = 'datadog'\n endpoint_list.append(endpoint_info)\n return endpoint_list\n\n\n\n\n\n#----- Setting print levels\nif args.brief == True:\n args.debug = False\nelse:\n args.debug = True\n\n\n\n\n\n#----- This function allows for passwords to be either plaintext or base64 encoded\ndef isBase64(password):\n try:\n if base64.b64encode(base64.b64decode(password)) == password:\n return base64.b64decode(password)\n else:\n return password\n except Exception:\n return password\n\n\n\n\n#----- This class is where all the test methods/functions exist and are executed\nclass avi_metrics():\n def __init__(self,avi_controller,host_location,host_environment, avi_user, avi_pass):\n self.avi_cluster_ip = avi_controller\n self.host_location = host_location\n self.host_environment = host_environment\n self.avi_user = avi_user\n self.avi_pass = avi_pass\n #------ Default Metric Payload Template\n self.payload_template = {}\n self.payload_template['location'] = self.host_location\n self.payload_template['environment'] = self.host_environment\n self.payload_template['avicontroller'] = self.avi_cluster_ip\n #------\n vs_metric_list = [\n 'l4_server.avg_errored_connections',\n 'l4_server.avg_rx_pkts',\n 'l4_server.avg_bandwidth',\n 'l4_server.avg_open_conns',\n 'l4_server.avg_new_established_conns',\n 'l4_server.avg_pool_complete_conns',\n 'l4_server.apdexc',\n 'l4_server.avg_total_rtt',\n 'l4_client.apdexc',\n 'l4_client.avg_bandwidth',\n 'l4_client.avg_application_dos_attacks',\n 'l4_client.avg_complete_conns',\n 'l4_client.avg_connections_dropped',\n 'l4_client.avg_new_established_conns',\n 'l4_client.avg_policy_drops',\n 'l4_client.avg_rx_pkts',\n 'l4_client.avg_tx_pkts',\n 'l4_client.avg_rx_bytes',\n 'l4_client.avg_tx_bytes',\n 'l4_client.max_open_conns',\n 'l4_client.avg_lossy_connections',\n 'l7_client.avg_complete_responses',\n 'l7_client.avg_client_data_transfer_time',\n 'l7_client.avg_client_txn_latency',\n 'l7_client.sum_application_response_time',\n 'l7_client.avg_resp_4xx_avi_errors',\n 'l7_client.avg_resp_5xx_avi_errors',\n 'l7_client.avg_resp_4xx',\n 'l7_client.avg_resp_5xx',\n 'l4_client.avg_total_rtt',\n 'l7_server.avg_resp_latency',\n 'l7_server.apdexr',\n 'l7_client.avg_page_load_time',\n 'l7_client.apdexr',\n 'l7_client.avg_ssl_handshakes_new',\n 'l7_client.avg_ssl_connections',\n 'l7_server.avg_application_response_time',\n 'l7_server.pct_response_errors',\n 'l7_server.avg_frustrated_responses',\n 'l7_server.avg_total_requests',\n 'l7_client.sum_get_reqs',\n 'l7_client.sum_post_reqs',\n 'l7_client.sum_other_reqs',\n 'l7_client.avg_frustrated_responses',\n 'l7_client.avg_waf_attacks',\n 'l7_client.pct_waf_attacks',\n 'dns_client.avg_complete_queries',\n 'dns_client.avg_domain_lookup_failures',\n 'dns_client.avg_tcp_queries',\n 'dns_client.avg_udp_queries',\n 'dns_client.avg_udp_passthrough_resp_time',\n 'dns_client.avg_unsupported_queries',\n 'dns_client.pct_errored_queries',\n 'dns_client.avg_domain_lookup_failures',\n 'dns_client.avg_avi_errors',\n 'dns_server.avg_complete_queries',\n 'dns_server.avg_errored_queries',\n 'dns_server.avg_tcp_queries',\n 'dns_server.avg_udp_queries']\n self.vs_metric_list = ','.join(vs_metric_list)\n se_metric_list = [\n 'se_if.avg_bandwidth',\n 'se_stats.avg_connection_mem_usage',\n 'se_stats.avg_connections',\n 'se_stats.avg_connections_dropped',\n 'se_stats.avg_cpu_usage',\n 'se_stats.avg_disk1_usage',\n 'se_stats.avg_mem_usage',\n 'se_stats.avg_persistent_table_usage',\n 'se_stats.avg_rx_bandwidth',\n 'se_if.avg_rx_bytes',\n 'se_if.avg_rx_pkts',\n 'se_if.avg_rx_pkts_dropped_non_vs',\n 'se_if.avg_tx_pkts',\n 'se_if.avg_tx_bytes',\n 'se_stats.avg_ssl_session_cache_usage',\n 'se_if.avg_connection_table_usage',\n 'se_stats.max_se_bandwidth',\n 'se_stats.avg_eth0_bandwidth',\n 'se_stats.pct_syn_cache_usage',\n 'se_stats.avg_packet_buffer_usage',\n 'se_stats.avg_packet_buffer_header_usage',\n 'se_stats.avg_packet_buffer_large_usage',\n 'se_stats.avg_packet_buffer_small_usage']\n self.se_metric_list = ','.join(se_metric_list)\n controller_metric_list = [\n 'controller_stats.avg_cpu_usage',\n 'controller_stats.avg_disk_usage',\n 'controller_stats.avg_mem_usage']\n self.controller_metric_list = ','.join(controller_metric_list)\n controller_process_metric_list = [\n 'process_stats.avg_rss',\n 'process_stats.avg_swap',\n 'process_stats.max_cpu_pct',\n 'process_stats.avg_num_threads',\n 'process_stats.avg_fds',\n 'process_stats.avg_pss',\n 'process_stats.avg_vms']\n self.controller_process_metric_list = ','.join(controller_process_metric_list)\n #----\n pool_server_metric_list = [\n 'l4_server.avg_rx_pkts',\n 'l4_server.avg_tx_pkts',\n 'l4_server.avg_rx_bytes',\n 'l4_server.avg_tx_bytes',\n 'l4_server.avg_bandwidth',\n 'l7_server.avg_complete_responses',\n 'l4_server.avg_new_established_conns',\n 'l4_server.avg_pool_open_conns',\n 'l4_server.avg_pool_complete_conns',\n 'l4_server.avg_open_conns',\n 'l4_server.max_open_conns']\n self.pool_server_metric_list = ','.join(pool_server_metric_list)\n\n\n def avi_login(self):\n try:\n login = pickle.load(open((os.path.join(fdir,self.avi_cluster_ip)),'rb'))\n for c in login.cookies:\n expires = c.expires\n headers = ({\"X-Avi-Tenant\": \"admin\", 'content-type': 'application/json'})\n resp = requests.get('https://%s/api/cluster' %self.avi_cluster_ip, verify=False, headers = headers,cookies=dict(sessionid= login.cookies['sessionid']),timeout=5)\n #if expires > time.time():\n if resp.status_code() == 200:\n return login\n else:\n login = requests.post('https://%s/login' %self.avi_cluster_ip, verify=False, data={'username': self.avi_user, 'password': self.avi_pass},timeout=15)\n pickle.dump(login, open((os.path.join(fdir,self.avi_cluster_ip)),'wb'))\n return login\n except:\n login = requests.post('https://%s/login' %self.avi_cluster_ip, verify=False, data={'username': self.avi_user, 'password': self.avi_pass},timeout=15)\n pickle.dump(login, open((os.path.join(fdir,self.avi_cluster_ip)),'wb'))\n return login\n\n\n def avi_request(self,avi_api,tenant):\n headers = ({\"X-Avi-Tenant\": \"%s\" %tenant, 'content-type': 'application/json'})\n return requests.get('https://%s/api/%s' %(self.avi_controller,avi_api), verify=False, headers = headers,cookies=dict(sessionid= self.login.cookies['sessionid']),timeout=50)\n\n\n def avi_post(self,api_url,tenant,payload):\n headers = ({\"X-Avi-Tenant\": \"%s\" %tenant, 'content-type': 'application/json','referer': 'https://%s' %self.avi_controller, 'X-CSRFToken': dict(self.login.cookies)['csrftoken']})\n cookies = dict(sessionid= self.login.cookies['sessionid'],csrftoken=self.login.cookies['csrftoken'])\n return requests.post('https://%s/api/%s' %(self.avi_controller,api_url), verify=False, headers = headers,cookies=cookies, data=json.dumps(payload),timeout=50)\n\n\n\n #----- Tries to determine a follower controller to poll\n def controller_to_poll(self):\n headers = ({\"X-Avi-Tenant\": \"admin\", 'content-type': 'application/json'})\n resp = (requests.get('https://%s/api/%s' %(self.avi_cluster_ip,'cluster/runtime'), verify=False, headers = headers,cookies=dict(sessionid= self.login.cookies['sessionid']),timeout=50)).json()\n follower_list = []\n if len(resp['node_states']) > 1:\n for c in resp['node_states']:\n if c['state'] == 'CLUSTER_ACTIVE' and c['role'] == 'CLUSTER_FOLLOWER':\n follower_list.append(c['mgmt_ip'])\n if len(follower_list) == 0:\n return self.avi_cluster_ip\n else:\n return sorted(follower_list)[0]\n else:\n return self.avi_cluster_ip\n\n\n #----- Creates inventory dicts to be used by other methods\n def gen_inventory_dict(self):\n try:\n start_time = time.time()\n vs_dict = {'tenants':{},'admin_vs':[]}\n se_dict={'tenants':{},'admin_se':[]}\n pool_dict={'tenants':{}}\n seg_dict = {'tenants':{}}\n if self.login.json()['user']['is_superuser'] == True: #----if SU, use wildcard tenant\n vs_inv = self.avi_request('virtualservice-inventory?page_size=1000','*').json()\n vs_total_pages = (vs_inv['count']/1000) + (vs_inv['count'] % 1000 > 0)\n page_number = 1\n while vs_total_pages > page_number:\n page_number += 1\n resp = self.avi_request('virtualservice-inventory?page_size=1000&page='+page_number,'*').json()\n vs_inv['results'].append(resp['results'])\n #------------------\n se_inv = self.avi_request('serviceengine-inventory?page_size=1000','*').json()\n #------------------\n pool_inv = self.avi_request('pool-inventory?page_size=1000','*').json()\n pool_total_pages = (pool_inv['count']/1000) + (pool_inv['count'] % 1000 > 0)\n page_number = 1\n while pool_total_pages > page_number:\n page_number += 1\n resp = self.avi_request('pool-inventory?page_size=1000&page='+page_number,'*').json()\n pool_inv['results'].append(resp['results'])\n #------------------\n seg_inv = self.avi_request('serviceenginegroup-inventory?page_size=1000','*').json()\n if vs_inv['count'] > 0:\n for v in vs_inv['results']:\n for t in self.tenants:\n if t['url'].split('/tenant/')[1] == v['config']['tenant_ref'].split('/tenant/')[1]:\n temp_tenant = t['name']\n if temp_tenant not in vs_dict['tenants']:\n vs_dict['tenants'][temp_tenant] = {'count':1,'results':[v]}\n else:\n vs_dict['tenants'][temp_tenant]['count']+=1\n vs_dict['tenants'][temp_tenant]['results'].append(v)\n vs_dict[v['uuid']] = v['config']['name']\n if temp_tenant == 'admin':\n vs_dict['admin_vs'].append(v['uuid'])\n if se_inv['count'] > 0:\n for s in se_inv['results']:\n for t in self.tenants:\n if t['url'].split('/tenant/')[1] == s['config']['tenant_ref'].split('/tenant/')[1]:\n temp_tenant = t['name']\n if temp_tenant not in se_dict['tenants']:\n se_dict['tenants'][temp_tenant] = {'count':1,'results':[s]}\n else:\n se_dict['tenants'][temp_tenant]['count']+=1\n se_dict['tenants'][temp_tenant]['results'].append(s)\n se_dict[s['uuid']] = s['config']['name']\n if temp_tenant == 'admin':\n se_dict['admin_se'].append(s['uuid'])\n if pool_inv['count'] > 0:\n for p in pool_inv['results']:\n for t in self.tenants:\n if t['url'].split('/tenant/')[1] == p['config']['tenant_ref'].split('/tenant/')[1]:\n temp_tenant = t['name']\n if temp_tenant not in pool_dict['tenants']:\n pool_dict['tenants'][temp_tenant] = {'count':1,'results':[p]}\n else:\n pool_dict['tenants'][temp_tenant]['count']+=1\n pool_dict['tenants'][temp_tenant]['results'].append(p)\n pool_dict[p['uuid']] = p['config']['name']\n if seg_inv['count'] > 0:\n for seg in seg_inv['results']:\n for t in self.tenants:\n if t['url'].split('/tenant/')[1] == seg['config']['tenant_ref'].split('/tenant/')[1]:\n temp_tenant = t['name']\n if temp_tenant not in seg_dict['tenants']:\n seg_dict['tenants'][temp_tenant] = {'count':1,'results':[seg]}\n else:\n seg_dict['tenants'][temp_tenant]['count']+=1\n seg_dict['tenants'][temp_tenant]['results'].append(seg)\n seg_dict[seg['uuid']] = seg['config']['name']\n else:\n for t in self.tenants:\n vs_inv = self.avi_request('virtualservice-inventory?page_size=1000',t['name']).json()\n vs_total_pages = (vs_inv['count']/1000) + (vs_inv['count'] % 1000 > 0)\n page_number = 1\n while vs_total_pages > page_number:\n page_number += 1\n resp = self.avi_request('virtualservice-inventory?page_size=1000&page='+page_number,t['name']).json()\n vs_inv['results'].append(resp['results'])\n #------------------\n se_inv = self.avi_request('serviceengine-inventory?page_size=1000',t['name']).json()\n #------------------\n pool_inv = self.avi_request('pool-inventory?page_size=1000',t['name']).json()\n pool_total_pages = (pool_inv['count']/1000) + (pool_inv['count'] % 1000 > 0)\n page_number = 1\n while pool_total_pages > page_number:\n page_number += 1\n resp = self.avi_request('pool-inventory?page_size=1000&page='+page_number,'*').json()\n pool_inv['results'].append(resp['results'])\n #------------------\n seg_inv = self.avi_request('serviceenginegroup-inventory?page_size=1000',t['name']).json()\n if vs_inv['count'] > 0:\n vs_dict['tenants'][t['name']]=vs_inv\n for v in vs_inv['results']:\n vs_dict[v['uuid']] = v['config']['name']\n if t['name'] == 'admin':\n vs_dict['admin_vs'].append(v['uuid'])\n if se_inv['count'] > 0:\n se_dict['tenants'][t['name']] = se_inv\n for s in se_inv['results']:\n se_dict[s['uuid']] = s['config']['name']\n if t['name'] == 'admin':\n se_dict['admin_se'].append(s['uuid'])\n if pool_inv['count'] > 0:\n pool_dict['tenants'][t['name']] = pool_inv\n for p in pool_inv['results']:\n pool_dict[p['uuid']] = s['config']['name']\n if seg_inv['count'] > 0:\n seg_dict['tenants'][t['name']] = seg_inv\n for seg in seg_inv['results']:\n seg_dict[seg['uuid']] = seg['config']['name']\n temp_total_time = str(time.time()-start_time)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func gen_inventory_dict completed, executed in '+temp_total_time+' seconds')\n return vs_dict, se_dict, pool_dict, seg_dict\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func gen_inventory_dict encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n sys.exit(1)\n\n\n\n\n\n\n\n\n #-----------------------------------\n #----- Add Test functions\n #-----------------------------------\n def srvc_engn_vs_count(self):\n try:\n temp_start_time = time.time()\n discovered_vs = []\n srvc_engn_dict = {}\n for t in self.tenants:\n if t['name'] in self.se_dict['tenants'] and self.se_dict['tenants'][t['name']]['count'] > 0:\n for entry in self.se_dict['tenants'][t['name']]['results']:\n if len(entry['config']['virtualservice_refs']) > 0:\n for v in entry['config']['virtualservice_refs']:\n if entry['config']['name']+v not in discovered_vs:\n discovered_vs.append(entry['config']['name']+v)\n if entry['config']['name'] not in srvc_engn_dict:\n srvc_engn_dict[self.se_dict[entry['uuid']]] = 1\n else:\n srvc_engn_dict[entry['config']['name']] +=1\n else:\n if entry['config']['name'] not in srvc_engn_dict:\n srvc_engn_dict[entry['config']['name']] = 0\n if len(srvc_engn_dict) > 0:\n endpoint_payload_list = []\n for entry in srvc_engn_dict:\n temp_payload = self.payload_template.copy()\n temp_payload['metric_type'] = 'serviceengine_vs_count'\n temp_payload['timestamp']=int(time.time())\n temp_payload['se_name'] = entry\n temp_payload['metric_type'] = 'serviceengine_vs_count'\n temp_payload['metric_name'] = 'vs_count'\n temp_payload['metric_value'] = srvc_engn_dict[entry]\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||serviceengine||%s||vs_count' %entry\n endpoint_payload_list.append(temp_payload)\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n temp_total_time = str(time.time()-temp_start_time)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func srvc_engn_vs_count completed, executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func srvc_engn_vs_count encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n #-----------------------------------\n\n def srvc_engn_count(self):\n try:\n temp_start_time = time.time()\n se_count = len(self.se_dict) - 2\n endpoint_payload_list = []\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['metric_type'] = 'serviceengine_count'\n temp_payload['metric_name'] = 'count'\n temp_payload['metric_value'] = se_count\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||serviceengine||count'\n endpoint_payload_list.append(temp_payload)\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n temp_total_time = str(time.time()-temp_start_time)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func srvc_engn_count completed, executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func srvc_engn_count encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n #-----------------------------------\n\n\n def srvc_engn_stats(self):\n try:\n temp_start_time = time.time()\n endpoint_payload_list = []\n discovered_ses = []\n discovered_health = []\n for t in self.tenants:\n if t['name'] in self.se_dict['tenants'] and self.se_dict['tenants'][t['name']]['count'] > 0:\n payload = {\n \"metric_requests\": [\n {\n \"step\": 300,\n \"limit\": 1,\n \"aggregate_entity\": False,\n \"entity_uuid\": \"*\",\n \"se_uuid\": \"*\",\n \"id\": \"collItemRequest:AllSEs\",\n \"metric_id\": self.se_metric_list\n }\n ]}\n se_stat = self.avi_post('analytics/metrics/collection?pad_missing_data=false', t['name'], payload).json()\n payload = {\n \"metric_requests\": [\n {\n \"step\": 5,\n \"limit\": 1,\n \"aggregate_entity\": False,\n \"entity_uuid\": \"*\",\n \"se_uuid\": \"*\",\n \"id\": \"collItemRequest:AllSEs\",\n \"metric_id\": self.se_metric_list\n }\n ]}\n realtime_stat = self.avi_post('analytics/metrics/collection?pad_missing_data=false', t['name'], payload).json()\n if 'series' in realtime_stat:\n se_stat['series']['collItemRequest:AllSEs'].update(realtime_stat['series']['collItemRequest:AllSEs'])\n for s in se_stat['series']['collItemRequest:AllSEs']:\n if s in self.se_dict:\n se_name = self.se_dict[s]\n if se_name not in discovered_ses:\n discovered_ses.append(se_name)\n for entry in se_stat['series']['collItemRequest:AllSEs'][s]:\n if 'data' in entry:\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['se_name'] = se_name\n temp_payload['metric_type'] = 'serviceengine_metrics'\n temp_payload['metric_name'] = entry['header']['name']\n temp_payload['metric_value'] = entry['data'][0]['value']\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||serviceengine||%s||%s' %(se_name, entry['header']['name'])\n endpoint_payload_list.append(temp_payload)\n if len(endpoint_payload_list) > 0:\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n temp_total_time = str(time.time()-temp_start_time)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func srvc_engn_stats completed, executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func srvc_engn_stats encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n #-----------------------------------\n #--- This function will loop through all tenants pulling the following statistics\n #--- for all Virtual Services.\n def virtual_service_stats_threaded(self):\n proc = []\n for t in self.tenants:\n t_name = t['name']\n p = Process(target = self.virtual_service_stats, args = (t_name,))\n p.start()\n proc.append(p)\n for p in proc:\n p.join()\n\n\n\n\n def virtual_service_stats(self,tenant):\n try:\n temp_start_time = time.time()\n #-----\n if tenant in self.vs_dict['tenants'] and self.vs_dict['tenants'][tenant]['count'] > 0:\n endpoint_payload_list = []\n payload = {'metric_requests': [{'step' : 300, 'limit': 1, 'id': 'allvs', 'entity_uuid' : '*', 'metric_id': self.vs_metric_list}]}\n vs_stats = self.avi_post('analytics/metrics/collection?pad_missing_data=false', tenant, payload).json()\n #----- this pulls 1 min avg stats for vs that have realtime stats enabled\n payload = {'metric_requests': [{'step' : 5, 'limit': 1, 'id': 'allvs', 'entity_uuid' : '*', 'metric_id': self.vs_metric_list}]}\n realtime_stats = self.avi_post('analytics/metrics/collection?pad_missing_data=false', tenant, payload).json()\n #----- overwrites real time vs' 5 min avg with the 1 min avg\n if 'series' in realtime_stats:\n vs_stats['series']['allvs'].update(realtime_stats['series']['allvs'])\n #----- THIS IS NEW\n for v in vs_stats['series']['allvs']:\n if v in self.vs_dict:\n vs_uuid = v\n vs_name = self.vs_dict[vs_uuid]\n for m in vs_stats['series']['allvs'][v]:\n metric_name = m['header']['name']\n if 'data' in m:\n temp_payload = self.payload_template.copy().copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['vs_name'] = vs_name\n temp_payload['metric_type'] = 'virtualservice_metrics'\n temp_payload['metric_name'] = metric_name\n temp_payload['metric_value'] = m['data'][0]['value']\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||virtualservice||%s||%s' %(vs_name, metric_name)\n endpoint_payload_list.append(temp_payload)\n if len(endpoint_payload_list) > 0:\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n temp_total_time = str(time.time()-temp_start_time)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func virtual_service_stats completed for tenant: '+tenant+', executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func virtual_service_stats encountered an error for tenant '+tenant)\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n\n def vs_metrics_per_se_threaded(self):\n try:\n temp_start_time = time.time()\n major,minor = self.login.json()['version']['Version'].rsplit('.',1)\n if float(major) >= 17.2 and float(minor) >= 8: #----- controller metrics api introduced in 17.2.5\n proc = []\n for t in self.tenants:\n if t['name'] in self.se_dict['tenants'] and self.se_dict['tenants'][t['name']]['count'] > 0:\n p = Process(target = self.vs_metrics_per_se, args = (t['name'],))\n p.start()\n proc.append(p)\n elif 'admin' in self.se_dict['tenants'] and self.se_dict['tenants']['admin']['count'] > 0:\n p = Process(target = self.vs_metrics_per_se, args = (t['name'],))\n p.start()\n proc.append(p)\n for p in proc:\n p.join()\n temp_total_time = str(time.time()-temp_start_time)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func vs_metrics_per_se_threaded completed, executed in '+temp_total_time+' seconds')\n except:\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n\n\n def vs_metrics_per_se(self,tenant):\n try:\n temp_start_time = time.time()\n endpoint_payload_list = []\n payload = {'metric_requests': [{'step' : 300, 'limit': 1, 'id': 'vs_metrics_by_se', 'entity_uuid' : '*', 'serviceengine_uuid': '*', 'include_refs': True, 'metric_id': self.vs_metric_list}]}\n vs_stats = self.avi_post('analytics/metrics/collection?pad_missing_data=false', tenant, payload).json()\n #----- this will pull 1 min stats for vs that have realtime stat enabled\n payload = {'metric_requests': [{'step' : 5, 'limit': 1, 'id': 'vs_metrics_by_se', 'entity_uuid' : '*', 'serviceengine_uuid': '*', 'include_refs': True, 'metric_id': self.vs_metric_list}]}\n realtime_stats = self.avi_post('analytics/metrics/collection?pad_missing_data=false', tenant, payload).json()\n #----- overwrite 5 min avg stats with 1 min avg stats for vs that have realtime stats enabled\n if 'series' in realtime_stats:\n vs_stats['series']['vs_metrics_by_se'].update(realtime_stats['series']['vs_metrics_by_se'])\n if len(vs_stats['series']['vs_metrics_by_se']) > 0:\n for entry in vs_stats['series']['vs_metrics_by_se']:\n if tenant == 'admin' and entry not in self.vs_dict['admin_vs']:\n continue\n elif tenant != 'admin' and entry in self.vs_dict['admin_vs']:\n continue\n else:\n vs_name = self.vs_dict[entry]\n for d in vs_stats['series']['vs_metrics_by_se'][entry]:\n if 'data' in d:\n se_name = self.se_dict[d['header']['serviceengine_ref'].split('serviceengine/')[1]]\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['se_name'] = se_name\n temp_payload['vs_name'] = vs_name\n temp_payload['metric_type'] = 'virtualservice_metrics_per_serviceengine'\n temp_payload['metric_name'] = d['header']['name']\n temp_payload['metric_value'] = d['data'][0]['value']\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||serviceengine||%s||virtualservice_stats||%s||%s' %(se_name,vs_name,d['header']['name'])\n endpoint_payload_list.append(temp_payload)\n if len(endpoint_payload_list) > 0:\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n temp_total_time = str(time.time()-temp_start_time)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func vs_metrics_per_se completed tenant: '+tenant+', executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func vs_metrics_per_se for tenant: '+tenant+', encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n\n\n\n\n\n #----- VS / SE HEALTHSCORES\n def vs_se_healthscores(self):\n try:\n temp_start_time = time.time()\n discovered_vs = []\n discovered_se = []\n endpoint_payload_list = []\n for t in self.tenants:\n if t['name'] in self.vs_dict['tenants'] and self.vs_dict['tenants'][t['name']]['count'] > 0:\n for v in self.vs_dict['tenants'][t['name']]['results']:\n if v['uuid'] not in discovered_vs:\n discovered_vs.append(v['uuid'])\n vs_name = v['config']['name']\n temp_dict = {}\n temp_dict['healthscore'] = v['health_score']['health_score']\n temp_dict['resources_penalty'] = v['health_score']['resources_penalty']\n temp_dict['anomaly_penalty'] = v['health_score']['anomaly_penalty']\n temp_dict['performance_score'] = v['health_score']['performance_score']\n temp_dict['security_penalty'] = v['health_score']['security_penalty']\n for h in temp_dict:\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['vs_name'] = vs_name\n temp_payload['metric_type'] = 'virtualservice_healthscore'\n temp_payload['metric_name'] = h\n temp_payload['metric_value'] = temp_dict[h]\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||virtualservice||%s||%s' %(vs_name,h)\n endpoint_payload_list.append(temp_payload)\n if t['name'] in self.se_dict['tenants'] and self.se_dict['tenants'][t['name']]['count'] > 0:\n for s in self.se_dict['tenants'][t['name']]['results']:\n if s['uuid'] not in discovered_se:\n discovered_se.append(s['uuid'])\n #se_healthscore = s['health_score']['health_score']\n temp1_dict = {}\n temp1_dict['healthscore'] = s['health_score']['health_score']\n temp1_dict['resources_penalty'] = s['health_score']['resources_penalty']\n temp1_dict['anomaly_penalty'] = s['health_score']['anomaly_penalty']\n temp1_dict['performance_score'] = s['health_score']['performance_score']\n temp1_dict['security_penalty'] = s['health_score']['security_penalty']\n for h in temp1_dict:\n temp1_payload = self.payload_template.copy()\n temp1_payload['timestamp']=int(time.time())\n temp1_payload['se_name'] = self.se_dict[s['uuid']]\n temp1_payload['metric_type'] = 'serviceengine_healthscore'\n temp1_payload['metric_name'] = h\n temp1_payload['metric_value'] = temp1_dict[h]\n temp1_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||serviceengine||%s||%s' %(self.se_dict[s['uuid']],h)\n endpoint_payload_list.append(temp1_payload)\n if len(endpoint_payload_list) > 0:\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n temp_total_time = str(time.time()-temp_start_time)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func vs_se_healthscores completed, executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func vs_se_healthscores encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n #----- VS UP/DOWN/Enabled/Disabled STATUS\n def vs_oper_status(self):\n try:\n temp_start_time = time.time()\n endpoint_payload_list = []\n vs_up_count = 0\n vs_down_count = 0\n vs_disabled_count = 0\n vs_count = 0\n for t in self.tenants:\n if t['name'] in self.vs_dict['tenants'] and self.vs_dict['tenants'][t['name']]['count'] > 0:\n for v in self.vs_dict['tenants'][t['name']]['results']:\n vs_name = v['config']['name']\n metric_name = 'oper_status'\n if v['runtime']['oper_status']['state'] == 'OPER_UP':\n metric_value = 1\n vs_up_count += 1\n elif v['runtime']['oper_status']['state'] == 'OPER_DISABLED':\n metric_value = 0\n vs_down_count += 1\n vs_disabled_count += 1\n else:\n metric_value = 0\n vs_down_count += 1\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['vs_name'] = vs_name\n temp_payload['metric_type'] = 'virtualservice_operstatus'\n temp_payload['metric_name'] = 'oper_status'\n temp_payload['metric_value'] = metric_value\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||virtualservice||%s||%s' %(vs_name, metric_name)\n endpoint_payload_list.append(temp_payload)\n #----- Starting here sending VS operstatus summary info\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n #----- Total VS\n a = temp_payload.copy()\n a['metric_name'] = 'count'\n a['metric_value'] = len(self.vs_dict) - 2\n a['metric_type'] = 'virtualservice_count'\n a['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||virtualservice||count'\n endpoint_payload_list.append(a)\n #----- Total VS UP\n b = temp_payload.copy()\n b['metric_type'] = 'virtualservice_up'\n b['metric_name'] = 'status_up'\n b['metric_value'] = vs_up_count\n b['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||virtualservice||status_up'\n endpoint_payload_list.append(b)\n #----- Total VS Down\n c = temp_payload.copy()\n c['metric_type'] = 'virtualservice_down'\n c['metric_name'] = 'status_down'\n c['metric_value'] = vs_down_count\n c['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||virtualservice||status_down'\n endpoint_payload_list.append(c)\n #----- Total VS Disabled\n d = temp_payload.copy()\n d['metric_type'] = 'virtualservice_disabled'\n d['metric_name'] = 'status_disabled'\n d['metric_value'] = vs_disabled_count\n d['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||virtualservice||status_disabled'\n endpoint_payload_list.append(d)\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n temp_total_time = str(time.time()-temp_start_time)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func vs_oper_status completed, executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func vs_oper_status encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n #-----------------------------------\n #----- RETRIEVE THE NUMBER OF ENABLED, ACTIVE, AND TOTAL POOL MEMBERS FOR EACH VIRTUAL SERVER\n def vs_active_pool_members(self):\n try:\n temp_start_time = time.time()\n endpoint_payload_list = []\n for t in self.tenants:\n if t['name'] in self.pool_dict['tenants'] and self.pool_dict['tenants'][t['name']]['count'] > 0:\n pool_member_status = self.pool_dict['tenants'][t['name']]['results']\n for p in pool_member_status:\n try:\n vs_list = []\n if 'num_servers' in p['runtime']:\n if 'virtualservice' in p:\n vs_list.append(p['virtualservice']['name'])\n elif 'virtualservices' in p:\n for v in p['virtualservices']:\n vs_list.append(self.vs_dict[v.rsplit('/',1)[1]])\n pool_name = p['config']['name']\n pool_members_up = p['runtime']['num_servers_up']\n pool_members_enabled = p['runtime']['num_servers_enabled']\n pool_members = p['runtime']['num_servers']\n for vs_entry in vs_list:\n #----- pool members enabled\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['vs_name'] = vs_entry\n temp_payload['pool_name'] = pool_name\n temp_payload['metric_type'] = 'virtualservice_pool_members'\n temp_payload['metric_name'] = 'virtualservice_pool_members_enabled'\n temp_payload['metric_value'] = pool_members_enabled\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||virtualservice||%s||pool||%s||%s' %(vs_entry, pool_name, 'pool_members_enabled')\n endpoint_payload_list.append(temp_payload)\n #----- pool members up\n temp1_payload = self.payload_template.copy()\n temp1_payload['timestamp']=int(time.time())\n temp1_payload['vs_name'] = vs_entry\n temp1_payload['pool_name'] = pool_name\n temp1_payload['metric_type'] = 'virtualservice_pool_members'\n temp1_payload['metric_name'] = 'virtualservice_pool_members_up'\n temp1_payload['metric_value'] = pool_members_up\n temp1_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||virtualservice||%s||pool||%s||%s' %(vs_entry, pool_name, 'pool_members_up')\n endpoint_payload_list.append(temp1_payload)\n #----- pool members configured\n temp2_payload = self.payload_template.copy()\n temp2_payload['timestamp']=int(time.time())\n temp2_payload['vs_name'] = vs_entry\n temp2_payload['pool_name'] = pool_name\n temp2_payload['metric_type'] = 'virtualservice_pool_members'\n temp2_payload['metric_name'] = 'virtualservice_pool_members'\n temp2_payload['metric_value'] = pool_members\n temp2_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||virtualservice||%s||pool||%s||%s' %(vs_entry, pool_name, 'pool_members')\n endpoint_payload_list.append(temp2_payload)\n except:\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n if len(endpoint_payload_list) > 0:\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n temp_total_time = str(time.time()-temp_start_time)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func vs_active_pool_members completed, executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func vs_active_pool_members encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n\n\n\n\n #-----------------------------------\n #----- SE missed heartbeats\n def se_missed_hb(self):\n try:\n temp_start_time = time.time()\n endpoint_payload_list = []\n discovered_se = []\n for t in self.tenants:\n if t['name'] in self.se_dict['tenants'] and self.se_dict['tenants'][t['name']]['count'] > 0:\n for s in self.se_dict['tenants'][t['name']]['results']:\n if s['uuid'] not in discovered_se:\n discovered_se.append(s['uuid'])\n if 'hb_status' in s['runtime']:\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['se_name'] = s['config']['name']\n temp_payload['metric_type'] = 'serviceengine_missed_heartbeats'\n temp_payload['metric_name'] = 'missed_heartbeats'\n temp_payload['metric_value'] = s['runtime']['hb_status']['num_hb_misses']\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||serviceengine||%s||%s' %(s['config']['name'], 'missed_heartbeats')\n endpoint_payload_list.append(temp_payload)\n if len(endpoint_payload_list) > 0:\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n temp_total_time = str(time.time()-temp_start_time)\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func se_missed_hb completed, executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func se_missed_hb encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n\n\n #-----------------------------------\n def cluster_status(self):\n try:\n temp_start_time = time.time()\n cluster_status = self.avi_request('cluster/runtime','admin').json()\n endpoint_payload_list = []\n active_members = 0\n #-----------------------------------\n #---- RETURN CLUSTER MEMBER ROLE\n #---- follower = 0, leader = 1\n for c in cluster_status['node_states']:\n if c['state'] == 'CLUSTER_ACTIVE':\n active_members = active_members + 1\n if c['role'] == 'CLUSTER_FOLLOWER':\n member_role = 0\n elif c['role'] == 'CLUSTER_LEADER':\n member_role = 1\n try:\n member_name = socket.gethostbyaddr(c['name'])[0]\n except:\n member_name = c['name']\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['cluster_name'] = member_name\n temp_payload['metric_type'] = 'cluster'\n temp_payload['metric_name'] = 'member_role'\n temp_payload['metric_value'] = member_role\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||cluster||%s||role' %member_name\n endpoint_payload_list.append(temp_payload)\n #-----------------------------------\n #---- ADD ACTIVE MEMBER COUNT TO LIST\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['metric_type'] = 'cluster'\n temp_payload['metric_name'] = 'active_members'\n temp_payload['metric_value'] = active_members\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||cluster||active_members'\n endpoint_payload_list.append(temp_payload)\n #----- Send metrics\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n temp_total_time = str(time.time()-temp_start_time)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func cluster_status completed, executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func cluster_status encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n\n #-----------------------------------\n def avi_subnet_usage(self):\n try:\n if datetime.now().minute % 5 == 0: #----- run every 5 mins\n temp_start_time = time.time()\n subnets = self.avi_request('network-inventory?page_size=1000','admin').json()['results']\n endpoint_payload_list = []\n if len(subnets) > 0:\n for s in subnets:\n if 'subnet_runtime' in s['runtime'].keys():\n pool_size = float(s['runtime']['subnet_runtime'][0]['total_ip_count'])\n if pool_size > 0:\n network_name = s['runtime']['name'].replace('|','_').replace(':','_')\n pool_used = float(s['runtime']['subnet_runtime'][0]['used_ip_count'])\n percentage_used = int((pool_used/pool_size)*100)\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['network_name'] = network_name\n temp_payload['metric_type'] = 'network_usage'\n temp_payload['metric_name'] = 'used'\n temp_payload['metric_value'] = percentage_used\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||networks||%s||used' %network_name\n endpoint_payload_list.append(temp_payload)\n if len(endpoint_payload_list) > 0:\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n temp_total_time = str(time.time()-temp_start_time)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func avi_subnet_usage completed, executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func avi_subnet_usage encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n #-----------------------------------\n def virtual_service_hosted_se(self):\n try:\n temp_start_time = time.time()\n vs_dict = {}\n endpoint_payload_list = []\n discovered = []\n for t in self.tenants:\n if t['name'] in self.se_dict['tenants'] and self.se_dict['tenants'][t['name']]['count'] > 0:\n for s in self.se_dict['tenants'][t['name']]['results']:\n se_name = s['config']['name']\n if 'virtualservice_refs' in s['config']:\n for e in s['config']['virtualservice_refs']:\n vs_name = self.vs_dict[e.split('/api/virtualservice/')[1]]\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['se_name'] = se_name\n temp_payload['vs_name'] = vs_name\n temp_payload['metric_type'] = 'virtualservice_hosted_se'\n temp_payload['metric_name'] = 'hosting_se'\n temp_payload['metric_value'] = 1\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||virtualservice||%s||serviceengine||%s' %(vs_name, se_name)\n if temp_payload not in discovered:\n discovered.append(temp_payload)\n endpoint_payload_list.append(temp_payload)\n elif 'vs_uuids' in s['config']: #---- 17.2.4 api changed\n for e in s['config']['vs_uuids']:\n vs_name = self.vs_dict[e.rsplit('api/virtualservice/')[1]]\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['se_name'] = se_name\n temp_payload['vs_name'] = vs_name\n temp_payload['metric_type'] = 'virtualservice_hosted_se'\n temp_payload['metric_name'] = 'hosting_se'\n temp_payload['metric_value'] = 1\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||virtualservice||%s||serviceengine||%s' %(vs_name, se_name)\n if temp_payload not in discovered:\n discovered.append(temp_payload)\n endpoint_payload_list.append(temp_payload)\n if len(endpoint_payload_list) > 0:\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n temp_total_time = str(time.time()-temp_start_time)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func virtual_service_hosted_se completed, executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func virtual_service_hosted_se encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n\n\n #-----------------------------------\n def license_usage(self):\n try:\n temp_start_time = time.time()\n endpoint_payload_list = []\n licensing = self.avi_request('licenseusage?limit=1&step=300','admin').json()\n lic_cores = licensing['licensed_cores']\n if lic_cores != None:\n cores_used = licensing['num_se_vcpus']\n percentage_used = (cores_used / float(lic_cores))*100\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['metric_type'] = 'licensing'\n temp_payload['metric_name'] = 'licensed_cores'\n temp_payload['metric_value'] = lic_cores\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||licensing||licensed_cores'\n endpoint_payload_list.append(temp_payload)\n #-----\n temp1_payload = self.payload_template.copy()\n temp1_payload['timestamp']=int(time.time())\n temp1_payload['metric_type'] = 'licensing'\n temp1_payload['metric_name'] = 'cores_used'\n temp1_payload['metric_value'] = cores_used\n temp1_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||licensing||cores_used'\n endpoint_payload_list.append(temp1_payload)\n #-----\n temp2_payload = self.payload_template.copy()\n temp2_payload['timestamp']=int(time.time())\n temp2_payload['metric_type'] = 'licensing'\n temp2_payload['metric_name'] = 'percentage_used'\n temp2_payload['metric_value'] = percentage_used\n temp2_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||licensing||percentage_used'\n endpoint_payload_list.append(temp2_payload)\n temp_total_time = str(time.time()-temp_start_time)\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func license_usage completed, executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func license_usage encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n\n\n #-----------------------------------\n def service_engine_vs_capacity(self):\n try:\n temp_start_time = time.time()\n endpoint_payload_list = []\n se_group_max_vs = {}\n discovered_vs = []\n se_vs = {}\n for t in self.tenants:\n if t['name'] in self.seg_dict['tenants'] and self.seg_dict['tenants'][t['name']]['count'] > 0:\n for g in self.seg_dict['tenants'][t['name']]['results']:\n se_group_max_vs[g['uuid']] = float(g['config']['max_vs_per_se'])\n for t in self.tenants:\n if t['name'] in self.se_dict['tenants'] and self.se_dict['tenants'][t['name']]['count'] > 0:\n for s in self.se_dict['tenants'][t['name']]['results']:\n se_name = s['config']['name']\n if se_name not in se_vs:\n max_vs = se_group_max_vs[s['config']['se_group_ref'].rsplit('api/serviceenginegroup/')[1]]\n se_vs[se_name]={'max_vs': max_vs, 'total_vs':0}\n if 'virtualservice_refs' in s['config']:\n for v in s['config']['virtualservice_refs']:\n if se_name+v.rsplit('api/virtualservice/')[1] not in discovered_vs:\n discovered_vs.append(s['config']['name']+v.rsplit('api/virtualservice/')[1])\n se_vs[se_name]['total_vs'] += 1\n for entry in se_vs:\n vs_percentage_used = (se_vs[entry]['total_vs']/se_vs[entry]['max_vs'])*100\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['se_name'] = entry\n temp_payload['metric_type'] = 'serviceengine_capacity'\n temp_payload['metric_name'] = 'vs_capacity_used'\n temp_payload['metric_value'] = vs_percentage_used\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||serviceengine||%s||vs_capacity_used' %entry\n endpoint_payload_list.append(temp_payload)\n if len(endpoint_payload_list) > 0:\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n temp_total_time = str(time.time()-temp_start_time)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func service_engine_vs_capacity completed, executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func service_engine_vs_capacity encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n\n\n\n #-----------------------------------\n def license_expiration(self):\n try:\n if datetime.now().hour % 6 == 0: #----- run once every 6 hours\n current_time = datetime.today()\n temp_start_time = time.time()\n licenses = self.avi_request('license','admin').json()\n for l in licenses['licenses']:\n license_id = l['license_id']\n try:\n expires = datetime.strptime(l['valid_until'],\"%Y-%m-%d %H:%M:%S\")\n except:\n expires = datetime.strptime(l['valid_until'],\"%Y-%m-%dT%H:%M:%S\")\n days_to_expire = (expires - current_time).days\n endpoint_payload_list = []\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['license_id'] = license_id\n temp_payload['metric_type'] = 'license'\n temp_payload['metric_name'] = 'license_expiration'\n temp_payload['metric_value'] = days_to_expire\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||licensing||expiration_days||'+license_id\n endpoint_payload_list.append(temp_payload)\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n temp_total_time = str(time.time()-temp_start_time)\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func license_expiration completed, executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func license_expiration encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n\n\n #-----------------------------------\n #----- GET AVI SOFTWARE VERSION NUMBER AND ASSIGN VALUE OF 1\n def get_avi_version(self):\n try:\n temp_start_time = time.time()\n #current_version = self.login.json()['version']['Version']+'('+str(self.login.json()['version']['build'])+')'\n current_version = self.login.json()['version']['Version']\n endpoint_payload_list = []\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['metric_type'] = 'version'\n temp_payload['metric_name'] = current_version\n temp_payload['metric_value'] = 1\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||current_version||%s' %current_version\n endpoint_payload_list.append(temp_payload)\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n if args.debug == True:\n temp_total_time = str(time.time()-temp_start_time)\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func get_avi_version completed, executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': get_avi_version encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n\n #-----------------------------------\n #----- GET Pool Member specific statistics\n def pool_server_metrics(self):\n try:\n temp_start_time = time.time()\n endpoint_payload_list = []\n discovered_servers = []\n try:\n for t in self.tenants:\n payload = {\n \"metric_requests\": [\n {\n \"step\": 300,\n \"limit\": 1,\n \"aggregate_entity\": False,\n \"entity_uuid\": \"*\",\n \"obj_id\": \"*\",\n \"pool_uuid\": \"*\",\n \"id\": \"collItemRequest:AllServers\",\n \"metric_id\": self.pool_server_metric_list\n }\n ]}\n api_url = 'analytics/metrics/collection?pad_missing_data=false&dimension_limit=1000&include_name=true&include_refs=true'\n resp = self.avi_post(api_url,t['name'],payload)\n if 'series' in resp.json():\n if len(resp.json()['series']['collItemRequest:AllServers']) != 0:\n for p in resp.json()['series']['collItemRequest:AllServers']:\n if p not in discovered_servers:\n discovered_servers.append(p)\n server_object = p.split(',')[2]\n for d in resp.json()['series']['collItemRequest:AllServers'][p]:\n if 'data' in d:\n pool_name = d['header']['pool_ref'].rsplit('#',1)[1]\n vs_name = d['header']['entity_ref'].rsplit('#',1)[1]\n metric_name = d['header']['name']\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['vs_name'] = vs_name\n temp_payload['pool_name'] = pool_name\n temp_payload['pool_member'] = server_object\n temp_payload['metric_type'] = 'pool_member_metrics'\n temp_payload['metric_name'] = metric_name\n temp_payload['metric_value'] = d['data'][0]['value']\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||virtualservice||%s||pool||%s||%s||%s' %(vs_name, pool_name, server_object,metric_name)\n endpoint_payload_list.append(temp_payload)\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func pool_server_metrics encountered an error for tenant '+t['name'])\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n if len(endpoint_payload_list) > 0:\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n temp_total_time = str(time.time()-temp_start_time)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': pool_server_metrics, executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func pool_server_metrics encountered an error encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n\n #-----------------------------------\n #----- GET customer Member specific statistics\n def controller_cluster_metrics(self):\n try:\n temp_start_time = time.time()\n major,minor = self.login.json()['version']['Version'].rsplit('.',1)\n if float(major) >= 17.2 and float(minor) >= 5: #----- controller metrics api introduced in 17.2.5\n cluster= self.avi_request('cluster','admin').json()\n cluster_nodes = {}\n temp_list=[]\n endpoint_payload_list = []\n for c in cluster['nodes']:\n cluster_nodes[c['vm_uuid']]=c['ip']['addr']\n #cluster_nodes[c['vm_uuid']]=c['vm_hostname']\n resp = self.avi_request('analytics/metrics/controller/%s/?metric_id=%s&limit=1&step=300&?aggregate_entity=False' %(c['vm_uuid'],self.controller_metric_list),'admin').json()\n temp_list.append(resp)\n for n in temp_list:\n node = cluster_nodes[n['entity_uuid']]\n for m in n['series']:\n metric_name = m['header']['name']\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['cluster_node'] = node\n temp_payload['metric_type'] = 'controller_metrics'\n temp_payload['metric_name'] = metric_name\n temp_payload['metric_value'] = m['data'][0]['value']\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||controller||%s||%s' %(node,metric_name)\n endpoint_payload_list.append(temp_payload)\n if len(endpoint_payload_list) > 0:\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n else:\n pass\n temp_total_time = str(time.time()-temp_start_time)\n if args.debug == True:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': controller_cluster_metrics, executed in '+temp_total_time+' seconds')\n except:\n print(str(datetime.now())+' '+self.avi_cluster_ip+': func controller_cluster_metrics encountered an error encountered an error')\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n\n\n\n\n\n\n#-----------------------------------\n#-----------------------------------\n#-----------------------------------\n\n #-----------------------------------\n #----- This is the method within the class that will execute the other methods.\n #----- all test methods will need to be added to test_functions list to be executed\n def gather_metrics(self):\n try:\n start_time = time.time()\n self.login = self.avi_login()\n self.tenants = self.login.json()['tenants']\n self.avi_controller = self.controller_to_poll()\n print '=====> Chose '+self.avi_controller\n self.vs_dict, self.se_dict, self.pool_dict, self.seg_dict = self.gen_inventory_dict()\n #-----------------------------------\n #----- Add Test functions to list for threaded execution\n #-----------------------------------\n test_functions = []\n test_functions.append(self.virtual_service_stats_threaded)\n test_functions.append(self.vs_metrics_per_se_threaded)\n test_functions.append(self.srvc_engn_stats)\n test_functions.append(self.srvc_engn_vs_count)\n test_functions.append(self.srvc_engn_count)\n test_functions.append(self.vs_se_healthscores)\n test_functions.append(self.vs_oper_status)\n test_functions.append(self.se_missed_hb)\n test_functions.append(self.vs_active_pool_members)\n test_functions.append(self.cluster_status)\n test_functions.append(self.avi_subnet_usage)\n test_functions.append(self.virtual_service_hosted_se)\n test_functions.append(self.license_usage)\n test_functions.append(self.service_engine_vs_capacity)\n test_functions.append(self.license_expiration)\n test_functions.append(self.get_avi_version)\n test_functions.append(self.pool_server_metrics)\n test_functions.append(self.controller_cluster_metrics)\n #-----------------------------------\n #-----------------------------------\n #-----\n #-----------------------------------\n #----- BEGIN Running Test Functions\n #-----------------------------------\n proc = []\n for f in test_functions:\n p = Process(target = f, args = ())\n p.start()\n proc.append(p)\n for p in proc:\n p.join()\n #-----------------------------------\n #-----\n #-----------------------------------\n #----- Log time it took to execute script\n #-----------------------------------\n total_time = str(time.time()-start_time)\n print(str(datetime.now())+' '+self.avi_cluster_ip+': controller specific tests have completed, executed in '+total_time+' seconds')\n endpoint_payload_list = []\n temp_payload = self.payload_template.copy()\n temp_payload['timestamp']=int(time.time())\n temp_payload['metric_type'] = 'metricscript'\n temp_payload['metric_name'] = 'execution_time'\n temp_payload['metric_value'] = float(total_time)*1000\n temp_payload['name_space'] = 'avi||'+self.host_location+'||'+self.host_environment+'||'+self.avi_cluster_ip+'||metricscript||executiontime'\n endpoint_payload_list.append(temp_payload)\n send_metriclist_to_endpoint(endpoint_list, endpoint_payload_list)\n except:\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' Unable to login to: '+self.avi_cluster_ip)\n print(str(datetime.now())+' '+self.avi_cluster_ip+': '+exception_text)\n\n\n\n #--- THIS METHOD KICKS OFF THE EXECUTION\n def run(self):\n self.gather_metrics()\n\n\n\n #-----------------------------------\n #-----------------------------------\n #-----------------------------------\n\n\n#--- Primary function to execute the metrics gathering\n#--- This function will create a avi_metrics object for each controller\n#--- and kick off the metrics gathering for them.\ndef main():\n start_time = time.time()\n proc = []\n for entry in avi_controller_list:\n avi_controller = entry['avi_controller']\n host_location = entry['location']\n host_environment = entry['environment']\n c = avi_metrics(avi_controller, host_location, host_environment, entry['avi_user'], isBase64(entry['avi_pass']))\n p = Process(target = c.run, args = ())\n p.start()\n proc.append(p)\n for p in proc:\n p.join()\n total_time = str(time.time()-start_time)\n print(str(datetime.now())+' AVI_SCRIPT: metric script has completed, executed in '+total_time+' seconds')\n\n\n\n\n\n\n#----- START SCRIPT EXECUTION\n#----- check for docker environment Variable\n#----- if docker environment, runs as while loop\nif 'EN_DOCKER' in os.environ:\n #----- Metrics db server\n fdir = os.path.abspath(os.path.dirname(__file__))\n args.metrics = (os.environ['EN_METRIC_ENDPOINT'].replace(' ','').lower().split(':'))\n endpoint_list = determine_endpoint_type()\n while True:\n loop_start_time = time.time()\n with open('avi_controllers.json') as amc:\n avi_controller_list = json.load(amc)['controllers']\n main()\n loop_total_time = time.time()-loop_start_time\n if loop_total_time < 60:\n print(str(datetime.now())+' AVI_SCRIPT: sleeping for '+str(60 - datetime.now().second)+' seconds')\n time.sleep(60 - datetime.now().second)\nelse:\n #----- Get the file path to import controllers, needed for cron\n fdir = os.path.abspath(os.path.dirname(__file__))\n #----- Import avi controller info from json file\n with open(os.path.join(fdir,'avi_controllers.json')) as amc:\n avi_controller_list = json.load(amc)['controllers']\n #----- Import endpoint info from json files\n endpoint_list = determine_endpoint_type()\n main()\n\n" }, { "alpha_fraction": 0.508012056350708, "alphanum_fraction": 0.5123500227928162, "avg_line_length": 34.13374710083008, "blob_id": "f5a769190b5b5233b5ac9636bf9162c6f19cb6f5", "content_id": "282bd4ccf6565976e698e415fd2654b0f33919df", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 45188, "license_type": "permissive", "max_line_length": 274, "num_lines": 1286, "path": "/servers/demo-scaleout/html/nyc-2/masthead.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "var NYTD = NYTD || {};\n\n// NYT5 reskin\nNYTD.reskin = (function($) {\n 'use strict';\n\n var navigationModalOptions = {\n uniqueId: \"navigationModal\",\n bind: \"#navigation-panel .taxonomy li:last\",\n positionType: \"Fixed\",\n overlayBackground: 'None',\n modalTitle: \"\",\n width: 210\n };\n\n var userSettingsModalOpenCallback = function() {\n $('#masthead-tools').find('.settings-modal span').addClass('activated');\n };\n\n var userSettingsModalCloseCallback = function() {\n $('#masthead-tools').find('.settings-modal span').removeClass('activated');\n };\n\n var getCookie = function (name) {\n return new RegExp(name + '=([^;]+)').test(window.unescape(document.cookie)) ? RegExp.$1 : null;\n };\n\n var getPageCategory = function() {\n return $(\"meta[name='CG']\").attr('content');\n };\n\n var getPageSubCategory = function() {\n return $(\"meta[name='SCG']\").attr('content');\n };\n\n var getPageType = function() {\n return $(\"meta[name='PT']\").attr('content');\n };\n\n var getPageSubType = function() {\n return $(\"meta[name='PST']\").attr('content');\n };\n\n var getEdition = function() {\n var edition;\n var cookie = getCookie('NYT-Edition');\n if (cookie && cookie === 'edition|GLOBAL') {\n edition = 'global';\n } else {\n edition = 'domestic';\n }\n\n return edition;\n };\n\n var userSettingsModalOptions = {\n uniqueId: \"user-settings-modal\",\n bind: \".masthead-tools .settings-modal\",\n positionType: \"BelowLeft\",\n overlayBackground: 'None',\n modalTitle: \"\",\n width: 210,\n openCallback: userSettingsModalOpenCallback,\n closeCallback: userSettingsModalCloseCallback\n };\n\n var internationalMap = [\"sports\", \"business\", \"opinion\", \"style\", \"arts\", \"dining\"];\n var taxonomyUrl = NYTD.Hosts.jsonHost + '/services/json/taxonomy/hierarchical.jsonp';\n var userInfoUrl = '/svc/web-products/userinfo.json';\n var mobileRegex = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i;\n var isMobile = mobileRegex.test(navigator.userAgent);\n var searchUrl = 'http://query.nytimes.com/search/sitesearch/#/';\n var trackingBaseData = {\n 'action': 'click',\n 'region': 'Masthead',\n 'pgtype': getPageType().replace(' ', '')\n };\n var mTimeout = true;\n var mouseLocs = [];\n var mouseLocsTracked = 2;\n var intentRangeLower = 10;\n var intentRangeUpper = 170;\n var timer = {};\n var isNavAnimating = false;\n var panelWidth = 210;\n var singlePanelWidth = panelWidth + 'px';\n var singlePanelPartlyShut = (panelWidth - 20) + 'px';\n var navTimeout = 500;\n var navAnimation = 150;\n var hoverTimeout = 500;\n var $el = $('#navigation-panel');\n var $shell = $('#shell');\n var $html = $('html');\n var $body = $('body');\n var $document = $(document);\n var $top1,\n $mid1,\n $sections,\n $navigationModal,\n $navigationPointer,\n navigationModal,\n userSettingsModal;\n\n var templates = {\n sectionsButton : [\n '<div id=\"masthead-buttons-container\" class=\"masthead-buttons-container\">',\n '<div id=\"masthead-sections-button\" class=\"buttons masthead-button masthead-sections-button\" onclick=\"NYTD.reskin.toggle();\">Sections</div>',\n '<div id=\"masthead-search-button\" class=\"buttons masthead-button masthead-search-button\">Search</div>',\n '</div>'\n ].join(''),\n\n loginModal : function(data) {\n return [\n '<div class=\"modal-header\">',\n '<h5 class=\"modal-heading\"><a href=\"' + data.profileUrl + '\"></a>' + data.username + '</h5>',\n '</div>',\n '<div class=\"modal-content\">',\n '<ul>',\n '<li><a class=\"login-modal-profile\" href=\"' + data.profileUrl + '\">My Profile</a></li>',\n '<li><a class=\"login-modal-account\" href=\"' + data.myaccountUrl + '\">My Account</a></li>',\n '<li><a class=\"login-modal-saved\" href=\"' + data.savedUrl + '\">My Saved Items</a></li>',\n '<li><a class=\"button log-out-button\" href=\"' + data.logOutUrl + '\">Log Out</a></li>',\n '</ul>',\n '</div>',\n '<button type=\"button\" class=\"modal-close hidden\"><i class=\"icon\"></i><span class=\"visually-hidden\">Close this modal window</span></button>',\n '<div class=\"modal-pointer modal-pointer-up-right\"><div class=\"modal-pointer-conceal\"></div></div>'\n ].join('')\n },\n\n settingsModal : function(data) {\n var location = window.location.pathname;\n return [\n '<div class=\"modal-header\">',\n '<h5 class=\"modal-heading\"></h5>',\n '</div>',\n '<div class=\"modal-content\">',\n '<div class=\"menu edition-menu\">',\n '<h5 class=\"modal-heading\">Edition</h5>',\n '<ul>',\n '<li><a href=\"' + location + '\" data-edition=\"us\">U.S.</a></li>',\n '<li><a href=\"' + location + '\" data-edition=\"international\">International</a></li>',\n '<li><a href=\"http://cn.nytimes.com\" data-edition=\"chinese\">中文网 (Chinese)</a></li>',\n '</ul>',\n '</div>',\n '<div class=\"menu help-menu\">',\n '<h5 class=\"modal-heading\">Help</h5>',\n '<ul>',\n '<li><a class=\"settings-faq\" href=\"http://www.nytimes.com/content/help/front.html\">FAQ</a></li>',\n '<li><a class=\"settings-contact\" href=\"http://www.nytimes.com/content/help/contact/directory.html\">Contact Us</a></li>',\n '</ul>',\n '</div>',\n '</div>',\n '<button type=\"button\" class=\"modal-close hidden\"><i class=\"icon\"></i><span class=\"visually-hidden\">Close this modal window</span></button>',\n '<div class=\"modal-pointer modal-pointer-up-right\"><div class=\"modal-pointer-conceal\"></div></div>'\n ].join('')\n },\n\n nav : function (nData, sData) {\n var shortcuts = '';\n var nav = '';\n\n $.each(sData, function(k, n) {\n shortcuts += '<li><a id=\"shortcuts-' + n.id + '\" class=\"icon-' + n.id + '\" href=\"' + n.path + '\"><i class=\"icon\"></i>' + n.name + '</a></li>';\n });\n\n\n $.each(nData, function(k, n) {\n nav += '<li><a id=\"navId-' + n.id + '\" class=\"' + n.class_name + '\">' + n.name + '<div class=\"arrow-right\"><div class=\"arrow-conceal\"></div></div></a></li>';\n });\n\n var html = [\n '<nav id=\"navigation-panel\" class=\"navigation-panel\" role=\"navigation\"><div class=\"sections\">',\n '<div class=\"section taxonomy-preferences\">',\n '<div class=\"header\">',\n '<h5 class=\"section-heading\">Shortcuts</h5>',\n '</div><!-- close header --><ul class=\"menu\">',\n shortcuts,\n '</ul>',\n '</div>',\n '<div class=\"section taxonomy\">',\n '<div class=\"header\">',\n '<h5 class=\"section-heading\">All Sections</h5>',\n '</div><!-- close header --><ul class=\"menu\">',\n nav,\n '</ul><!-- close primary nav -->',\n '</div>',\n '</div></nav>'\n ].join('');\n\n return html;\n },\n\n modal : function (sData) {\n var output = {};\n output.secondary = '';\n output.tertiary = '';\n\n $.each(sData, function(k, d) {\n if (d.children) {\n output[d.class_name] += '<ul class=\"' + d.class_name + '\" data-parent=\"navId-' + d.parent_id + '\">';\n $.each(d.children, function(k, n) {\n var classes = n.children_in_nav === true ? n.class_name + ' expandable' : n.class_name;\n var href = n.path ? ' href=\"' + n.path + '\"' : '';\n output[d.class_name] += '<li><a id=\"navId-' + n.id + '\" class=\"' + classes + '\"' + href + '>' + n.name + '<div class=\"arrow-right\"><div class=\"arrow-conceal\"></div></div><div class=\"arrow arrow-left\"><div class=\"arrow-conceal\"></div></div></a></li>';\n });\n output[d.class_name] += '</ul>';\n }\n });\n\n return '<div class=\"secondary-container\"><div class=\"header\"><h5 class=\"section-heading\"></h5></div>'\n + output.secondary + '</div>'\n + '<div class=\"tertiary-container\"><div class=\"header\"><h5 class=\"section-heading\"><a></a></h5></div>'\n + output.tertiary + '</div>';\n },\n\n artSubNavigation : function() {\n return [\n '<ul class=\"subNavigation\">',\n '<li id=\"subNav_design\"><a href=\"http://www.nytimes.com/pages/arts/design/index.html\">Art &amp; Design</a></li>',\n '<li id=\"subNav_books\"><a href=\"http://www.nytimes.com/pages/books/index.html\">Books</a></li>',\n '<li id=\"subNav_dance\"><a href=\"http://www.nytimes.com/pages/arts/dance/index.html\">Dance</a></li>',\n '<li id=\"subNav_movies\"><a href=\"http://www.nytimes.com/pages/movies/index.html\">Movies</a></li>',\n '<li id=\"subNav_music\"><a href=\"http://www.nytimes.com/pages/arts/music/index.html\">Music</a></li>',\n '<li id=\"subNav_television\" class=\"selected nochildren\"><a href=\"http://www.nytimes.com/pages/arts/television/index.html\">Television</a></li>',\n '<li id=\"subNav_theater\"><a href=\"http://www.nytimes.com/pages/theater/index.html\">Theater</a></li>',\n '<li id=\"subNav_video-games\"><a href=\"http://www.nytimes.com/pages/arts/video-games/index.html\">Video Games</a></li>',\n '<li id=\"subNav_events\"><a href=\"http://www.nytimes.com/events\">Events</a></li>',\n '<li id=\"subNav_international\"><a href=\"http://www.nytimes.com/pages/arts/international/index.html\">International Arts</a></li>',\n '</ul>'\n ].join('');\n },\n\n theaterSubNavigation : function() {\n return [\n '<ul class=\"subNavigation\">',\n '<li>',\n '<a href=\"http://www.nytimes.com/theater/venues/broadway.html\">Broadway</a>',\n '</li>',\n '<li>',\n '<a href=\"http://www.nytimes.com/theater/venues/off-broadway.html\">Off &amp; Off Off Broadway</a>',\n '</li>',\n '<li>',\n '<a href=\"http://www.nytimes.com/theater/shows/plays.html\">Plays</a>',\n '</li>',\n '<li>',\n '<a href=\"http://www.nytimes.com/theater/shows/musicals.html\">Musicals</a>',\n '</li>',\n '<li>',\n '<a href=\"http://www.nytimes.com/theater/shows/family-friendly.html\">Family Friendly</a>',\n '</li>',\n '<li>',\n '<a href=\"http://www.nytimes.com/theater/shows/recently-opened.html\">Recently Opened</a>',\n '</li>',\n '<li>',\n '<a href=\"http://www.nytimes.com/video/landing/theater/100000001064152/index.html\">Theater Video</a>',\n '</li>',\n '<li class=\"subNavigation-tickets\"><a href=\"http://www.nytimes.com/theater/show/buy-ticket.html\">Tickets &amp; Offers</a></li>',\n '</ul>'\n ].join('');\n }\n };\n\n var open = function () {\n\n if (isNavAnimating === false && $el.hasClass('active') === false) {\n\n var openInit = {\n 'width': singlePanelPartlyShut,\n 'display': 'block',\n 'opacity': '0'\n };\n\n var openMore = {\n 'width': singlePanelWidth,\n 'opacity': '1'\n };\n\n //first move it over most of the way, and make it transparent\n $el.css(openInit);\n $el.toggleClass('active');\n $html.toggleClass('navigation-active');\n isNavAnimating = true;\n\n //materialize partly open, and animate the rest of the way\n $el.animate(openMore, navAnimation, function () {\n isNavAnimating = false;\n\n //hack for ios\n if (isMobile) {\n $('body').css('cursor', 'pointer');\n }\n\n $(document).on('click', handleClickClose);\n });\n\n // start tracking mouse movement for hover intent\n $document.on('mousemove', mousemoveDocument);\n }\n };\n\n var close = function () {\n\n if (isNavAnimating === false && $el.hasClass('active') === true) {\n\n var navMarginTop = $el.css('marginTop'); // for messaging\n\n var shutSome = {\n 'width': singlePanelPartlyShut,\n 'opacity': '0'\n };\n\n navigationModal.close();\n resetNav(2);\n\n isNavAnimating = true;\n $el.animate(shutSome, navAnimation, function () { //animate it partly closed, then disappear\n $el.toggleClass('active');\n $html.toggleClass('navigation-active');\n $(document).off('click', handleClickClose);\n\n //hack for ios\n if (isMobile) {\n $('body').css('cursor', '');\n }\n\n $el.removeAttr('style');\n $el.css('marginTop', navMarginTop); // for messaging\n $el.find('.taxonomy a').removeClass('active'); // Resets active state\n isNavAnimating = false;\n });\n\n $document.off('mousemove', mousemoveDocument); // stop tracking mouse movements\n }\n };\n\n var toggle = function () {\n\n if (isNavAnimating === false && $el.hasClass('active') === false) {\n open();\n } else if (isNavAnimating === false && $el.hasClass('active') === true) {\n close();\n }\n };\n\n var activatePrimaryItem = function (e) {\n e.stopPropagation();\n\n var $target = $(e.target).closest('a');\n\n navigationModal.open();\n repositionModal($target);\n\n if (!$target.hasClass('active') && isNavAnimating === false) {\n\n cancelDelayedModalClose();\n resetNav(2);\n\n // Sets active state for the hovered on taxonomy item\n $el.find('.taxonomy a').removeClass('active');\n $target.addClass('active');\n\n // reset the content\n $navigationModal.find(\".secondary\").removeClass('active');\n\n // set the text of the heading\n $navigationModal.find(\".secondary-container .section-heading\").text($target.text());\n\n // activate the content based on the parent id\n $navigationModal.find(\"[data-parent='\" + $target.attr('id') + \"']\").addClass('active');\n\n }\n };\n\n var activateSecondaryItem = function (e) {\n var $target = $(e.target).closest('a');\n if (!$target.hasClass('active') && isNavAnimating === false) {\n e.preventDefault();\n var $modal = $('#navigationModalContainer');\n\n if ($target.hasClass('expandable')) {\n\n // resets the content\n resetNav(3);\n $modal.find(\".nytModalContent\").addClass('expanded');\n\n // set the text of the heading\n var $heading = $modal.find(\".tertiary-container .section-heading\");\n\n if (typeof $target.attr('href') !== \"undefined\") {\n $heading.html('<a href=\"'+ $target.attr('href') + '\">' + $target.text() + '</a>');\n } else {\n $heading.html($target.text());\n }\n\n // activate the content based on the parent id\n $modal.find(\"[data-parent='\" + $target.attr('id') + \"']\").addClass('active');\n\n // set active class\n $target.addClass('active');\n } else {\n // resets the content\n resetNav(3);\n\n // set active class\n $target.addClass('active');\n }\n }\n };\n\n var tryPrimaryHover = function(e) {\n cancelDelayedClose();\n cancelDelayedModalClose();\n cancelDelayedPrimaryHover();\n\n if ($el.find(\".taxonomy li a.active\").length > 0) { // Only activate hover intent if the modal is active\n var angle = getAngle(mouseLocs[0], mouseLocs[1]);\n\n if (angle > intentRangeLower && angle < intentRangeUpper) {\n delayedPrimaryHover(e); // OUT OF RANGE, START TIMEOUT FOR HOVER\n } else {\n activatePrimaryItem(e); // IN RANGE, ACTIVATE RIGHT AWAY\n }\n } else {\n activatePrimaryItem(e); // IN RANGE, ACTIVATE RIGHT AWAY\n }\n };\n\n var trySecondaryHover = function(e) {\n cancelDelayedClose();\n cancelDelayedModalClose();\n cancelDelayedSecondaryHover();\n\n if ($navigationModal.find(\".nytModalContent\").hasClass('expanded')) { // Only activate hover intent if the tertiary panel is open\n var angle = getAngle(mouseLocs[0], mouseLocs[1]);\n\n if (angle > intentRangeLower && angle < intentRangeUpper) {\n delayedSecondaryHover(e); // Out of range, start timeout for hover\n } else {\n activateSecondaryItem(e); // In range, activate right away\n }\n } else {\n activateSecondaryItem(e);\n }\n };\n\n var repositionModal = function ($target) {\n $navigationModal.css({\n 'top': ($sections.height() - $navigationModal.height() + 30) + 'px',\n 'left': '200px',\n 'margin-left': '0',\n 'margin-top': '0',\n 'width': 'auto'\n });\n\n var $listItem = $target.closest('li');\n var $list = $target.closest('ul');\n\n var activePosition = $listItem.position().top + (Math.floor($listItem.height() / 2)) + 3;\n var base = $list.position().top + $list.height();\n var bottom = base - activePosition;\n\n $navigationPointer\n .removeClass('nytModalPointer nytModalPointerNone')\n .addClass('modal-pointer modal-pointer-left-bottom')\n .html('<div class=\"modal-pointer-conceal\"></div>')\n .css('bottom', bottom + 'px');\n };\n\n var resetNav = function (level) {\n if (level === 2) {\n $navigationModal.find(\".secondary\").removeClass('active');\n }\n\n $navigationModal.find(\".secondary a\").removeClass('active');\n $navigationModal.find(\".tertiary\").removeClass('active');\n $navigationModal.find(\".nytModalContent\").removeClass('expanded');\n\n };\n\n // Get recommended sections from API, de-dupe, then create menus\n var getTaxonomy = function() {\n $.ajax({\n url: taxonomyUrl,\n dataType: 'jsonp',\n jsonpCallback: 'jsonTaxonomyCallback'\n }).done(function (data) {\n if(data.taxonomy && data.shortcuts) {\n processTaxonomy(data);\n }\n });\n };\n\n var getUserInfo = function() {\n $.ajax({\n url: userInfoUrl,\n dataType: 'json'\n }).done(function (data) {\n if(data && data.data && data.data.subscription && data.data.subscription.crosswords && data.data.subscription.crosswords !== \"1\") {\n $('#shortcuts-3300EB4C-284F-4484-AF31-0D7D1DBA4F4C').parent().hide();\n }\n });\n };\n\n var getClassName = function(name) {\n return name.replace(/\\W/g, '').toLowerCase();\n };\n\n // Process taxonomy data\n var processTaxonomy = function(data) {\n var navigation1 = [];\n var navigation2 = [];\n var navigation3 = [];\n var shortcuts = [];\n\n $.each(data.taxonomy, function(x, first) {\n first.class_name = getClassName(first.name);\n\n if (first.show_in_nav === true) {\n navigation1.push(first);\n }\n\n // parse second level\n if (first.children) {\n navigation2.push({\n parent_id : first.id,\n class_name : 'secondary',\n children : []\n });\n\n $.each(first.children, function(key, second) {\n\n second.class_name = getClassName(second.name);\n if (second.children) {\n second.children_in_nav = childrenInNav(second.children);\n }\n\n if (second.show_in_nav === true) {\n navigation2[navigation2.length - 1].children.push(second);\n }\n\n // parse third level\n if (second.children) {\n if (childrenInNav(second.children)) {\n\n navigation3.push({\n parent_id : second.id,\n class_name : 'tertiary',\n children : []\n });\n\n $.each(second.children, function(key, third) {\n third.class_name = getClassName(third.name);\n\n if (third.show_in_nav === true) {\n navigation3[navigation3.length - 1].children.push(third);\n }\n\n });\n\n }\n\n }\n\n });\n\n }\n\n });\n\n $.each(data.shortcuts[getEdition()], function(x, s) {\n shortcuts.push(s);\n });\n\n buildNav(navigation1, navigation2, navigation3, shortcuts);\n setEventHandlers();\n getUserInfo();\n };\n\n var childrenInNav = function(children) {\n var inNav = false;\n $.each(children, function(a, b) {\n if (b.show_in_nav === true) {\n inNav = true;\n }\n });\n\n return inNav;\n\n };\n\n var buildNav = function (navigation1, navigation2, navigation3, shortcuts) {\n $('#navigationModalContainer').find('.nytModalContent').removeClass('singleRule').html(templates.modal(navigation2.concat(navigation3)));\n $('body').prepend(templates.nav(navigation1, shortcuts));\n\n $el = $('#navigation-panel');\n $shell = $('#shell');\n $sections = $('#navigation-panel').find('.sections');\n $navigationModal = $('#navigationModalContainer').find('.navigationModal');\n $navigationPointer = $('#navigationModalContainer').find('.nytModalPointer');\n };\n\n var setEventHandlers = function () {\n $el\n .on('mouseleave', delayedClose)\n .on('mouseenter', cancelDelayedClose)\n .on('mouseenter', '.taxonomy li a', tryPrimaryHover)\n .on('mouseleave', '.taxonomy li a', delayedModalClose)\n .on('click', '.taxonomy li a', activatePrimaryItem)\n .on('click', '.taxonomy-preferences a[href]', handleShortcutClick);\n\n $navigationModal\n .on('mouseover', '.secondary li a', trySecondaryHover)\n .on('click', '.secondary li a.expandable', activateSecondaryItem)\n .on('mouseenter', '.tertiary-container', cancelDelayedSecondaryHover)\n .on('mouseenter', function() {\n cancelDelayedClose();\n cancelDelayedModalClose();\n })\n .on('mouseleave', function() {\n delayedClose();\n delayedModalClose();\n })\n .on('click', '.navigationModal a[href]', handleModalClick);\n\n $('body')\n .on('click', '.masthead-search-button', handleSearchClick)\n .on('submit', '#searchForm', handleSearchSubmit)\n .on('click', '.user-settings-modal .edition-menu a', handleSettingsModalEditionClick)\n .on('click', '.user-settings-modal .help-menu a', handleSettingsModalHelpClick)\n .on('click', '.masthead-login-button a', handleLoginButtonClick)\n .on('click', '#profileDropDownModal .modal-content a', handleLoginModalClick)\n .on('click', '.register-now a', handleRegisterNowClick);\n /* .on('click', '.commentsRefer a, .commentCountLink a', handleCommentsReferClick); */\n\n // ESC key\n $(document).keyup(function(e) {\n if (e.keyCode === 27) {\n close();\n }\n });\n\n $(window)\n .resize(function() {\n close();\n });\n };\n\n var loginDropDown = function() {\n var $tools = $('#memberTools');\n $tools\n .removeAttr('id')\n .addClass('masthead-tools')\n .attr('id', 'masthead-tools');\n\n var $register = $tools.find('li:contains(\"Register\")');\n $register.addClass('register-now');\n var regText = $register.text();\n $register.find('a').text(regText.replace(' Now', ''));\n\n if (getPageCategory() !== 'opinion') {\n $('#masthead').prepend($tools);\n } else {\n $('#page').prepend($tools);\n }\n\n var $modal = $('#profileDropDownModal');\n var $modalContent = $modal.find('.dropDownModalBox');\n\n var data = {};\n\n data.username = $modal\n .find('.dropDownModalLink')\n .text();\n\n data.profileUrl = $modalContent\n .find('.profileDropDownMyProfile a')\n .attr('href');\n\n data.myaccountUrl = $modalContent\n .find('.profileDropDownMyAccount a')\n .attr('href');\n\n data.savedUrl = $modalContent\n .find('.profileDropDownMySavedArticles a')\n .attr('href');\n\n data.logOutUrl = $modalContent\n .find('.profileDropDownLogOut a')\n .attr('href');\n\n $modal.addClass('user-name-modal');\n $modalContent.append(templates.loginModal(data));\n\n setTimeout(function() {\n var img = $modalContent\n .find('img')\n .removeClass('runaroundLeft');\n $modal\n .find('.modal-header h5 a')\n .append(img);\n }, 2000);\n };\n\n var settingsDropDown = function() {\n var $tools = $('#masthead-tools');\n var $modal = $('.user-settings-modal');\n\n $modal.empty().append(templates.settingsModal());\n var $list = $modal.find('.edition-menu ul');\n var $itemInternational = $list.find(\"li a[data-edition='international']\");\n var $itemUs = $list.find(\"li a[data-edition='us']\");\n\n if (getEdition() === 'global') {\n $itemInternational.addClass('selected');\n stripInternational($itemUs);\n } else {\n $itemUs.addClass('selected');\n checkInternationalMapping($itemInternational);\n }\n\n $list.find('li a').on('click', function(e) {\n var edition = $(this).attr('data-edition');\n editionToggleCallback(edition);\n });\n\n $('body').on('click', function(e) {\n var isSettingsModal = $(e.target).closest('.user-settings-modal').length;\n\n if ($(e.target).closest('.modal-pointer').length > 0) {\n isSettingsModal = 0;\n }\n\n if (isSettingsModal !== 1) {\n userSettingsModal.close();\n }\n });\n\n var $pointer = $('.user-settings-modal .modal-pointer, #profileDropDownModal .modal-pointer');\n $pointer.on('click', function() {\n $(document).trigger('click');\n });\n };\n\n var checkInternationalMapping = function(item) {\n $.each(internationalMap, function(i,sectionName) {\n if (window.location.pathname.match(sectionName)) {\n item.attr('href', '/pages/' + sectionName + '/international/index.html');\n }\n });\n };\n\n var stripInternational = function(item) {\n var href = item.attr('href');\n item.attr('href', href.replace('/international', ''));\n };\n\n var editionToggleCallback = function (edition) {\n\n switch (edition) {\n case 'international':\n NYTD.EditionPref.setGlobal();\n window.dcsMultiTrack && window.dcsMultiTrack('DCS.dcssip', 'www.nytimes.com', 'DCS.dcsuri', '/toggleNYTtoIHT.html', 'WT.ti', 'toggleNYTtoIHT', 'WT.z_dcsm', '1');\n break;\n case 'us':\n NYTD.EditionPref.setUS();\n window.dcsMultiTrack && window.dcsMultiTrack('DCS.dcssip', 'global.nytimes.com', 'DCS.dcsuri', '/toggleIHTtoNYT.html', 'WT.ti', 'toggleIHTtoNYT', 'WT.z_dcsm', '1');\n break;\n case 'chinese':\n if (getEdition() === 'global') {\n window.dcsMultiTrack && window.dcsMultiTrack('DCS.dcssip', 'global.nytimes.com', 'DCS.dcsuri', '/toggleIHTtoCHNS', 'WT.ti', 'toggleIHTtoCHNS', 'WT.z_dcsm', '1');\n } else {\n window.dcsMultiTrack && window.dcsMultiTrack('DCS.dcssip', 'www.nytimes.com', 'DCS.dcsuri', '/toggleNYTtoCHNS', 'WT.ti', 'toggleNYTtoCHNS', 'WT.z_dcsm', '1');\n }\n break;\n }\n };\n\n var buildMastheadContent = function () {\n var pageCategory = getPageCategory();\n var $branding = $('#branding');\n var $memberTools = $('#masthead-tools');\n var $searchTool = $('#searchWidget');\n\n if (pageCategory !== 'opinion') {\n $('#masthead').prepend(templates.sectionsButton);\n } else {\n $('#masthead').before(templates.sectionsButton);\n }\n\n $memberTools\n .find('li:contains(\"Log In\")')\n .addClass('masthead-login-button')\n .find('a')\n .text('Sign In');\n\n $memberTools\n .find('li:contains(\"Help\")')\n .remove();\n\n $memberTools.append('<li class=\"settings-modal\"><span><i class=\"icon\"></i></span></li>');\n\n if (pageCategory === 'arts' && getPageSubCategory() === 'television') {\n $('.navigation .selected:eq(0)').append(templates.artSubNavigation());\n }\n\n if (pageCategory !== 'opinion') {\n\n // SEARCH\n $searchTool\n .find('form')\n .prepend('<img class=\"close\" src=\"' + NYTD.Hosts.imageHost + '/images/icons/x_icon_gray_10x10.png\" onclick=\"NYTD.reskin.hideSearch()\"/>');\n $searchTool\n .find('#searchSubmit')\n .replaceWith('<input class=\"searchSubmit\" type=\"submit\" value=\"GO\">');\n\n $('#masthead-buttons-container').append($searchTool);\n\n }\n\n if ((pageCategory === 'opinion' && getPageSubCategory() === '') || pageCategory === 'magazine') {\n $branding\n .find('img')\n .replaceWith('<img src=\"' + NYTD.Hosts.imageHost + '/images/misc/nytlogo152x23.gif\" alt=\"New York Times\" />');\n }\n\n if (pageCategory === 'opinion' && getPageSubCategory() === 'international') {\n $branding\n .addClass('international-branding')\n .find('img')\n .replaceWith('<img src=\"' + NYTD.Hosts.imageHost + '/images/misc/international-logo-205x19.png\" alt=\"New York Times\" />');\n }\n\n\n $('#masthead-buttons-container').append($branding);\n\n if (pageCategory === 'business' && getPageSubCategory() === '') {\n $('#masthead')\n .before($('#masthead-buttons-container'))\n .before($('#masthead-tools'))\n\n }\n\n if (pageCategory === 'movies' && getPageSubCategory() === '') {\n $('.subNavigation .firstColumn .columnGroup').prependTo('.cColumn');\n }\n\n if (pageCategory === 'health' || pageCategory === 'theater') {\n $('.subNavigation .first .columnGroup').prependTo('.bColumn');\n }\n\n if (pageCategory === 'your-money') {\n $('.subNavigation .first .columnGroup').prependTo('.cColumn');\n }\n\n if (pageCategory === 'theater') {\n $('.navigation .selected:eq(0)').append(templates.theaterSubNavigation());\n }\n\n var $parent = $('.navigation .selected:eq(0) a:eq(0)');\n if ( $parent.length > 0 ) {\n\n var hosts = /dev\\.|stg\\./;\n var href = $parent.attr('href').replace(hosts, '');\n var $current = $('#masthead h2 > a');\n var currentHref = $current.attr('href').replace(hosts, '');\n\n if (href !== currentHref) {\n createSubnavBack(href, $parent.text());\n }\n }\n\n };\n\n var createSubnavBack = function(href, text) {\n if (getPageCategory() !== 'greathomesanddestinations') {\n if ($('ul.subNavigation').length > 0) {\n $('.subNavigation').prepend('<li class=\"subnavBack\"><a href=\"' + href + '\"><div class=\"arrow arrow-left\"><div class=\"arrow-conceal\"></div></div>' + text + '</a></li>');\n } else if ($('div.subNavigation').length > 0) {\n $('.subNavigation').prepend('<div class=\"subnavBack\"><a href=\"' + href + '\"><div class=\"arrow arrow-left\"><div class=\"arrow-conceal\"></div></div>' + text + '</a></div>');\n }\n }\n }\n\n var showSearch = function() {\n $('#shell').find('.masthead-button, #branding').fadeOut(function(){\n $('#searchWidget').fadeIn(function(){\n $('#searchQuery, #bsearchQuery').focus();\n });\n });\n };\n\n var hideSearch = function() {\n $('#searchWidget').fadeOut(function(){\n $('#searchQuery, #bsearchQuery').val('');\n $('#shell').find('.masthead-button, #branding').fadeIn();\n });\n };\n\n var mousemoveDocument = function(e) {\n if (mTimeout) {\n mouseLocs.push({x: e.pageX, y: e.pageY});\n\n if (mouseLocs.length > mouseLocsTracked) {\n mouseLocs.shift();\n }\n\n startMTimeout();\n }\n };\n\n var startMTimeout = function() {\n mTimeout = false;\n setTimeout(function() {\n mTimeout = true;\n }, 5);\n };\n\n var getAngle = function(a, b) {\n if (a && b) {\n var x1 = a.x;\n var y1 = a.y;\n\n var x2 = b.x;\n var y2 = b.y;\n\n var dx = x2 - x1;\n var dy = y2 - y1;\n var result = Math.round((Math.atan2(dx, dy) * 180 / Math.PI) * 10) / 10;\n\n return result;\n } else {\n return null;\n }\n };\n\n var execReskin = function() {\n\n navigationModal = NYTD.UI.OverlayModal(navigationModalOptions).addToPage();\n userSettingsModal = NYTD.UI.OverlayModal(userSettingsModalOptions).addToPage();\n\n getTaxonomy();\n\n $(document).ready(function() {\n loginDropDown();\n settingsDropDown();\n\n buildMastheadContent();\n });\n };\n\n var delayedClose = function () {\n timer.navClose = window.setTimeout(close, navTimeout);\n };\n\n var cancelDelayedClose = function () {\n window.clearTimeout(timer.navClose);\n };\n\n var delayedModalClose = function () {\n cancelDelayedPrimaryHover();\n cancelDelayedSecondaryHover();\n\n timer.modalClose = window.setTimeout(function() {\n $el.find('.taxonomy a').removeClass('active'); // resets taxonomy active state\n navigationModal.close();\n }, navTimeout);\n };\n\n var cancelDelayedModalClose = function () {\n window.clearTimeout(timer.modalClose);\n };\n\n var delayedPrimaryHover = function (e) {\n timer.primaryHoverIntent = window.setTimeout(function(){\n activatePrimaryItem(e);\n }, hoverTimeout);\n };\n\n var cancelDelayedPrimaryHover = function () {\n window.clearTimeout(timer.primaryHoverIntent);\n };\n\n var delayedSecondaryHover = function (e) {\n timer.secondaryHoverIntent = window.setTimeout(function(){\n activateSecondaryItem(e);\n }, hoverTimeout);\n };\n\n var cancelDelayedSecondaryHover = function () {\n window.clearTimeout(timer.secondaryHoverIntent);\n };\n\n var handleClickClose = function (e) {\n if ($(e.target).closest('#navigation-panel, .navigationModal').length === 0) {\n close();\n }\n };\n\n // Tracking\n\n var handleRegisterNowClick = function (e) {\n var $el = $(e.currentTarget);\n $el.attr('href', 'https://myaccount.nytimes.com/register');\n var href = trackingAppendParams($el.attr('href'),\n trackingCombineData({\n 'module': 'Registration',\n 'contentCollection': getPageCategory()\n })\n );\n $el.attr('href', href);\n };\n\n var handleLoginModalClick = function (e) {\n var $el = $(e.currentTarget);\n\n var data = {\n 'contentCollection': getPageCategory()\n };\n\n if ($el.hasClass('login-modal-profile')) {\n data.module = 'MyProfile';\n }\n\n if ($el.hasClass('login-modal-account')) {\n data.module = 'MyAccount';\n }\n\n if ($el.hasClass('login-modal-saved')) {\n data.module = 'MySavedItems';\n }\n\n if ($el.hasClass('log-out-button')) {\n data.module = 'LogOut';\n }\n\n var href = trackingAppendParams($el.attr('href'),\n trackingCombineData(data)\n );\n\n $el.attr('href', href);\n };\n\n var handleLoginButtonClick = function (e) {\n var $el = $(e.currentTarget);\n var href = trackingAppendParams($el.attr('href'),\n trackingCombineData({\n 'module': 'Login',\n 'contentCollection': getPageCategory()\n })\n );\n $el.attr('href', href);\n };\n\n var handleSearchClick = function (e) {\n showSearch();\n\n trackingTrigger('masthead-search-click',\n trackingCombineData({\n 'module': 'SearchOpen',\n 'eventName': 'OpenSearchBar'\n })\n );\n };\n\n var handleSettingsModalEditionClick = function(e) {\n var $el = $(e.currentTarget);\n var editionData = {\n 'us': 'EditionToggleToUS',\n 'international': 'EditionToggleToGlobal',\n 'chinese': 'EditionToggleToCHNS',\n };\n var href = trackingAppendParams($el.attr('href'),\n trackingCombineData({\n 'module': editionData[$el.data('edition')],\n 'contentCollection': getPageCategory()\n })\n );\n $el.attr('href', href);\n };\n\n var handleSettingsModalHelpClick = function (e) {\n var $el = $(e.currentTarget);\n\n var data = {\n 'contentCollection': getPageCategory()\n };\n\n if ($el.hasClass('settings-faq')) {\n data.module = 'FAQ';\n }\n\n if ($el.hasClass('settings-contact')) {\n data.module = 'ContactUs';\n }\n\n var href = trackingAppendParams($el.attr('href'),\n trackingCombineData(data)\n );\n\n $el.attr('href', href);\n };\n\n var handleSearchSubmit = function (e) {\n e.preventDefault();\n var url = searchUrl + $('#searchQuery, #bsearchQuery').val();\n\n var href = trackingAppendParams(url,\n trackingCombineData({\n 'module': 'SearchSubmit',\n 'contentCollection': getPageCategory()\n })\n );\n\n window.location = href;\n };\n\n var handleShortcutClick = function (e) {\n var $el = $(e.currentTarget);\n var href = trackingAppendParams($el.attr('href'),\n trackingCombineData({\n 'module': 'SectionsNav',\n 'version': 'Shortcuts',\n 'contentCollection': $.trim($el.text())\n })\n );\n\n $el.attr('href', href);\n };\n\n var handleModalClick = function (e) {\n var $el = $(e.currentTarget);\n var href = trackingAppendParams($el.attr('href'),\n trackingCombineData({\n 'module': 'SectionsNav',\n 'version': 'BrowseTree',\n 'contentCollection': $.trim($el.text()),\n 'contentPlacement': $el.closest('ul').hasClass('secondary') ? 2 : 3\n })\n );\n\n $el.attr('href', href);\n };\n\n /* var handleCommentsReferClick = function (e) {\n var $el = $(e.currentTarget);\n var region = $el.parents('div[id]:eq(0)').attr('id');\n var href = trackingAppendParams($el.attr('href'),\n {\n 'action': 'click',\n 'module': 'Comments',\n 'contentCollection': getPageCategory(),\n 'version': 'HPCommentsRefer',\n 'region': region,\n 'pgtype': getPageType()\n }\n );\n\n $el.attr('href', href);\n }; */\n\n /**\n * Utility method to send an object to the TAGX event proxy\n *\n * @method trackingTrigger\n * @param {String} identifying string for TAGX handling\n * @param {Object} data to send\n */\n var trackingTrigger = function (action, trackingData) {\n if (window.TAGX && window.TAGX.EventProxy && window.TAGX.EventProxy.trigger) {\n try {\n window.TAGX.EventProxy.trigger(action, trackingData);\n }\n catch(e) {\n //Tagx didn't work :-/\n }\n }\n };\n\n /**\n * Creates an anchor for a provided url\n *\n * @public\n * @method createAnchor\n * @param url {String} an object similar to window.location\n **/\n var createAnchor = function (url) {\n var anchor = document.createElement('a');\n anchor.href = url;\n return anchor;\n };\n\n /**\n * Utility method to combine base tracking data with the provided object\n *\n * @method trackingCombineData\n * @param {Object} data to combine or override with base data\n * @return {Object}\n */\n var trackingCombineData = function (obj) {\n try {\n return $.extend({}, trackingBaseData, obj);\n }\n catch(e) {\n //just in case\n }\n };\n\n /**\n * Utility method to convert an object into a query string for appending to URLs\n *\n * @method trackingAppendParams\n * @param {String} href the href value from the link\n * @param {Object} paramsObj the object to serialize into a string for the URL\n * @return {String} the new url with the meta data appended to it\n */\n var trackingAppendParams = function (href, paramsObj) {\n var key;\n var aElem = createAnchor(href);\n var query = aElem.search;\n var separator = query.length > 0 && query.indexOf('?') === 0 ? '&' : '?';\n var cookieName = 'qry' + Math.ceil(Math.random() * 1000);\n var paramsList = [];\n\n //add the custom cookie to the tracking parameters\n paramsObj.t = cookieName;\n\n for (key in paramsObj) {\n var paramPart = encodeURIComponent(key) + '=';\n paramsList.push(paramPart + encodeURIComponent(paramsObj[key]));\n\n if (query.indexOf(paramPart) !== -1) {\n query = query.replace(new RegExp('&?' + paramPart + '[^&]*'), '');\n }\n }\n\n var trackingParamsStr = paramsList.join('&');\n var retUrl = [\n aElem.protocol !== ':' ? aElem.protocol + '//' : '',\n aElem.hostname !== '' ? aElem.hostname : '',\n '/', aElem.pathname.replace(/^\\//, ''),\n aElem.search, separator, trackingParamsStr,\n aElem.hash\n ].join('');\n\n // cookie expires in 2 min\n var cookieExp = new Date();\n cookieExp.setMinutes(cookieExp.getMinutes() + 2);\n // try to set the cookie\n //cookies.writeCookie(cookieName, trackingParamsStr, { expires: cookieExp });\n // did it work?\n //var cookieFailed = cookies.readCookie(cookieName) === null;\n\n //failed cookies get an extra paramater for tracking purposes.\n //if (cookieFailed) {\n // trackingParamsStr = 'alxcookie=0&' + trackingParamsStr;\n //}\n\n //return cookieFailed ? href + separator + trackingParamsStr : href + separator + 't=' + cookieName;\n return retUrl;\n };\n\n // Try reskin\n\n var tryReskin = function() {\n if ($('html').hasClass('NYT5Style')) {\n if ($('#masthead').length > 0) {\n execReskin();\n } else {\n setTimeout(function() {\n tryReskin();\n }, 100);\n }\n }\n };\n\n tryReskin();\n\n return {\n open : open,\n close : close,\n toggle : toggle,\n showSearch : showSearch,\n hideSearch : hideSearch\n };\n\n}(NYTD.jQuery));\n" }, { "alpha_fraction": 0.47579425573349, "alphanum_fraction": 0.5, "avg_line_length": 29.022727966308594, "blob_id": "caeb58c97ebdd28531d3c365d0d3c51d6591f60b", "content_id": "3e8745650367f51091e051af2f46f01c20e05db1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1322, "license_type": "permissive", "max_line_length": 190, "num_lines": 44, "path": "/servers/demo-scaleout/html/nyc-1/wtinit.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "function DcsInit(){\n this.enabled=true;\n this.trackevents=gtrackevents;\n this.dcsid=gdcsid;\n this.fpcdom = (function(){ \n var d = document.location.hostname.split('.'),\n l = d.length,\n fpcdom = (l >= 2) ? \".\" + d[l-2] + \".\" + d[l-1] : \"\";\n return fpcdom;\n })();\n this.domain=gdomain;\n this.exre=(function(){\n if (window.RegExp){\n return(new RegExp(\"dcs(uri)|(ref)|(aut)|(met)|(sta)|(sip)|(pro)|(byt)|(dat)|(p3p)|(cfg)|(redirect)|(cip)\",\"i\"));\n }\n else{\n return(\"\");\n }\n })();\n this.fpc=\"WT_FPC\";\n this.i18n=false;\n this.images=[];\n this.index=0;\n this.qp=[];\n this.re=(function(){\n if (window.RegExp){\n return(this.i18n?{\"%25\":/\\%/g}:{\"%09\":/\\t/g,\"%20\":/ /g,\"%23\":/\\#/g,\"%26\":/\\&/g,\"%2B\":/\\+/g,\"%3F\":/\\?/g,\"%5C\":/\\\\/g,\"%22\":/\\\"/g,\"%7F\":/\\x7F/g,\"%A0\":/\\xA0/g});\n }\n else{\n return(\"\");\n }\n })();\n this.timezone=-5;\n// var t=this;\n// (function(){\n// if (t.enabled&&(document.cookie.indexOf(t.fpc+\"=\")==-1)&&(document.cookie.indexOf(\"WTLOPTOUT=\")==-1)){\n// document.write(\"<scr\"+\"ipt type='text/javascript' src='\"+\"http\"+(window.location.protocol.indexOf('https:')==0?'s':'')+\"://\"+t.domain+\"/\"+t.dcsid+\"/wtid.js\"+\"'><\\/scr\"+\"ipt>\");\n// }\n// })();\n}\nvar DCS={};\nvar WT={};\nvar DCSext={};\nvar dcsInit=new DcsInit();\n\n" }, { "alpha_fraction": 0.5850714445114136, "alphanum_fraction": 0.6104344129562378, "avg_line_length": 37.41453170776367, "blob_id": "3edd8bd6244790cc2ffbeea4f8c4bc9f34f19792", "content_id": "95e2c7af0da669a3d644088bee8df6b8fca21b16", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 17979, "license_type": "permissive", "max_line_length": 512, "num_lines": 468, "path": "/servers/demo-scaleout/html/nyc-3/googleads.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "/*global NYTD, window, escape */\n/* \t \n$Id: googleads.js 62412 2011-03-23 20:10:19Z helckt $ \t \n(c) 2010 The New York Times Company \t \n*/\n\n\nNYTD.GoogleAds = NYTD.GoogleAds || {\n\t\n\tdefaultGoogleParamsList: {\n\t\tAFS:{\n\t\t\t'google_ad_output': 'js',\n\t\t\t'google_afs_ad': 'w2n4',\n\t\t\t'google_afs_client': 'newyorktimes',\n\t\t\t'google_afs_query': null,\n\t\t\t'google_afs_adsafe': 'high',\n\t\t\t'google_afs_channel': null,\n\t\t\t'google_afs_adtest': 'off'\n\t\t},\n\t\tAFC:{\n\t\t\t'google_adtest': 'off',\n\t\t\t'google_ad_type': 'text',\n\t\t\t'google_ad_client': 'nytimes_article_var',\n\t\t\t'google_ad_output': 'js',\n\t\t\t'google_ad_channel': null,\n\t\t\t'google_feedback': 'on',\n\t\t\t'google_skip': 0,\n\t\t\t'google_safe': 'high',\n\t\t\t'google_hints': null,\n\t\t\t'google_contents': null,\n\t\t\t'google_page_url': null,\n\t\t\t'google_targeting': null,\n\t\t\t'google_image_size': null,\n\t\t\t'google_max_num_ads': 3\n\t\t},\n\t\tRAD:{\n\t\t\t'google_adtest': 'off',\n\t\t\t'google_ad_client': 'nytimes_article_var',\n\t\t\t'google_ad_output': 'js',\n\t\t\t'google_ad_channel': null,\n\t\t\t'google_safe': 'high',\n\t\t\t'google_page_url': null,\n\t\t\t'google_max_num_ads': 0,\n\t\t\t'google_num_radlinks': 5,\n\t\t\t'google_max_radlink_len': 23,\n\t\t\t'google_kw_type': 'broad',\n\t\t\t'google_kw': null\n\t\t},\n\t\tLB:{\n\t\t\t'google_ad_client': 'ca-nytimes_display_html',\n\t\t\t'google_alternate_ad_url': 'http://www.nytimes.com/ads/remnant/networkredirect-leaderboard.html',\n\t\t\t'google_ad_width': 728,\n\t\t\t'google_ad_height': 90,\n\t\t\t'google_ad_format': '728x90_pas_abgc',\n\t\t\t'google_ad_type': 'image',\n\t\t\t'google_safe': 'high',\n\t\t\t'google_targeting': 'site',\n\t\t\t'google_ad_channel': null\n\t\t}\n\t},\n\t\n\tcpcCount: 0,\n\tmetaTagCache: {},\n\tdebugElement: {},\n\n\ttargetList: {\n\t\t'sponLink': ['adxSponLink', 'SponLink', 'adxSponLinkA', 'SponLinkA'],\n\t\t'sponLinkA': ['adxSponLinkA', 'SponLinkA', 'adxSponLink', 'SponLink'],\n\t\t'middleRight': ['MiddleRight', 'SFMiddle']\n\t},\t\n\tadTarget: '',\n\n\ttemplates: {\n\t\t\"afsWideAd\" :\n\t\t\t'<div class=\"ad\">' +\n\t\t\t\t'<a href=\"#\" onclick=\"linkbox(\\'<%=url%>\\',\\'popWin\\')\">' +\n\t\t\t\t\t'<span class=\"blue\"><%=line1%></span><%=line2%><br/>'+\n\t\t\t\t\t'<div class=\"link\"><%=visibleUrl%></div>'+\n\t\t\t\t'</a>' +\n\t\t\t'</div>',\n\t\t\"afsNarrowAd\" :\n\t\t\t'<div class=\"ad\">' +\n\t\t\t\t'<a onclick=\"linkbox(\\'<%=url%>\\',\\'popWin\\')\" class=\"blue\" href=\"#\"><%=line1%></a>' +\n\t\t\t\t'<br/><%=line2%><br/><%=line3%><br/>' +\n\t\t\t\t'<div class=\"link\">' +\n\t\t\t\t\t'<a onclick=\"linkbox(\\'<%=url%>\\',\\'popWin\\')\" class=\"green\" href=\"#\"><%=visibleUrl%></a>' +\n\t\t\t\t'</div>' +\n\t\t\t'</div>',\n\t\t\"radLink\":\n\t\t\t'<div class=\"ad\">' +\n\t\t\t\t'&raquo; ' +\n\t\t\t\t'<a href=\"http://<%=queryHost%>/search/query?srchst=r&term=<%=term%>&google_ad_channel=health&' +\n\t\t\t\t'google_ad_client=ca-nytimes_radlinks_js&google_page_url=<%=thisPage%>\">' +\n\t\t\t\t\t'<%=term%>' +\n\t\t\t\t'</a>' +\n\t\t\t'</div>',\n\t\t\"afcAd\":{\n\t\t\t'text':\n\t\t\t\t'</tr><tr class=\"listing\" bidtype=\"<%=bidType%>\" targetingType=\"<%=targetingType%>\">' +\n\t\t\t\t'<td colspan=\"2\" valign=\"middle\">' +\n\t\t\t\t\t'<a class=\"first\" target=\"_blank\" href=\"<%=url%>\"><%=line1%></a><br/>' +\n\t\t\t\t\t'<%=line2%><br/>' +\n\t\t\t\t\t'<%=line3%><br/>' +\n\t\t\t\t\t'<a class=\"last\" target=\"_blank\" href=\"<%=url%>\"><%=visibleUrl%></a>' +\n\t\t\t\t'</td>',\n\t\t\t'image':\n\t\t\t\t'<a href=\"<%=url%>\" target=\"_top\" title=\"go to <%=visibleUrl%>\" bidtype=\"<%=bidType%>\" targetingType=\"<%=targetingType%>\">' +\n\t\t\t\t\t'<img border=\"0\" src=\"<%=imageUrl%>\" width=\"<%=imageWidth%>\" height=\"<%=imageHeight%>\">' +\n\t\t\t\t'</a>',\n\t\t\t'flash':\n\t\t\t\t'<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0\" width=\"<%=imageWidth%>\" height=\"<%=imageHeight%>\" bidtype=\"<%=bidType%>\" targetingType=\"<%=targetingType%>\">' +\n\t\t\t\t\t'<param name=\"movie\" value=\"<%=imageUrl%>\">' +\n\t\t\t\t\t'<param name=\"quality\" value=\"high\">' +\n\t\t\t\t\t'<param name=\"AllowScriptAccess\" value=\"never\">' +\n\t\t\t\t\t'<embed src=\"<%=imageUrl%>\" width=\"<%=imageWidth%>\" height=\"<%=imageHeight%> type=\"application/x-shockwave-flash\" AllowScriptAccess=\"never\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\"></embed>' +\n\t\t\t\t'</object>'\n\t\t}\t\n\t},\n\n\tloadCss: function() {\n\t\t// check if googleads.css is already loaded:\n\t\tvar cssLoaded = 0;\n\t\tvar linkNodes = $$('link');\n\t\tif(linkNodes.any(function(x) {\n\t\t\treturn x.getAttribute('href').indexOf(\"2.0/styles.css\") != -1 ;\n\t\t})) { cssLoaded = 1; }\n\t\t\n\t\tif(!cssLoaded) {\n\t\t\tvar cssLink =document.createElement(\"link\");\n\t\t\tcssLink.setAttribute(\"rel\", \"stylesheet\")\n\t\t\tcssLink.setAttribute(\"type\", \"text/css\")\n\t\t\tcssLink.setAttribute(\"href\", NYTD.Hosts.cssHost + \"/css/0.1/screen/common/googleads.css\")\n\t\t\t$$(\"head\")[0].appendChild(cssLink)\n\t\t}\n\t},\n\n\tgetQueryParam: function(defaultQuery, key) {\n\t\tkey = key || \"query\";\n\t\tvar query = window.location.toString().toQueryParams()[key] || defaultQuery;\n\t\tif (!query) {\n\t\t\tquery = $$('meta[name=\"CG\"]')[0];\n\t\t\tquery = query?query.getAttribute(\"content\"):null;\n\t\t}\n\t\telse {\n\t\t\tquery = decodeURI(query);\n\t\t\tquery = query.replace(/'/g, \"\\\\'\");\n\t\t}\n\t\treturn query;\n\t},\n\n\n\tgetFirstGood: function() {\n\t\tfor(var i = 0; i < arguments.length; i++) {\n\t\t\tif(\"undefined\" !== typeof(arguments[i]) && \"undefined\" !== arguments[i] && null !== arguments[i] && '' !== arguments[i] && arguments[i] === arguments[i]) {\n\t\t\t\treturn arguments[i];\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t},\n\n\tgetParsedMetaTag: function( metaTagName ) {\n\t\tif ( !this.metaTagCache[metaTagName] ) {\n\t\t\tvar metaTagValue = '';\n\n\t\t\tif ( !this.metaTagCache.metaTags ) {\n\t\t\t\tthis.metaTagCache.metaTags = $('meta');\n\t\t\t}\n\n\t\t\tfor ( var m in this.metaTagCache.metaTags ) {\n\t\t\t\tif ( this.metaTagCache.metaTags[m].name == metaTagName ) {\n\t\t\t\t\tmetaTagValue = this.metaTagCache.metaTags[m].content;\n\t\t\t\t\tmetaTagValue = metaTagValue.replace( /[\\s\\,\\.]+/g, '_' );\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.metaTagCache[metaTagName] = metaTagValue;\n\t\t}\n\t\treturn this.metaTagCache[metaTagName];\n\t},\n\n\n\n\tsetDebugElement: function(adProgram) {\n\t\tvar w = window;\n\t\tvar s1 = \"\", s2 = \"\";\n\t\tif(window.location.search.match(/ga_debug=1/)) { \n\t\t\ts1 += \"<div style=\\\"display:none\\\" class=\\\"googleDebug\\\"\";\n\n\t\t\t$H(this.defaultGoogleParamsList[adProgram]).each(function(pair) {\n\t\t\t\tif(typeof(w[pair.key]) !== \"undefined\" && w[pair.key] !== \"\") {\t\t\t\t\n\t\t\t\t\ts1 += ' ' + pair.key + '=\"' + w[pair.key] + '\"';\n\t\t\t\t\ts2 += '\\r\\n' + pair.key + ':\\t\"' + w[pair.key] + '\"';\n\t\t\t\t}\t\n\t\t\t}, this);\n\t\t\t\n\t\t\ts1 += \"></div>\";\n\t\t\tNYTD.GoogleAds.debugElement.html = s1;\n\t\t\tNYTD.GoogleAds.debugElement.text = s2;\n\t\t}\t\n\t},\n\n\n\tgetGoogleAds: function(adProgram, paramList) {\n\t\tif(paramList === undefined) { return; }\n\n\t\tNYTD.GoogleAds.preserveAppParams();\n\t\tNYTD.GoogleAds.resolveGoogleVars(adProgram, paramList);\n\t\tNYTD.GoogleAds.setDebugElement(adProgram);\n\n\t\tif(adProgram === \"AFS\") {\n\t\t\twindow.google_afs_request_done = NYTD.GoogleAds.googleAfsRequestDone;\n\t\t\tNYTD.require('http://www.google.com/afsonline/show_afs_ads.js', true);\n\t\t}\n\t\telse if(adProgram === \"AFC\" || adProgram === \"RAD\" || adProgram === \"LB\") {\n\t\t\twindow.google_ad_request_done = NYTD.GoogleAds.googleAdRequestDone;\n\t\t\twindow.google_radlink_request_done = NYTD.GoogleAds.googleRadlinkRequestDone;\n\t\t\tNYTD.require('http://pagead2.googlesyndication.com/pagead/show_ads.js', true);\n\t\t}\n\t},\n\n\tpreserveAppParams: function() {\n\t\t/* look for the GoogleAds global variables that might be set by the app and save them. They\n\t\t * may or may not be suffixed with 'nyt_'. This is called for each GoogleAds position but\n\t\t * only does anything the first time it is called.\n\t\t */\n\t\tvar w = window;\n\t\tif(!this.appParams) {\n\t\t\tthis.appParams = {};\n\t\t\t$H(this.defaultGoogleParamsList).each(function(pair) {\n\t\t\t\t$H(pair.value).each(function(pair2) {\n\t\t\t\t\tif(w['nyt_' + pair2.key] || w[pair2.key]) {\n\t\t\t\t\t\tthis.appParams[pair2.key] = this.getFirstGood(w['nyt_' + pair2.key], w[pair2.key]);\n\t\t\t\t\t}\n\t\t\t\t}, this);\n\t\t\t}, this);\n\t\t}\n\t},\n\n\tclearGoogleParams: function(adProgram) {\n\t\tvar w = window;\n\t\t$H(this.defaultGoogleParamsList[adProgram]).each(function(pair) {\n\t\t\tw[pair.key[0]] = null;\n\t\t}, this);\n\t},\n\n\tresolveGoogleVars: function(adProgram, adxParams) {\n\t\tvar w = window;\n\n\t\t$H(this.defaultGoogleParamsList[adProgram]).each(function(pair){\n\t\t\tvar param = pair.key;\n\t\t\tvar defaultValue = pair.value;\n\t\t\tif(adxParams[param] || this.appParams[param] || defaultValue) {\n\t\t\t\tw[param] = this.getFirstGood(this.appParams[param], adxParams[param], defaultValue);\n\t\t\t}\n\t\t}, this);\n\t\n\t\tif(adProgram === \"AFS\") {\n\t\t\tw.google_afs_query = this.getQueryParam();\n\t\t\tw.google_afs_channel = [this.appParams.google_afs_channel, adxParams.google_afs_channel].join(' ');\n\t\t\tw.google_afs_adtest = NYTD.env === \"production\" ? \"off\" : \"on\";\n\t\t\tthis.narrowPosition = this.getFirstGood(adxParams.narrowPosition, 'SponLink');\n\t\t\tthis.widePosition = this.getFirstGood(adxParams.widePosition, 'SponLinkA');\n\t\t\tthis.relatedAdsPosition = this.getFirstGood(adxParams.relatedAdsPosition, 'SponLink');\n\t\t}\n\n\t\telse if(adProgram === \"AFC\") {\n\t\t\tw.google_ad_channel = [this.appParams.google_ad_channel, adxParams.google_ad_channel].join(' ');\n\t\t\tw.google_skip = this.getFirstGood(NYTD.GoogleAds.cpcCount, 0);\n\t\t\tw.google_adtest = NYTD.env === \"production\" ? \"off\" : \"on\";\n\t\t\tif(adxParams.ad_target) {\n\t\t\t\tthis.adTarget = adxParams.ad_target;\n\t\t\t}\n\t\t\telse if(adxParams.ad_target_list && this.targetList[adxParams.ad_target_list]) {\n\t\t\t\tthis.adTarget = this.targetList[adxParams.ad_target_list].find(function(t){ return($(t) && !$(t + '_googleAds')); });\n\t\t\t}\t\n\n\t\t}\n\n\t\telse if(adProgram === \"RAD\") {\n\t\t\tw.google_ad_channel = [this.appParams.google_ad_channel, adxParams.google_ad_channel].join(' ');\n\t\t\tw.google_adtest = NYTD.env === \"production\" ? \"off\" : \"on\";\n\t\t\tthis.ad_target = adxParams.ad_target;\n\t\t}\n\t\t\n\t\telse if(adProgram === \"LB\") {\n\t\t\tw.google_ad_channel = [this.appParams.google_ad_channel, adxParams.google_ad_channel].join(' ');\n\t\t\tw.google_adtest = NYTD.env === \"production\" ? \"off\" : \"on\";\n\t\t\tthis.ad_target = adxParams.ad_target;\n\t\t}\n\n\t\tvar adChannelYear;\n\t\tvar year = '';\n\t\tif(typeof(getMetaTagValue(\"dat\")) === \"string\") {\n\t\t\tyear = parseInt(getMetaTagValue(\"dat\").substr(-4), 10);\t\n\t\t\tif(isFinite(year)) {\n\t\t\t\t// for years after 2009, go strictly by decade:\n\t\t\t\tif (year > 2009) adChannelYear = year.toString().substr(0,3) + '0-' + year.toString().substr(0,3) + '9';\n\t\t\t\telse if(year > 2004) adChannelYear = '2005_2009';\n\t\t\t\telse if(year > 1986) adChannelYear = '1987-2004'; \n\t\t\t\telse if(year > 1979) adChannelYear = '1980-1986'; \n\t\t\t\telse if(year > 1969) adChannelYear = '1970-1979'; \n\t\t\t\telse if(year > 1959) adChannelYear = '1960-1969'; \n\t\t\t\telse if(year > 1949) adChannelYear = '1950-1959'; \n\t\t\t\telse if(year > 1939) adChannelYear = '1940-1949'; \n\t\t\t\telse if(year > 1929) adChannelYear = '1930-1939'; \n\t\t\t\telse if(year > 1922) adChannelYear = '1923_1929'; \n\t\t\t\telse if(year > 1909) adChannelYear = '1910_1922'; \n\t\t\t\telse if(year > 1899) adChannelYear = '1900_1909'; \n\t\t\t\telse if(year > 1889) adChannelYear = '1890_1899'; \n\t\t\t\telse if(year > 1879) adChannelYear = '1880_1889'; \n\t\t\t\telse if(year > 1869) adChannelYear = '1870_1879'; \n\t\t\t\telse if(year > 1865) adChannelYear = '1866_1869'; \n\t\t\t\telse if(year > 1859) adChannelYear = '1860_1865'; \n\t\t\t\telse if(year > 1850) adChannelYear = '1851_1859'; \n\t\t\t}\n\t\t}\n\t\tif(adChannelYear) {\n\t\t\tw.google_ad_channel += \" \" + adChannelYear;\n\t\t\t// for testing, remove before going live:\n\t\t\tw.saveAdChannel = w.google_ad_channel;\n\t\t}\n\t\n\t},\n\n\n\t/* \n\t * These are the Google Callback Functions. They need to be in the Global Namespace\n\t * so that google code can call them. In our old GoogleAds code, these functions are \n\t * defined in the ad position. Since there is still the chance that old code could \n\t * appear on the page, and overwrite these functions, we define them here as methods \n\t * of NYTD.GoogleAds, and put them into the global namespace in GetGoogleAds() each \n\t * time we need them. \n\t */\n\n\t/* Google code will call this function when AFS ads are requested */\n\tgoogleAfsRequestDone: function(ads) {\n\t\t\n\t\t// Verify that there are actually ads to display. If not, try to get Radlinks\n\t\tvar google_num_ads = ads.length;\n\t\tif (google_num_ads <= 0) {\n\t\t\tNYTD.GoogleAds.getGoogleAds('RAD', {'ad_target':NYTD.GoogleAds.narrowPosition});\n\t\t}\n\n\t\tvar wideAds = \"\"; //wide ad unit html text\n\t\tvar narrowAds = \"\"; //narrow ad unit html text\n\n\t\tfor(i = 0; i < google_num_ads; i++){\n\t\t\t var values = {\n\t\t\t\t url: ads[i].url,\n\t\t\t\t line1: ads[i].line1,\n\t\t\t\t line2: ads[i].line2,\n\t\t\t\t visibleUrl: ads[i].visible_url\n\t\t\t};\n\n\t\t\tif (ads[i].type==\"text/wide\"){\n\t\t\t\twideAds += NYTD.Template(NYTD.GoogleAds.templates.afsWideAd, values);\n\t\t\t} else {\n\t\t\t\tvalues.line3 = ads[i].line3;\n\t\t\t\tnarrowAds += NYTD.Template(NYTD.GoogleAds.templates.afsNarrowAd, values);\n\t\t\t}\n\t\t}\n\t\tif (narrowAds !== \"\") {\n\t\t\tnarrowAds = '<div id=\"sponsoredLinksC\">' +\n\t\t\t\t\t\t'<div class=\"sponsLinksWhat\"><a href=\"javascript:pop_me_up2(\\'http://www.nytimes.com/ref/membercenter/faq/linkingqa15.html\\',\\'420400\\',\\'width=420,height=400,scrollbars=yes,toolbars=no,resizable=no\\');\">Advertiser Links</a></div>' + narrowAds +\n\t\t\t\t\t\t'<div class=\"sponsLinksWhat\"><a href=\"javascript:pop_me_up2(\\'http://www.nytimes.com/ref/membercenter/faq/linkingqa15.html\\',\\'420400\\',\\'width=420,height=400,scrollbars=yes,toolbars=no,resizable=no\\');\">What are Advertiser Links?</a></div></div>';\n\t\t}\n\t\telse {\n\t\t\t// if there are no narrow ads, request related ads \n\t\t\tNYTD.GoogleAds.getGoogleAds('RAD', {'ad_target':NYTD.GoogleAds.narrowPosition});\n\t\t}\n\n\t\tif (wideAds !== \"\") {\n\t\t\twideAds = '<div id=\"sponsoredLinks\">' +\n\t\t\t\t\t '<div id=\"sponsLinks\"><a href=\"javascript:pop_me_up2(\\'http://www.nytimes.com/ref/membercenter/faq/linkingqa15.html\\',\\'420400\\',\\'width=420,height=400,scrollbars=yes,toolbars=no,resizable=no\\');\">Advertiser Links</a></div>' + wideAds + '</div>';\n\t\t}\n\t\tif($(NYTD.GoogleAds.widePosition)) { $(NYTD.GoogleAds.widePosition).innerHTML = wideAds; }\n\t\tif($(NYTD.GoogleAds.narrowPosition)) { $(NYTD.GoogleAds.narrowPosition).innerHTML = narrowAds; }\n\t\tNYTD.GoogleAds.clearGoogleParams('AFS');\n\t},\n\n\n\t/* Google code will call this function when RADLINK ads are requested */\n\tgoogleRadlinkRequestDone: function(radlinks) {\n\t\tif (radlinks.length === 0) { return; }\n\n\t\tvar s = \"\";\n\t\tvar radlinksStr = '';\n\t\t\n\t\tNYTD.GoogleAds.radCount = NYTD.GoogleAds.radCount + radlinks.length || radlinks.length;\n\t\t\n\t\tfor (i = 0; i < radlinks.length; ++i) {\n\t\t\t var values = {\n\t\t\t\t queryHost: NYTD.GoogleAds.queryHost,\n\t\t\t\t term: radlinks[i].term,\n\t\t\t\t thisPage: escape(window.location)\n\t\t\t};\n\t\t\tradlinksStr += NYTD.Template(NYTD.GoogleAds.templates.radLink, values);\n\t\t}\n\n\t\ts += '\\n<div id=\"sponsoredLinksC\">' +\n\t\t\t '\\n<div class=\"sponsLinksWhat\"><a href=\"javascript:pop_me_up2(\\'http://www.nytimes.com/ref/membercenter/faq/linkingqa17.html\\',\\'420400\\',\\'width=420,height=400,scrollbars=yes,toolbars=no,resizable=no\\');\">Related Ads</a></div>' +\n\t\t\t radlinksStr +\n\t\t\t '\\n<div class=\"sponsLinksWhat\"><a href=\"javascript:pop_me_up2(\\'http://www.nytimes.com/ref/membercenter/faq/linkingqa17.html\\',\\'420400\\',\\'width=420,height=400,scrollbars=yes,toolbars=no,resizable=no\\');\">What are Related Ads?</a></div>' +\n\t\t\t '</div>';\n\n\t\tif($(NYTD.GoogleAds.ad_target)) { $(NYTD.GoogleAds.ad_target).innerHTML = s; }\n\t\tNYTD.GoogleAds.clearGoogleParams('RAD');\n\n\t},\n\n\n\n\t/* Google code will call this function when AFC ads are requested */\n\tgoogleAdRequestDone: function(ads) {\n\t\tvar ga = NYTD.GoogleAds;\n\t\t\n\t\tif(ads && typeof(ads) === 'object' && typeof(ads[0]) !== 'undefined' && typeof(ads[0].type) !== 'undefined' && $(ga.adTarget)) { \n\t\t\tvar className = 'nytd_google_ads', \n\t\t\t\tafc = \"\",\n\t\t\t s = ga.debugElement.html || '',\n\t\t\t\tadType = ads[0].type;\n\t\t\t\n\t\t\tif(adType === 'text') {\n\t\t\t\tif (ads.length === 1) { className += ' nytd_google_single_ad'; }\n\t\t\t\ts += '<table id=\"' + ga.adTarget + '_googleAds\" class=\"' + className + '\" cellspacing=\"0\" cellpadding=\"0\" border=0><tr class=\"header\"><td class=\"left\" >Ads by Google</td><td class=\"right\"><a target=\"popupad\" onclick=\"window.open(\\'\\',\\'popupad\\',\\'left=100,top=100,width=390,height=390,resizable,scrollbars=no\\')\" href=\"http://www.nytimes.com/ref/membercenter/faq/linkingqa16.html\" style=\"font-family: Arial,Helvetica,sans-serif; color: white; font-size: 12px; padding-right: 7px;\">what\\'s this?</a></td>\\n';\n\t\t\t}\n\t\t\tfor (i = 0; i < ads.length; ++i) {\n\t\t\t\t var values = {\n\t\t\t\t\t url: ads[i].url,\n\t\t\t\t\t line1: ads[i].line1,\n\t\t\t\t\t line2: ads[i].line2,\n\t\t\t\t\t line3: ads[i].line3,\n\t\t\t\t\t visibleUrl: ads[i].visible_url,\n\t\t\t\t\t bidType: ads[i].bidtype,\n\t\t\t\t\t targetingType: ads[i].targeting_type,\n\t\t\t\t\t imageUrl: ads[i].image_url || null,\n\t\t\t\t\t imageWidth: ads[i].image_width || null,\n\t\t\t\t\t imageHeight: ads[i].image_height || null\n\t\t\t\t};\n\n\t\t\t\tafc += NYTD.Template(ga.templates.afcAd[adType], values);\n\t\t\t\tga.cpcCount++;\n\t\t\t}\n\t\t\t\n\t\t\tif(adType === 'text') { s += afc + '</tr></table>'; }\n\t\t\telse { \n\t\t\t\t//s += afc + '</div>'; \n\t\t\t\tvar feedbackLink = 'Ads by Google';\n\t\t\t\tif (google_info && google_info.feedback_url) {\n\t\t\t\t\tfeedbackLink = '<a href=\"' + google_info.feedback_url + '\" target=\"blank\">Ads by Google</a>';\n\t\t\t\t}\n\t\t\t\ts += '<div class=\"' + className + '\">';\n\t\t\t\ts += afc;\n\t\t\t\ts += '\t<div class=\"footer\">';\n\t\t\t\ts += '\t\t<div class=\"left\">' + feedbackLink + '</div>';\n\t\t\t\ts += '\t\t<div class=\"right\"><a href=\"http://www.nytimes.com/ref/membercenter/faq/linkingqa16.html\" onclick=\"window.open(\\'\\',\\'popupad\\',\\'left=100,top=100,width=390,height=390,resizable,scrollbars=no\\')\" target=\"popupad\">what\\'s this?</a></div>';\n\t\t\t\ts += '\t</div>';\n\n\t\t\t}\n\t\t\t$(ga.adTarget).innerHTML = s; \n\t\t}\n\t\t\n\t\tga.clearGoogleParams('AFC');\n\t\treturn;\n\t}\n};\n\nEvent.observe(window, 'load', NYTD.GoogleAds.loadCss);\n\n" }, { "alpha_fraction": 0.5636079907417297, "alphanum_fraction": 0.5665863156318665, "avg_line_length": 34.0796012878418, "blob_id": "34edaaff9a7429748f8b46f5daa9029c7408194f", "content_id": "2b38711d7e013559560e63cd6f688774fe297f51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7051, "license_type": "permissive", "max_line_length": 221, "num_lines": 201, "path": "/metrics/avimetrics/metrics_endpoints.py", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "import socket\nimport requests\nimport json\nimport traceback\nfrom datetime import datetime\nimport sys\n\n\n#----- Send value to graphite\ndef send_value_graphite(endpoint_info, graphite_payload):\n try:\n message_list = []\n name_space_prefix = 'network-script||'\n for entry in graphite_payload:\n name_space = (name_space_prefix+entry['name_space']).replace('.','_').replace('||','.').replace(' ','_')\n message_list.append('%s %d %d' %(name_space, entry['metric_value'], entry['timestamp']))\n #----- I believe there is a message list limit on graphite for plain text\n if sys.getsizeof(message_list) > 4915:\n message = '\\n'.join(message_list) + '\\n'\n socket.setdefaulttimeout(10)\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((endpoint_info['server'], endpoint_info['server_port']))\n sock.send(message)\n sock.close()\n message_list = []\n message = '\\n'.join(message_list) + '\\n'\n socket.setdefaulttimeout(10)\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((endpoint_info['server'], endpoint_info['server_port']))\n sock.send(message)\n sock.close()\n\n except:\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+exception_text)\n print message\n\n\n\n\n\n#----- Send value to splunk HEC - destination a metric index\ndef send_value_splunk(endpoint_info, splunk_payload):\n try:\n splunk_payload_template = {\n \"source\": \"avi\",\n \"event\" : \"metric\",\n \"index\": endpoint_info['index'],\n \"time\": \"\",\n \"host\": \"\",\n \"fields\": {\n \"service\": \"avi\",\n \"environment\": \"\",\n \"_value\": \"\",\n \"location\": \"\",\n \"metric_name\": \"\"\n }\n }\n hec_token = endpoint_info['hec_token']\n headers = ({'Authorization': 'Splunk '+hec_token})\n for entry in splunk_payload:\n temp_entry = entry\n keys_to_remove=[\"location\",\"environment\",\"avicontroller\",\"timestamp\",\"metric_value\",\"metric_name\",\"name_space\"]\n payload = splunk_payload_template.copy()\n payload['host'] = temp_entry['avicontroller']\n payload['time'] = temp_entry['timestamp']\n payload['fields']['environment'] = temp_entry['environment']\n payload['fields']['location'] = temp_entry['location']\n payload['fields']['_value'] = temp_entry['metric_value']\n payload['fields']['metric_name'] = temp_entry['metric_name']\n for k in keys_to_remove:\n entry.pop(k, None)\n for e in entry:\n payload[\"fields\"][e]=entry[e]\n resp = requests.post('%s://%s:%s/services/collector/event' %(endpoint_info['hec_protocol'], endpoint_info['server'], str(endpoint_info['hec_port'])) , verify=False, headers = headers, data=json.dumps(payload))\n if resp.status_code == 400:\n print payload\n except:\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+exception_text)\n print entry\n\n\n\n\n#----- Send value to appdynamics\ndef send_value_appdynamics_machine(endpoint_info, appd_payload):\n try:\n for entry in appd_payload:\n name_space = entry['name_space'].replace('||','|')\n print('name=Custom Metrics|%s,value=%d,aggregator=OBSERVATION,time-rollup=CURRENT,cluster-rollup=INDIVIDUAL' % (name_space, long(entry['metric_value'])))\n except:\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+exception_text)\n\n\n\n\n#----- this is to send to appdynamics machine agent http listener\ndef send_value_appdynamics_http(endpoint_info, appd_payload):\n try:\n payload = []\n for entry in appd_payload:\n name_space = entry['name_space'].replace('||','|')\n temp_payload = {}\n temp_payload['metricName'] = 'Custom Metrics|'+name_space\n temp_payload['aggregatorType'] = 'OBSERVATION'\n temp_payload['value'] = long(entry['metric_value'])\n payload.append(temp_payload)\n headers = ({'content-type': 'application/json'})\n resp = requests.post('http://%s:%s/api/v1/metrics' %(endpoint_info['server'],endpoint_info['server_port']),headers = headers, data=json.dumps(payload))\n if resp.status_code != 204:\n print resp\n #if resp.status_code != 202:\n # print resp\n except:\n exception_text = traceback.format_exc()\n print exception_text\n\n\n\n\n\n\n\n\n\ndef send_value_opentsdb(payload):\n pass\n\n\n\n\n\ndef send_value_prometheus(payload):\n pass\n\n\n\n\n\ndef send_value_datadog(endpoint_info, datadog_payload):\n try:\n keys_to_remove=[\"avicontroller\",\"timestamp\",\"metric_value\",\"metric_name\",\"name_space\"]\n series_list = []\n datadog_payload_template = {\n \"metric\":\"\",\n \"points\":\"\",\n \"host\":\"\",\n \"tags\":\"\"\n }\n for entry in datadog_payload:\n temp_payload = datadog_payload_template.copy()\n temp_payload['metric'] = entry['metric_name']\n temp_payload['points'] = [[entry['timestamp'],entry['metric_value']]]\n temp_payload['host'] = entry['avicontroller']\n #for k in keys_to_remove:\n # entry.pop(k, None)\n tag_list = []\n for e in entry:\n if e not in keys_to_remove:\n tag_list.append(str(e+':'+entry[e]))\n temp_payload['tags'] = tag_list\n series_list.append(temp_payload)\n payload = {'series': series_list}\n headers = ({'content-type': 'application/json'})\n resp = requests.post('https://%s%s' %(endpoint_info['api_url'],endpoint_info['api_key']), verify=False, headers = headers, data=json.dumps(payload))\n if resp.status_code != 202:\n print resp\n except:\n exception_text = traceback.format_exc()\n print exception_text\n\n\n\n\n\n\ndef send_value_elastic_stack(payload):\n pass\n\n\n\n\n\ndef send_metriclist_to_endpoint(endpoint_list, payload):\n try:\n for endpoint_info in endpoint_list:\n if endpoint_info['type'] == 'graphite':\n send_value_graphite(endpoint_info, payload)\n elif endpoint_info['type'] == 'splunk':\n send_value_splunk(endpoint_info, payload)\n elif endpoint_info['type'] == 'appdynamics_http':\n send_value_appdynamics_http(endpoint_info, payload)\n elif endpoint_info['type'] == 'appdynamics_machine':\n send_value_appdynamics_machine(endpoint_info, payload)\n elif endpoint_info['type'] == 'datadog':\n send_value_datadog(endpoint_info, payload)\n except:\n exception_text = traceback.format_exc()\n print exception_text\n" }, { "alpha_fraction": 0.6210106611251831, "alphanum_fraction": 0.6642287373542786, "avg_line_length": 26.345455169677734, "blob_id": "9b29bbe4ef0a5b05eda83fbfc4fedec3ceed85ca", "content_id": "a418c902b9e4af4eeb2b100be6ce9e9325610b23", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4512, "license_type": "permissive", "max_line_length": 262, "num_lines": 165, "path": "/README.md", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "# This project is being migrated to a new repo: Please use https://github.com/avinetworks/demo-in-a-box instead\n\n## Avi Vantage Demo Setup\n\nThis project results in creating a \"demo-in-a-box\" of the Avi Vantage platform. This demo setup will deploy clients, servers and virtual services all within a single host resulting in an up and running demo system within minutes.\n\n### Prerequisites\n * Linux Server\n - RHEL\n - Centos\n - Ubuntu\n\n\n\n\n### System Resources\n <table class=\"table table table-bordered table-hover\"> \n <tbody> \n <tr> \n <th>\n </th>\n <th>**CPU**\n </th>\n <th>**Memory**\n </th>\n <th>**Storage**\n </th>\n </tr>\n <tr> \n <td><strong>Recommended</strong></td>\n <td>16+</td>\n <td>64+ GB</td>\n <td>96+ GB</td>\n </tr>\n <tr> \n <td><strong>Minimum</strong></td>\n <td>12</td>\n <td>32 GB</td>\n <td>72 GB</td>\n </tr>\n\n </tbody>\n </table>\n\n\n## Install Instructions\n\n### Automated Install\n```\n$ curl -sSL https://raw.githubusercontent.com/avinetworks/avi-corp-demo/master/demo-install.sh | sudo bash\n```\n\n\n\n\n ## Demo Setup\n\n Utilizing docker containers, the \"demo-in-a-box\" setup is completely self contained within a single host. \n\n A bridged network (<b>avinet : 169.254.0.0/16</b>) has been created for the internal docker networking.\n\n The table below lists the containers that will be created and amongst other information the roles they serve for the demo. \n\n\n <table class=\"table table table-bordered table-hover\"> \n <tbody> \n <tr> \n <th>CONTAINER NAME\n </th>\n <th>CONTAINER ROLE\n </th>\n <th>INTERNAL IP\n </th>\n <th>EXPOSED PORTS\n </th>\n </tr>\n <tr> \n <td><strong>avicontroller</strong></td>\n <td>Avi Vantage controller</td>\n <td>169.254.0.100</td>\n <td>tcp:80, tcp:443, tcp:5054, tcp:5098(ssh), tcp:8443, udp:161</td>\n </tr>\n <tr> \n <td><strong>avise1</strong></td>\n <td>Avi Service Engine</td>\n <td>169.254.0.101</td>\n <td>none</td>\n </tr>\n <tr> \n <td><strong>avise2</strong></td>\n <td>Avi Service Engine</td>\n <td>169.254.0.102</td>\n <td>none</td>\n </tr>\n <tr> \n <td><strong>democlient1</strong></td>\n <td>Client running scripted traffic against <strong> avi-demo-vs </strong> and <strong>waf-vs</strong> virtual services</td>\n <td>169.254.128.1</td>\n <td>none</td>\n </tr>\n <tr> \n <td><strong>democlient2</strong></td>\n <td>Client running scripted traffic against <strong> avi-demo-vs </strong> and <strong>waf-vs</strong> virtual services</td>\n <td>169.254.128.2</td>\n <td>none</td>\n </tr>\n <tr> \n <td><strong>scaleoutclient1</strong></td>\n <td>Client running scripted traffic against <strong> avi-scaleout-vs </strong> virtual service</td>\n <td>169.254.128.3</td>\n <td>none</td>\n </tr>\n <tr> \n <td><strong>demoserver1</strong></td>\n <td>Server used for <strong> avi-demo-vs </strong> and <strong>avi-scaleout-vs</strong> virtual services</td>\n <td>169.254.255.200</td>\n <td>none</td>\n </tr>\n <tr> \n <td><strong>demoserver2</strong></td>\n <td>Server used for <strong> avi-demo-vs </strong> and <strong>avi-scaleout-vs</strong> virtual services</td>\n <td>169.254.255.201</td>\n <td>none</td>\n </tr>\n <tr> \n <td><strong>demoserver3</strong></td>\n <td>Server used for <strong> avi-demo-vs </strong> and <strong>avi-scaleout-vs</strong> virtual services</td>\n <td>169.254.255.203</td>\n <td>none</td>\n </tr>\n <tr> \n <td><strong>wafserver1</strong></td>\n <td>Server used for <strong> waf-vs</strong> virtual service</td>\n <td>169.254.255.100</td>\n <td>none</td>\n </tr>\n <tr> \n <td><strong>wafserver2</strong></td>\n <td>Server used for <strong> waf-vs</strong> virtual service</td>\n <td>169.254.255.101</td>\n <td>none</td>\n </tr>\n <tr> \n <td><strong>rdpserver</strong></td>\n <td>An rdp server to be used to access virtual services</td>\n <td>169.254.128.0</td>\n <td>tcp:3389</td>\n </tr>\n </tbody>\n </table>\n\n ## How to Access\n\n There are two containers that are exposing services externally on the host; the Avi Controller and the RDP Server\n\n\n#### Avi Controller\n The Avi Vantage Controller can be accessed through the GUI or SSH. To access the GUI point a browser to https://<host_ip>. To access the cli, ssh to the host ip on port 5098. Login credentials for the Avi controller are:<br>\n - u: admin<br>\n - p: AviDemo1!\n\n#### RDP Server\nBecause this demo setup is isolated within the host an RDP server is provided to allow for manual access to the virtual services. To login to the RDP server, using an RDP client connect to the host IP on port 3389. Login credentials for the RDP server are:<br>\n - u: demouser<br>\n - p: demouser\n" }, { "alpha_fraction": 0.5587255954742432, "alphanum_fraction": 0.5686131715774536, "avg_line_length": 28.125762939453125, "blob_id": "6249b78902b7b8b674084d84353d2387caf7c10e", "content_id": "dfd9c8f0b556877a36c4bd8e4756ea73ab3099cf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 59165, "license_type": "permissive", "max_line_length": 498, "num_lines": 1964, "path": "/servers/demo-scaleout/html/boston.tmp/bcom_global_scripts.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "var doc = document,\r\n\twin = window,\r\n\tsById = (doc.getElementById) ? true : false;\r\nfunction setStyleName(objId, styleName) {\r\n\tdocument.getElementById(objId).style.display = styleName;\r\n}\r\nvar archivedState = 0;\r\n\r\nfunction setCookie(name, value, expires, path, domain, secure) {\r\n\tdocument.cookie = name + '=' + escape(value) + ((expires) ? ';expires=' + expires.toGMTString() : '') + ';path=' + ((path) ? path : '/') + ';domain=' + ((domain) ? domain : 'boston.com') + ((secure) ? ';secure' : '');\r\n}\r\n\r\nfunction ifSafari() {\r\n\tif ((navigator.userAgent.indexOf('Safari') != -1) || (navigator.userAgent.indexOf(\"Macintosh\") != -1) || (navigator.userAgent.indexOf(\"Mac_PowerPC\") != -1)) {\r\n\t\tdocument.write(\"<style type='text/css' media='all'>@import 'http://cache.boston.com/universal/css/bcom_hp_styles_safari.css';</style>\")\r\n\t};\r\n}\r\n\r\nfunction getCookie(name) {\r\n\tvar dc = document.cookie,\r\n\t\tprefix = name + '=',\r\n\t\tbegin = dc.indexOf('; ' + prefix);\r\n\tif (begin == -1) {\r\n\t\tbegin = dc.indexOf(prefix);\r\n\t\tif (begin != 0) return null;\r\n\t} else begin += 2;\r\n\tvar end = dc.indexOf(';', begin);\r\n\tif (end == -1) end = dc.length;\r\n\treturn unescape(dc.substring(begin + prefix.length, end));\r\n}\r\n\r\nfunction expireCookie(name, path, domain) {\r\n\tdocument.cookie = name + '=;expires=Thu, 01-Jan-70 00:00:01 GMT;path=' + ((path) ? path : '/') + ';domain=' + ((domain) ? domain : 'boston.com');\r\n}\r\n\r\nfunction windowLoaded() {}\r\n\r\nfunction tabs(view, hideA, hideB) {\r\n\tif (view.style.visibility == \"hidden\") {\r\n\t\tview.style.visibility = \"visible\";\r\n\t\tview.style.display = \"block\";\r\n\t\thideA.style.visibility = \"hidden\";\r\n\t\thideB.style.visibility = \"hidden\";\r\n\t\thideA.style.display = \"none\";\r\n\t\thideB.style.display = \"none\";\r\n\t} else {\r\n\t\tview.style.visibility = \"visible\";\r\n\t\tview.style.display = \"block\";\r\n\t}\r\n}\r\n\r\nfunction tabs2(view, hideA) {\r\n\tif (view.style.visibility == \"hidden\") {\r\n\t\tview.style.visibility = \"visible\";\r\n\t\tview.style.display = \"block\";\r\n\t\thideA.style.visibility = \"hidden\";\r\n\t\thideA.style.display = \"none\";\r\n\t} else {\r\n\t\tview.style.visibility = \"visible\";\r\n\t\tview.style.display = \"block\";\r\n\t}\r\n}\r\nvar var5 = 'hp_header_';\r\nfunction keyword() {\r\n\tif (document.getElementById('textField').value != \"\" && document.getElementById('textField').value != null) {\r\n\t\treturn document.getElementById('textField').value.toLowerCase();\r\n\t} else {\r\n\t\treturn \"User_Blank\"\r\n\t}\r\n}\r\nvar otherTab;\r\nfunction choose(tab) {\r\n\tif (tab != otherTab) {\r\n\t\ttab.className = \"searchOn\";\r\n\t\totherTab.className = \"\";\r\n\t\totherTab = tab;\r\n\t\tif (tab.id == \"searchLocal\") {\r\n\t\t\tdocument.getElementById(\"tab\").value = \"\";\r\n\t\t} else if (tab.id == \"searchSite\") {\r\n\t\t\tdocument.getElementById(\"tab\").value = \"ssearch\";\r\n\t\t} else if (tab.id == \"searchBusiness\") {\r\n\t\t\tdocument.getElementById(\"tab\").value = \"yp\";\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfunction searchSubmit() {\r\n\tomnitureCode(document.getElementById(\"tab\"));\r\n}\r\n\r\nfunction omnitureCode(tabName) {\r\n\tvar temp5 = var5;\r\n\tif (tabName.value == \"\") {\r\n\t\tif (document.getElementById('p1') != null) {\r\n\t\t\tdocument.getElementById('p1').value = 'Header_Searchbox_LocalSearch'\r\n\t\t};\r\n\t\ttemp5 = var5 + 'searchbox_greaterboston';\r\n\t}\r\n\tif (tabName.value == \"ssearch\") {\r\n\t\tif (document.getElementById('p1') != null) {\r\n\t\t\tdocument.getElementById('p1').value = 'Header_Searchbox_SiteSearch'\r\n\t\t};\r\n\t\ttemp5 = var5 + 'searchbox_site';\r\n\t}\r\n\tif (tabName.value == \"yp\") {\r\n\t\tif (document.getElementById('p1') != null) {\r\n\t\t\tdocument.getElementById('p1').value = 'Header_Searchbox_BusinessSearch'\r\n\t\t};\r\n\t\ttemp5 = var5 + 'searchbox_site'; {\r\n\t\t\tdocument.getElementById('textField').name = 's.ypsearch'\r\n\t\t};\r\n\t}\r\n\tif (keyword() != \"User_Blank\") {\r\n\t\ts_linkType = 'o';\r\n\t\ts_linkName = 'search_query';\r\n\t\ts_eVar2 = keyword();\r\n\t\ts_eVar5 = temp5;\r\n\t\ts_lnk = s_co(document.getElementById('searchForm'));\r\n\t\ts_gs('nytbglobe');\r\n\t}\r\n}\r\n\r\nfunction openWindow(url, name, props) {\r\n\ttry {\r\n\t\tprops = props.replace(/(resizable|scrollbars)\\=no/g, '$1=yes');\r\n\t\tvar nw = win.open(url, name, props);\r\n\t\tnw.focus();\r\n\t\twindow.event.cancelBubble = true;\r\n\t} catch (e) {}\r\n}\r\n\r\nfunction MM_openBrWindow(url, name, props) {\r\n\topenWindow(url, name, props);\r\n}\r\nvar doc = document,\r\n\twin = window,\r\n\tsById = (doc.getElementById) ? true : false;\r\nfunction openWindow(url, name, props) {\r\n\ttry {\r\n\t\tprops = props.replace(/(resizable|scrollbars)\\=no/g, '$1=yes');\r\n\t\tvar nw = win.open(url, name, props);\r\n\t\tnw.focus();\r\n\t\twindow.event.cancelBubble = true;\r\n\t} catch (e) {}\r\n}\r\nvar bcHomepage;\r\nvar bcCategoryPage;\r\nvar homepageSWF = \"homepage_thumbs\";\r\nvar categorySWF = \"category_thumbs\";\r\nvar titleIDs = new Array();\r\nfunction onTemplateLoaded() {\r\n\tcallFlash(\"addEventListener\", \"contentLoad\", \"onContentLoad\");\r\n\tcallFlash(\"addEventListener\", \"mediaReady\", \"onMediaReady\");\r\n\tbcHomepage = document.getElementById(\"bcHomepage\");\r\n\tbcCategoryPage = document.getElementById(\"bcCategoryPage\");\r\n\tbcArticlePage = document.getElementById(\"bcArticlePage\");\r\n\tbcRelatedVideos = document.getElementById(\"bcRelatedVideos\");\r\n\tbcPlayerThumbnails = document.getElementById(\"bcPlayerThumbnails\");\r\n\tbcThumbnailTitle = document.getElementById(\"bcThumbnailTitle\");\r\n\tbcTitleHeadline = document.getElementById(\"bcTitleHeadline\");\r\n\tbcPaging = document.getElementById(\"bcPaging\");\r\n\tbcDescription = document.getElementById(\"bcDescription\");\r\n\tbcVideoHeader = document.getElementById(\"bcVideoHeader\");\r\n}\r\n\r\nfunction onContentLoad() {\r\n\tif (bcHomepage || bcCategoryPage) callFlash(\"getFeaturedLineup\");\r\n\tif (bcHomepage) thisMovie(homepageSWF).unhide();\r\n\tif (bcArticlePage) onMediaReady();\r\n}\r\n\r\nfunction onMediaReady() {\r\n\tcallFlash(\"getCurrentTitle\");\r\n}\r\n\r\nfunction getCurrentTitle_Result(titleDTO) {\r\n\tif (bcTitleHeadline) bcTitleHeadline.innerHTML = titleDTO.displayName;\r\n\tif (bcDescription) bcDescription.innerHTML = titleDTO.shortDescription;\r\n\tif (bcVideoHeader) bcVideoHeader.style.visibility = \"visible\";\r\n}\r\n\r\nfunction getFeaturedLineup_Result(lineupDTO) {\r\n\ttitleIDS = new Array();\r\n\ttitleIDs = lineupDTO.videoIds;\r\n\tfor (var i = 0; i < lineupDTO.videoIds.length; i++) {\r\n\t\tcallFlash(\"getTitleById\", lineupDTO.videoIds[i]);\r\n\t}\r\n\tif (bcRelatedVideos) bcRelatedVideos.innerHTML = \"RELATED VIDEOS (\" + lineupDTO.videoIds.length + \")\";\r\n\tif (bcRelatedVideos) bcRelatedVideos.style.color = \"#000\";\r\n\tonMediaReady();\r\n\tif (bcHomepage) thisMovie(homepageSWF).getPage(\"next\");\r\n\tif (bcCategoryPage) thisMovie(categorySWF).buildThumbnails();\r\n}\r\n\r\nfunction getTitleById_Result(titleDTO) {\r\n\tif (bcHomepage) thisMovie(homepageSWF).buildTitleIDs(Number(titleDTO.id));\r\n\tif (bcHomepage) thisMovie(homepageSWF).buildTitles(String(titleDTO.displayName));\r\n\tif (bcHomepage) thisMovie(homepageSWF).buildThumbArray(String(titleDTO.thumbnailURL));\r\n\tif (bcCategoryPage) thisMovie(categorySWF).buildTitleIDs(Number(titleDTO.id));\r\n\tif (bcCategoryPage) thisMovie(categorySWF).buildTitles(String(titleDTO.displayName));\r\n\tif (bcCategoryPage) thisMovie(categorySWF).buildThumbArray(String(titleDTO.thumbnailURL));\r\n\tif (bcCategoryPage) thisMovie(categorySWF).buildDescriptions(String(titleDTO.shortDescription));\r\n}\r\n\r\nfunction thisMovie(movieName) {\r\n\tif (navigator.appName.indexOf(\"Microsoft\") != -1) {\r\n\t\treturn window[movieName];\r\n\t} else {\r\n\t\treturn document[movieName];\r\n\t}\r\n}\r\nvar primary_id = 'tab1';\r\nfunction switchTab1() {\r\n\tdocument.getElementById('tab1').className = 'active';\r\n\tdocument.getElementById('tab2').className = '';\r\n\tdocument.getElementById('tab3').className = '';\r\n\tdocument.getElementById('zventsFooter').style.display = 'block'\r\n}\r\n\r\nfunction switchTab2() {\r\n\tdocument.getElementById('tab1').className = '';\r\n\tdocument.getElementById('tab2').className = 'active';\r\n\tdocument.getElementById('tab3').className = '';\r\n\tdocument.getElementById('zventsFooter').style.display = 'block'\r\n}\r\n\r\nfunction switchTab3() {\r\n\tdocument.getElementById('tab1').className = '';\r\n\tdocument.getElementById('tab2').className = '';\r\n\tdocument.getElementById('tab3').className = 'active';\r\n\tdocument.getElementById('zventsFooter').style.display = 'none'\r\n}\r\nvar primary_id = 'tab1';\r\nfunction switchTabA() {\r\n\tdocument.getElementById('tabA').className = 'active';\r\n\tdocument.getElementById('tabB').className = ''\r\n}\r\n\r\nfunction switchTabB() {\r\n\tdocument.getElementById('tabA').className = '';\r\n\tdocument.getElementById('tabB').className = 'active'\r\n}\r\n\r\nfunction ShowDiv(a, b, c, d) {\r\n\tvar i;\r\n\tif (c) {\r\n\t\ti = c\r\n\t} else {\r\n\t\ti = 1\r\n\t};\r\n\tvar z;\r\n\twhile (z = document.getElementById(b + i)) {\r\n\t\tif ((i >= c) && (i <= d)) {\r\n\t\t\tif (i == a) {\r\n\t\t\t\tz.style.display = 'block'\r\n\t\t\t} else {\r\n\t\t\t\tz.style.display = 'none'\r\n\t\t\t}\r\n\t\t}\r\n\t\ti++\r\n\t}\r\n}\r\ntabber = {\r\n\tclick: function(clicked) {\r\n\t\tvar ul = clicked.parentNode.parentNode;\r\n\t\tvar tabs = ul.getElementsByTagName('a');\r\n\t\tfor (i = 0; i < tabs.length; ++i) {\r\n\t\t\tvar a = tabs[i],\r\n\t\t\t\ton = (a == clicked);\r\n\t\t\ta.className = (on ? 'active' : '');\r\n\t\t\ttabber.show(a.id.replace(/^tab/, 'div'), on);\r\n\t\t}\r\n\t},\r\n\tzclick: function(clicked, when) {\r\n\t\ttabber.click(clicked);\r\n\t\ttabber.show('zventsFooter', !when);\r\n\t\tif (ZventsTomorrowID && when == 'Tomorrow') {\r\n\t\t\tZ.widget.popular({\r\n\t\t\t\tid: ZventsTomorrowID,\r\n\t\t\t\tload: {\r\n\t\t\t\t\twhen: when\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t\tZventsTomorrowID = null;\r\n\t\t}\r\n\t},\r\n\tshow: function(id, show) {\r\n\t\tdocument.getElementById(id).style.display = show ? 'block' : 'none';\r\n\t}\r\n};\r\nfunction keywordSelect(inputfield) {\r\n\tif (document.getElementById(inputfield).value != \"\" && document.getElementById(inputfield).value != null) {\r\n\t\treturn document.getElementById(inputfield).value.toLowerCase();\r\n\t} else {\r\n\t\treturn \"User_Blank\"\r\n\t}\r\n}\r\n\r\nfunction travelWidgetSubmit() {\r\n\tvar kw = \"\";\r\n\tif (document.getElementById('textField2').value == \"\") {\r\n\t\talert('Please enter a keyword, like \"Maine\" or \"Bermuda hotels\"');\r\n\t} else {\r\n\t\tdocument.getElementById('travelSearchWidget').submit();\r\n\t\tkw = \"Travel-\" + keywordSelect('textField2');\r\n\t\ttravelWidgetomnitureCode('searchbox', kw);\r\n\t}\r\n}\r\n\r\nfunction travelWidgetomnitureCode(tabName, keyword, sco) {\r\n\tvar temp5 = var5;\r\n\ttemp5 = var5 + 'travel' + tabName;\r\n\ts_linkType = 'o';\r\n\ts_linkName = 'search_query';\r\n\ts_eVar2 = keyword;\r\n\ts_eVar5 = temp5;\r\n\ts_lnk = s_co(document.getElementById('searchForm'));\r\n\ts_gs('nytbglobe');\r\n}\r\n\r\nfunction Nytd_Pixel_addGlobalTaxonomyValue(value) {}\r\n\r\nfunction Nytd_Pixel() {}\r\n\r\nfunction goToUgcProfileUrl() {\r\n\tvar pathAuth = getCookie(\"pathAuth\");\r\n\tif (!pathAuth) return;\r\n\t$.getJSON(\"/ugc/user/regiauthtoken/\" + getCookie(\"pathAuth\"), function(user, textStatus, jqXHR) {\r\n\t\twindow.location.href = \"/community/user/\" + user.id\r\n\t});\r\n\treturn false;\r\n}\r\n\r\nfunction showLoginRRD(twidth) {\r\n\tif (!twidth) twidth = 191;\r\n\tif (getCookie(\"pathAuth\") || getCookie(\"pathAuthSess\")) {\r\n\t\tif (((getCookie(\"PSyncHint\")) && (getCookie(\"PSyncHint\") != \"-\")) && (getCookie(\"AT\"))) {\r\n\t\t\tif (OAS_sitepage == 'www.boston.com/homepage/default') {\r\n\t\t\t\tdocument.writeln('<span id=\"mp\"><b><a onclick=\"goToUgcProfileUrl()\" href=\"javascript:void(0)\">' + getCookie(\"PSyncHint\") + '\\'s profile</a></b></span><br><span id=\"mc\"><a href=\"https://www.boston.com/eom/SysConfig/WebPortal/Boston/Framework/regi/membercenter-update-info.jsp\">Account settings</a></span> | <span id=\"lo\"><a onclick=\"setCookie(\\'AT\\');document.location=\\'http://www.boston.com/logout\\';return false\" href=\"http://www.boston.com/logout\">Log out</a></span>');\r\n\t\t\t} else {\r\n\t\t\t\tdocument.writeln('<div align=\"center\"><span id=\"mp\"><b><a onclick=\"goToUgcProfileUrl()\" href=\"javascript:void(0)\">' + getCookie(\"PSyncHint\") + '\\'s profile</a></b></span> | <span id=\"mc\"><a href=\"https://www.boston.com/eom/SysConfig/WebPortal/Boston/Framework/regi/membercenter-update-info.jsp\">Member Center</a></span> | <span id=\"lo\"><a onclick=\"setCookie(\\'AT\\');document.location=\\'http://www.boston.com/logout\\';return false\" href=\"http://www.boston.com/logout\">Log out</a></span></div>');\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tdocument.writeln('<div align=\"center\"><span id=\"mc\"><a href=\"https://www.boston.com/eom/SysConfig/WebPortal/Boston/Framework/regi/membercenter-update-info.jsp\">Member Center</a></span> | <span id=\"lo\"><a href=\"http://www.boston.com/logout\">Log out</a></span></div>');\r\n\t\t}\r\n\t} else {\r\n\t\tdocument.writeln('<div align=\"center\"><span id=\"si\"><a href=\"/login?p1=header_regi_signin\">Sign In</a></span> | <span id=\"rn\"><a href=\"https://www.boston.com/eom/SysConfig/WebPortal/Boston/Framework/regi/regi-login-register.jspw\">Register now</a></span></div>');\r\n\t}\r\n}\r\neval(function(p, a, c, k, e, d) {\r\n\twhile (c--) {\r\n\t\tif (k[c]) {\r\n\t\t\tp = p.replace(new RegExp('\\\\b' + c + '\\\\b', 'g'), k[c])\r\n\t\t}\r\n\t}\r\n\treturn p\r\n}('36={7:9(6,4,5,3){35(!6)34;4=4||\\'\\';5=5||\\'\\';3=3||\\'\\';33.32(\\'31://30.29/28-27?26=2&6=\\'+6+\\'&4=\\'+4+\\'&5=\\'+5+\\'&3=\\'+3,20 19().17(),\\'21=1,22=1,15=0,13=1,25=1,11=1,18=23,14=12,10 = 24,8 = 16\\')}}', 10, 37, '|||topic|title|bodytext|url|remoteSubmit|top|function|left|resizable|600|statusbar|height|location|150|getTime|width|Date|new|toolbar|scrollbars|575|470|menubar|phase|submit|remote|com|digg|http|open|window|return|if|Digg'.split('|')))\r\n\r\nfunction fbs_click() {\r\n\tu = location.href;\r\n\tt = document.title;\r\n\tvoid(window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer', 'toolbar=no,width=626,height=436'));\r\n\treturn false;\r\n}\r\n\r\nfunction classySwap() {\r\n\tvar foo = Math.random();\r\n\tvar bar;\r\n\tvar bar;\r\n\tif (foo < 0.25) bar = 'cars'\r\n\telse bar = 're';\r\n\tvar baz = bar + 'CfiedContent';\r\n\tvar spaz = 'g' + bar + '_on';\r\n\tvar jazz = 'g' + bar;\r\n\tif (bar == 'cars') {\r\n\t\tsetStyleName('gcars_on', 'block');\r\n\t\tsetStyleName('gcars', 'none');\r\n\t\tsetStyleName(baz, 'block');\r\n\t} else {\r\n\t\tsetStyleName(spaz, 'block');\r\n\t\tsetStyleName(jazz, 'none');\r\n\t\tsetStyleName('carsCfiedContent', 'None');\r\n\t\tsetStyleName(baz, 'block');\r\n\t}\r\n}\r\nvar globeWidgetTab;\r\nfunction chooseGlobe(tab) {\r\n\tif (tab != globeWidgetTab) {\r\n\t\ttab.className = \"searchOn\";\r\n\t\tglobeWidgetTab.className = \"\";\r\n\t\tglobeWidgetTab = tab;\r\n\t\tif (tab.id == \"globeArchive\") {\r\n\t\t\tdocument.getElementById(\"gwsort\").value = \"-articleprintpublicationdate\";\r\n\t\t\tdocument.getElementById(\"gwdateRange\").value = \"\";\r\n\t\t} else if (tab.id == \"todayGlobe\") {\r\n\t\t\tdocument.getElementById(\"gwdateRange\").value = \"today\";\r\n\t\t\tdocument.getElementById(\"gwsort\").value = \"\";\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfunction globeWidgetSubmit() {\r\n\tomnitureGlobeCode(globeWidgetTab.id);\r\n}\r\n\r\nfunction omnitureGlobeCode(tabName) {\r\n\tvar globeTemp5 = '';\r\n\tif (tabName == \"globeArchive\") {\r\n\t\tglobeTemp5 = temp5 + 'globearchive';\r\n\t}\r\n\tif (tabName == \"todayGlobe\") {\r\n\t\tglobeTemp5 = temp5 + 'todaysglobe';\r\n\t}\r\n\tif (globekeyword() != \"User_Blank\") {\r\n\t\ts_linkType = 'o';\r\n\t\ts_linkName = 'search_query';\r\n\t\ts_eVar2 = globekeyword();\r\n\t\ts_eVar5 = globeTemp5;\r\n\t\ts_lnk = s_co(document.getElementById('articleright_searchbox'));\r\n\t\ts_gs('nytbglobe');\r\n\t}\r\n}\r\n\r\nfunction globekeyword() {\r\n\tif (document.getElementById('globeText').value != \"\" && document.getElementById('globeText').value != null) {\r\n\t\treturn document.getElementById('globeText').value.toLowerCase();\r\n\t} else {\r\n\t\treturn \"User_Blank\"\r\n\t}\r\n}\r\n\r\nfunction calImage() {\r\n\tCalDate = CalDate.toLowerCase();\r\n\tif (CalDate.indexOf(\":\") == -1) {\r\n\t\tdte = CalDate.split(\"|\");\r\n\t} else {\r\n\t\tdte = new Array();\r\n\t\ttmpDte = CalDate.split(\"-\");\r\n\t\tdte[0] = tmpDte[0].substring(0, 3);\r\n\t\tdte[1] = tmpDte[1];\r\n\t\tdte[3] = tmpDte[2].substring(0, 4);\r\n\t\ttmpDte = tmpDte[0].split(\", \");\r\n\t\tdte[2] = tmpDte[1];\r\n\t}\r\n\tif (dte[2].indexOf(\"0\") == 0) {\r\n\t\tdte[2] = dte[2].charAt(1)\r\n\t}\r\n\tgbDate = parseInt(dte[2]);\r\n\tgbMonth = dte[1];\r\n\tgbYear = dte[3];\r\n\tvar ldays = new Array(\"jan\", \"feb\", \"mar\", \"apr\", \"may\", \"jun\", \"jul\", \"aug\", \"sep\", \"oct\", \"nov\", \"dec\")\r\n\tfor (i = 0; i < ldays.length; i++) {\r\n\t\tif (gbMonth.substring(0, 3) == ldays[i]) {\r\n\t\t\tgbMonNum = i\r\n\t\t};\r\n\t}\r\n\tgbMonNum = gbMonNum + 1;\r\n\tif (gbDate < 10)(gbDate = \"0\" + gbDate);\r\n\telse(gbDate = gbDate);\r\n\tif (gbMonNum < 10)(gbMonNum = \"0\" + gbMonNum);\r\n\telse(gbMonNum = gbMonNum);\r\n\tvar popParams = \"'http://www.boston.com/news/globe/larger_view','largerview','width=650,height=1100,resizable=yes,scrollbars=yes,toolbar=no,location=no,menubar=no,status=no'\";\r\n\tdocument.write(\"<a href=\\\"http://www.boston.com/news/globe/larger_view\\\" class=\\\"imageLink\\\" onclick=\\\"openWindow(\" + popParams + \"); return false;\\\"><img src='http://cache.boston.com/globe/\" + gbYear + \"/\" + gbMonNum + \"/\" + gbDate + \"/today_thumbnail.jpeg' alt='The Boston Globe' width='189' /></a>\");\r\n}\r\n\r\nfunction redirectSelectMenu(smenu) {\r\n\tif (typeof(smenu) == 'string' && sById) smenu = doc.getElementById(smenu);\r\n\tif (smenu) {\r\n\t\tvar sval = smenu.options[smenu.selectedIndex].value;\r\n\t\tif (sval) document.location.href = sval;\r\n\t}\r\n}\r\n\r\nfunction MM_findObj(n, d) {\r\n\tvar p, i, x;\r\n\tif (!d) d = document;\r\n\tif ((p = n.indexOf(\"?\")) > 0 && parent.frames.length) {\r\n\t\td = parent.frames[n.substring(p + 1)].document;\r\n\t\tn = n.substring(0, p);\r\n\t}\r\n\tif (!(x = d[n]) && d.all) x = d.all[n];\r\n\tfor (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];\r\n\tfor (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);\r\n\tif (!x && d.getElementById) x = d.getElementById(n);\r\n\treturn x;\r\n}\r\n\r\nfunction MM_showHideLayers() {\r\n\tvar i, p, v, obj, args = MM_showHideLayers.arguments;\r\n\tfor (i = 0; i < (args.length - 2); i += 3) if ((obj = MM_findObj(args[i])) != null) {\r\n\t\tv = args[i + 2];\r\n\t\tif (obj.style) {\r\n\t\t\tobj = obj.style;\r\n\t\t\tv = (v == 'show') ? 'visible' : (v == 'hide') ? 'hidden' : v;\r\n\t\t}\r\n\t\tobj.visibility = v;\r\n\t}\r\n}\r\n\r\nfunction displayEmbed() {};\r\nfunction changeImageOn() {};\r\nfunction changeImageOff() {};\r\nfunction displayInformBox() {};\r\n\r\nfunction clearText(thefield) {\r\n\tif (thefield.defaultValue == thefield.value) thefield.value = \"\";\r\n\tthefield.className = 'search_box active';\r\n}\r\n\r\nfunction checkForm(theform) {\r\n\tif (theform.q.defaultValue == theform.q.value) theform.q.value = \"\";\r\n}\r\n\r\nfunction signupLink() {\r\n\tvar cookie1 = getCookie('pathAuth'),\r\n\t\tcookie2 = getCookie('pathAuthSess');\r\n\tif (cookie1 != null || cookie2 != null) {\r\n\t\tdocument.writeln('<a href=\"http://www.boston.com/Boston/email?p1=Foot_ContactBostonCom_Newsletters\">Newsletters</a>');\r\n\t} else {\r\n\t\tdocument.writeln('<a href=\"http://www.boston.com/Boston/email?p1=Foot_ContactBostonCom_Newsletters\">Newsletters</a>');\r\n\t}\r\n}\r\n\r\nfunction showWhat(divid) {\r\n\tif (document.getElementById(divid).style.display == 'none') {\r\n\t\tdocument.getElementById(divid).style.display = 'block';\r\n\t}\r\n}\r\n\r\nfunction hideWhat(divid) {\r\n\tif (document.getElementById(divid).style.display == 'block') {\r\n\t\tdocument.getElementById(divid).style.display = 'none';\r\n\t}\r\n}\r\n\r\nfunction keywordForm(inputId) {\r\n\tif (document.getElementById(inputId).value != \"\" && document.getElementById(inputId).value != null) {\r\n\t\treturn document.getElementById(inputId).value.toLowerCase();\r\n\t} else {\r\n\t\treturn \"User_Blank\"\r\n\t}\r\n}\r\n\r\nfunction bload() {\r\n\tif (document.getElementById(\"plckForumTitleTag\")) {\r\n\t\tdocument.title = (document.getElementById(\"plckForumTitleTag\").innerHTML + \" - Boston.com\");\r\n\t} else {\r\n\t\tif (document.getElementById(\"plckTitleTag\")) {\r\n\t\t\tdocument.title = (document.getElementById(\"plckTitleTag\").innerHTML + \" - Boston.com\");\r\n\t\t}\r\n\t}\r\n}\r\n// Added for Pluck discovery widget.\r\n\r\nfunction dateCleanUp(fromDate) {\r\n\tvar today = new Date();\r\n\tvar dCompare = new Date(fromDate);\r\n\tvar difference = (today.getTime() - dCompare.getTime());\r\n\tvar tDiff = Math.floor(difference / (1000 * 60));\r\n\tvar diffString = \"\";\r\n\tif (tDiff < 60) {\r\n\t\tdiffString = tDiff + \" \" + ((tDiff > 1) ? \"minutes\" : \"minute\");\r\n\t} else {\r\n\t\ttDiff = Math.floor(tDiff / 60);\r\n\t\tif (tDiff < 24) {\r\n\t\t\tdiffString = tDiff + \" \" + ((tDiff > 1) ? \"hours\" : \"hour\");\r\n\t\t} else {\r\n\t\t\ttDiff = Math.floor(tDiff / 24);\r\n\t\t\tdiffString = tDiff + \" \" + ((tDiff > 1) ? \"days\" : \"day\");\r\n\t\t}\r\n\t}\r\n\treturn (diffString);\r\n}\r\n//This is for refershing ads in iframes on pages with paginated Flash conent. When avail it should target OAS iframes only\r\n\r\nfunction bcom_refreshAds() {\r\n\tvar iframes = document.getElementsByTagName('iframe');\r\n\tfor (var i = 0; i < iframes.length; i++) {\r\n\t\tiframes[i].src = iframes[i].src;\r\n\t}\r\n}\r\n/*\tSWFObject v2.2 <http://code.google.com/p/swfobject/> \r\n\tis released under the MIT License <http://www.opensource.org/licenses/mit-license.php> \r\n*/\r\nvar swfobject = function() {\r\n\t\tvar D = \"undefined\",\r\n\t\t\tr = \"object\",\r\n\t\t\tS = \"Shockwave Flash\",\r\n\t\t\tW = \"ShockwaveFlash.ShockwaveFlash\",\r\n\t\t\tq = \"application/x-shockwave-flash\",\r\n\t\t\tR = \"SWFObjectExprInst\",\r\n\t\t\tx = \"onreadystatechange\",\r\n\t\t\tO = window,\r\n\t\t\tj = document,\r\n\t\t\tt = navigator,\r\n\t\t\tT = false,\r\n\t\t\tU = [h],\r\n\t\t\to = [],\r\n\t\t\tN = [],\r\n\t\t\tI = [],\r\n\t\t\tl, Q, E, B, J = false,\r\n\t\t\ta = false,\r\n\t\t\tn, G, m = true,\r\n\t\t\tM = function() {\r\n\t\t\t\tvar aa = typeof j.getElementById != D && typeof j.getElementsByTagName != D && typeof j.createElement != D,\r\n\t\t\t\t\tah = t.userAgent.toLowerCase(),\r\n\t\t\t\t\tY = t.platform.toLowerCase(),\r\n\t\t\t\t\tae = Y ? /win/.test(Y) : /win/.test(ah),\r\n\t\t\t\t\tac = Y ? /mac/.test(Y) : /mac/.test(ah),\r\n\t\t\t\t\taf = /webkit/.test(ah) ? parseFloat(ah.replace(/^.*webkit\\/(\\d+(\\.\\d+)?).*$/, \"$1\")) : false,\r\n\t\t\t\t\tX = !+\"\\v1\",\r\n\t\t\t\t\tag = [0, 0, 0],\r\n\t\t\t\t\tab = null;\r\n\t\t\t\tif (typeof t.plugins != D && typeof t.plugins[S] == r) {\r\n\t\t\t\t\tab = t.plugins[S].description;\r\n\t\t\t\t\tif (ab && !(typeof t.mimeTypes != D && t.mimeTypes[q] && !t.mimeTypes[q].enabledPlugin)) {\r\n\t\t\t\t\t\tT = true;\r\n\t\t\t\t\t\tX = false;\r\n\t\t\t\t\t\tab = ab.replace(/^.*\\s+(\\S+\\s+\\S+$)/, \"$1\");\r\n\t\t\t\t\t\tag[0] = parseInt(ab.replace(/^(.*)\\..*$/, \"$1\"), 10);\r\n\t\t\t\t\t\tag[1] = parseInt(ab.replace(/^.*\\.(.*)\\s.*$/, \"$1\"), 10);\r\n\t\t\t\t\t\tag[2] = /[a-zA-Z]/.test(ab) ? parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/, \"$1\"), 10) : 0\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (typeof O.ActiveXObject != D) {\r\n\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\tvar ad = new ActiveXObject(W);\r\n\t\t\t\t\t\t\tif (ad) {\r\n\t\t\t\t\t\t\t\tab = ad.GetVariable(\"$version\");\r\n\t\t\t\t\t\t\t\tif (ab) {\r\n\t\t\t\t\t\t\t\t\tX = true;\r\n\t\t\t\t\t\t\t\t\tab = ab.split(\" \")[1].split(\",\");\r\n\t\t\t\t\t\t\t\t\tag = [parseInt(ab[0], 10), parseInt(ab[1], 10), parseInt(ab[2], 10)]\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} catch (Z) {}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\treturn {\r\n\t\t\t\t\tw3: aa,\r\n\t\t\t\t\tpv: ag,\r\n\t\t\t\t\twk: af,\r\n\t\t\t\t\tie: X,\r\n\t\t\t\t\twin: ae,\r\n\t\t\t\t\tmac: ac\r\n\t\t\t\t}\r\n\t\t\t}(),\r\n\t\t\tk = function() {\r\n\t\t\t\tif (!M.w3) {\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\t\t\t\tif ((typeof j.readyState != D && j.readyState == \"complete\") || (typeof j.readyState == D && (j.getElementsByTagName(\"body\")[0] || j.body))) {\r\n\t\t\t\t\tf()\r\n\t\t\t\t}\r\n\t\t\t\tif (!J) {\r\n\t\t\t\t\tif (typeof j.addEventListener != D) {\r\n\t\t\t\t\t\tj.addEventListener(\"DOMContentLoaded\", f, false)\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (M.ie && M.win) {\r\n\t\t\t\t\t\tj.attachEvent(x, function() {\r\n\t\t\t\t\t\t\tif (j.readyState == \"complete\") {\r\n\t\t\t\t\t\t\t\tj.detachEvent(x, arguments.callee);\r\n\t\t\t\t\t\t\t\tf()\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\tif (O == top) {\r\n\t\t\t\t\t\t\t(function() {\r\n\t\t\t\t\t\t\t\tif (J) {\r\n\t\t\t\t\t\t\t\t\treturn\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\t\tj.documentElement.doScroll(\"left\")\r\n\t\t\t\t\t\t\t\t} catch (X) {\r\n\t\t\t\t\t\t\t\t\tsetTimeout(arguments.callee, 0);\r\n\t\t\t\t\t\t\t\t\treturn\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tf()\r\n\t\t\t\t\t\t\t})()\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (M.wk) {\r\n\t\t\t\t\t\t(function() {\r\n\t\t\t\t\t\t\tif (J) {\r\n\t\t\t\t\t\t\t\treturn\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tif (!/loaded|complete/.test(j.readyState)) {\r\n\t\t\t\t\t\t\t\tsetTimeout(arguments.callee, 0);\r\n\t\t\t\t\t\t\t\treturn\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tf()\r\n\t\t\t\t\t\t})()\r\n\t\t\t\t\t}\r\n\t\t\t\t\ts(f)\r\n\t\t\t\t}\r\n\t\t\t}();\r\n\t\tfunction f() {\r\n\t\t\tif (J) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t\ttry {\r\n\t\t\t\tvar Z = j.getElementsByTagName(\"body\")[0].appendChild(C(\"span\"));\r\n\t\t\t\tZ.parentNode.removeChild(Z)\r\n\t\t\t} catch (aa) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t\tJ = true;\r\n\t\t\tvar X = U.length;\r\n\t\t\tfor (var Y = 0; Y < X; Y++) {\r\n\t\t\t\tU[Y]()\r\n\t\t\t}\r\n\t\t}\r\n\t\tfunction K(X) {\r\n\t\t\tif (J) {\r\n\t\t\t\tX()\r\n\t\t\t} else {\r\n\t\t\t\tU[U.length] = X\r\n\t\t\t}\r\n\t\t}\r\n\t\tfunction s(Y) {\r\n\t\t\tif (typeof O.addEventListener != D) {\r\n\t\t\t\tO.addEventListener(\"load\", Y, false)\r\n\t\t\t} else {\r\n\t\t\t\tif (typeof j.addEventListener != D) {\r\n\t\t\t\t\tj.addEventListener(\"load\", Y, false)\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (typeof O.attachEvent != D) {\r\n\t\t\t\t\t\ti(O, \"onload\", Y)\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tif (typeof O.onload == \"function\") {\r\n\t\t\t\t\t\t\tvar X = O.onload;\r\n\t\t\t\t\t\t\tO.onload = function() {\r\n\t\t\t\t\t\t\t\tX();\r\n\t\t\t\t\t\t\t\tY()\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tO.onload = Y\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfunction h() {\r\n\t\t\tif (T) {\r\n\t\t\t\tV()\r\n\t\t\t} else {\r\n\t\t\t\tH()\r\n\t\t\t}\r\n\t\t}\r\n\t\tfunction V() {\r\n\t\t\tvar X = j.getElementsByTagName(\"body\")[0];\r\n\t\t\tvar aa = C(r);\r\n\t\t\taa.setAttribute(\"type\", q);\r\n\t\t\tvar Z = X.appendChild(aa);\r\n\t\t\tif (Z) {\r\n\t\t\t\tvar Y = 0;\r\n\t\t\t\t(function() {\r\n\t\t\t\t\tif (typeof Z.GetVariable != D) {\r\n\t\t\t\t\t\tvar ab = Z.GetVariable(\"$version\");\r\n\t\t\t\t\t\tif (ab) {\r\n\t\t\t\t\t\t\tab = ab.split(\" \")[1].split(\",\");\r\n\t\t\t\t\t\t\tM.pv = [parseInt(ab[0], 10), parseInt(ab[1], 10), parseInt(ab[2], 10)]\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tif (Y < 10) {\r\n\t\t\t\t\t\t\tY++;\r\n\t\t\t\t\t\t\tsetTimeout(arguments.callee, 10);\r\n\t\t\t\t\t\t\treturn\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tX.removeChild(aa);\r\n\t\t\t\t\tZ = null;\r\n\t\t\t\t\tH()\r\n\t\t\t\t})()\r\n\t\t\t} else {\r\n\t\t\t\tH()\r\n\t\t\t}\r\n\t\t}\r\n\t\tfunction H() {\r\n\t\t\tvar ag = o.length;\r\n\t\t\tif (ag > 0) {\r\n\t\t\t\tfor (var af = 0; af < ag; af++) {\r\n\t\t\t\t\tvar Y = o[af].id;\r\n\t\t\t\t\tvar ab = o[af].callbackFn;\r\n\t\t\t\t\tvar aa = {\r\n\t\t\t\t\t\tsuccess: false,\r\n\t\t\t\t\t\tid: Y\r\n\t\t\t\t\t};\r\n\t\t\t\t\tif (M.pv[0] > 0) {\r\n\t\t\t\t\t\tvar ae = c(Y);\r\n\t\t\t\t\t\tif (ae) {\r\n\t\t\t\t\t\t\tif (F(o[af].swfVersion) && !(M.wk && M.wk < 312)) {\r\n\t\t\t\t\t\t\t\tw(Y, true);\r\n\t\t\t\t\t\t\t\tif (ab) {\r\n\t\t\t\t\t\t\t\t\taa.success = true;\r\n\t\t\t\t\t\t\t\t\taa.ref = z(Y);\r\n\t\t\t\t\t\t\t\t\tab(aa)\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\tif (o[af].expressInstall && A()) {\r\n\t\t\t\t\t\t\t\t\tvar ai = {};\r\n\t\t\t\t\t\t\t\t\tai.data = o[af].expressInstall;\r\n\t\t\t\t\t\t\t\t\tai.width = ae.getAttribute(\"width\") || \"0\";\r\n\t\t\t\t\t\t\t\t\tai.height = ae.getAttribute(\"height\") || \"0\";\r\n\t\t\t\t\t\t\t\t\tif (ae.getAttribute(\"class\")) {\r\n\t\t\t\t\t\t\t\t\t\tai.styleclass = ae.getAttribute(\"class\")\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\tif (ae.getAttribute(\"align\")) {\r\n\t\t\t\t\t\t\t\t\t\tai.align = ae.getAttribute(\"align\")\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\tvar ah = {};\r\n\t\t\t\t\t\t\t\t\tvar X = ae.getElementsByTagName(\"param\");\r\n\t\t\t\t\t\t\t\t\tvar ac = X.length;\r\n\t\t\t\t\t\t\t\t\tfor (var ad = 0; ad < ac; ad++) {\r\n\t\t\t\t\t\t\t\t\t\tif (X[ad].getAttribute(\"name\").toLowerCase() != \"movie\") {\r\n\t\t\t\t\t\t\t\t\t\t\tah[X[ad].getAttribute(\"name\")] = X[ad].getAttribute(\"value\")\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\tP(ai, ah, Y, ab)\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\tp(ae);\r\n\t\t\t\t\t\t\t\t\tif (ab) {\r\n\t\t\t\t\t\t\t\t\t\tab(aa)\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tw(Y, true);\r\n\t\t\t\t\t\tif (ab) {\r\n\t\t\t\t\t\t\tvar Z = z(Y);\r\n\t\t\t\t\t\t\tif (Z && typeof Z.SetVariable != D) {\r\n\t\t\t\t\t\t\t\taa.success = true;\r\n\t\t\t\t\t\t\t\taa.ref = Z\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tab(aa)\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfunction z(aa) {\r\n\t\t\tvar X = null;\r\n\t\t\tvar Y = c(aa);\r\n\t\t\tif (Y && Y.nodeName == \"OBJECT\") {\r\n\t\t\t\tif (typeof Y.SetVariable != D) {\r\n\t\t\t\t\tX = Y\r\n\t\t\t\t} else {\r\n\t\t\t\t\tvar Z = Y.getElementsByTagName(r)[0];\r\n\t\t\t\t\tif (Z) {\r\n\t\t\t\t\t\tX = Z\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn X\r\n\t\t}\r\n\t\tfunction A() {\r\n\t\t\treturn !a && F(\"6.0.65\") && (M.win || M.mac) && !(M.wk && M.wk < 312)\r\n\t\t}\r\n\t\tfunction P(aa, ab, X, Z) {\r\n\t\t\ta = true;\r\n\t\t\tE = Z || null;\r\n\t\t\tB = {\r\n\t\t\t\tsuccess: false,\r\n\t\t\t\tid: X\r\n\t\t\t};\r\n\t\t\tvar ae = c(X);\r\n\t\t\tif (ae) {\r\n\t\t\t\tif (ae.nodeName == \"OBJECT\") {\r\n\t\t\t\t\tl = g(ae);\r\n\t\t\t\t\tQ = null\r\n\t\t\t\t} else {\r\n\t\t\t\t\tl = ae;\r\n\t\t\t\t\tQ = X\r\n\t\t\t\t}\r\n\t\t\t\taa.id = R;\r\n\t\t\t\tif (typeof aa.width == D || (!/%$/.test(aa.width) && parseInt(aa.width, 10) < 310)) {\r\n\t\t\t\t\taa.width = \"310\"\r\n\t\t\t\t}\r\n\t\t\t\tif (typeof aa.height == D || (!/%$/.test(aa.height) && parseInt(aa.height, 10) < 137)) {\r\n\t\t\t\t\taa.height = \"137\"\r\n\t\t\t\t}\r\n\t\t\t\tj.title = j.title.slice(0, 47) + \" - Flash Player Installation\";\r\n\t\t\t\tvar ad = M.ie && M.win ? \"ActiveX\" : \"PlugIn\",\r\n\t\t\t\t\tac = \"MMredirectURL=\" + O.location.toString().replace(/&/g, \"%26\") + \"&MMplayerType=\" + ad + \"&MMdoctitle=\" + j.title;\r\n\t\t\t\tif (typeof ab.flashvars != D) {\r\n\t\t\t\t\tab.flashvars += \"&\" + ac\r\n\t\t\t\t} else {\r\n\t\t\t\t\tab.flashvars = ac\r\n\t\t\t\t}\r\n\t\t\t\tif (M.ie && M.win && ae.readyState != 4) {\r\n\t\t\t\t\tvar Y = C(\"div\");\r\n\t\t\t\t\tX += \"SWFObjectNew\";\r\n\t\t\t\t\tY.setAttribute(\"id\", X);\r\n\t\t\t\t\tae.parentNode.insertBefore(Y, ae);\r\n\t\t\t\t\tae.style.display = \"none\";\r\n\t\t\t\t\t(function() {\r\n\t\t\t\t\t\tif (ae.readyState == 4) {\r\n\t\t\t\t\t\t\tae.parentNode.removeChild(ae)\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tsetTimeout(arguments.callee, 10)\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t})()\r\n\t\t\t\t}\r\n\t\t\t\tu(aa, ab, X)\r\n\t\t\t}\r\n\t\t}\r\n\t\tfunction p(Y) {\r\n\t\t\tif (M.ie && M.win && Y.readyState != 4) {\r\n\t\t\t\tvar X = C(\"div\");\r\n\t\t\t\tY.parentNode.insertBefore(X, Y);\r\n\t\t\t\tX.parentNode.replaceChild(g(Y), X);\r\n\t\t\t\tY.style.display = \"none\";\r\n\t\t\t\t(function() {\r\n\t\t\t\t\tif (Y.readyState == 4) {\r\n\t\t\t\t\t\tY.parentNode.removeChild(Y)\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tsetTimeout(arguments.callee, 10)\r\n\t\t\t\t\t}\r\n\t\t\t\t})()\r\n\t\t\t} else {\r\n\t\t\t\tY.parentNode.replaceChild(g(Y), Y)\r\n\t\t\t}\r\n\t\t}\r\n\t\tfunction g(ab) {\r\n\t\t\tvar aa = C(\"div\");\r\n\t\t\tif (M.win && M.ie) {\r\n\t\t\t\taa.innerHTML = ab.innerHTML\r\n\t\t\t} else {\r\n\t\t\t\tvar Y = ab.getElementsByTagName(r)[0];\r\n\t\t\t\tif (Y) {\r\n\t\t\t\t\tvar ad = Y.childNodes;\r\n\t\t\t\t\tif (ad) {\r\n\t\t\t\t\t\tvar X = ad.length;\r\n\t\t\t\t\t\tfor (var Z = 0; Z < X; Z++) {\r\n\t\t\t\t\t\t\tif (!(ad[Z].nodeType == 1 && ad[Z].nodeName == \"PARAM\") && !(ad[Z].nodeType == 8)) {\r\n\t\t\t\t\t\t\t\taa.appendChild(ad[Z].cloneNode(true))\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn aa\r\n\t\t}\r\n\t\tfunction u(ai, ag, Y) {\r\n\t\t\tvar X, aa = c(Y);\r\n\t\t\tif (M.wk && M.wk < 312) {\r\n\t\t\t\treturn X\r\n\t\t\t}\r\n\t\t\tif (aa) {\r\n\t\t\t\tif (typeof ai.id == D) {\r\n\t\t\t\t\tai.id = Y\r\n\t\t\t\t}\r\n\t\t\t\tif (M.ie && M.win) {\r\n\t\t\t\t\tvar ah = \"\";\r\n\t\t\t\t\tfor (var ae in ai) {\r\n\t\t\t\t\t\tif (ai[ae] != Object.prototype[ae]) {\r\n\t\t\t\t\t\t\tif (ae.toLowerCase() == \"data\") {\r\n\t\t\t\t\t\t\t\tag.movie = ai[ae]\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\tif (ae.toLowerCase() == \"styleclass\") {\r\n\t\t\t\t\t\t\t\t\tah += ' class=\"' + ai[ae] + '\"'\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\tif (ae.toLowerCase() != \"classid\") {\r\n\t\t\t\t\t\t\t\t\t\tah += \" \" + ae + '=\"' + ai[ae] + '\"'\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tvar af = \"\";\r\n\t\t\t\t\tfor (var ad in ag) {\r\n\t\t\t\t\t\tif (ag[ad] != Object.prototype[ad]) {\r\n\t\t\t\t\t\t\taf += '<param name=\"' + ad + '\" value=\"' + ag[ad] + '\" />'\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\taa.outerHTML = '<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"' + ah + \">\" + af + \"</object>\";\r\n\t\t\t\t\tN[N.length] = ai.id;\r\n\t\t\t\t\tX = c(ai.id)\r\n\t\t\t\t} else {\r\n\t\t\t\t\tvar Z = C(r);\r\n\t\t\t\t\tZ.setAttribute(\"type\", q);\r\n\t\t\t\t\tfor (var ac in ai) {\r\n\t\t\t\t\t\tif (ai[ac] != Object.prototype[ac]) {\r\n\t\t\t\t\t\t\tif (ac.toLowerCase() == \"styleclass\") {\r\n\t\t\t\t\t\t\t\tZ.setAttribute(\"class\", ai[ac])\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\tif (ac.toLowerCase() != \"classid\") {\r\n\t\t\t\t\t\t\t\t\tZ.setAttribute(ac, ai[ac])\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfor (var ab in ag) {\r\n\t\t\t\t\t\tif (ag[ab] != Object.prototype[ab] && ab.toLowerCase() != \"movie\") {\r\n\t\t\t\t\t\t\te(Z, ab, ag[ab])\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\taa.parentNode.replaceChild(Z, aa);\r\n\t\t\t\t\tX = Z\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn X\r\n\t\t}\r\n\t\tfunction e(Z, X, Y) {\r\n\t\t\tvar aa = C(\"param\");\r\n\t\t\taa.setAttribute(\"name\", X);\r\n\t\t\taa.setAttribute(\"value\", Y);\r\n\t\t\tZ.appendChild(aa)\r\n\t\t}\r\n\t\tfunction y(Y) {\r\n\t\t\tvar X = c(Y);\r\n\t\t\tif (X && X.nodeName == \"OBJECT\") {\r\n\t\t\t\tif (M.ie && M.win) {\r\n\t\t\t\t\tX.style.display = \"none\";\r\n\t\t\t\t\t(function() {\r\n\t\t\t\t\t\tif (X.readyState == 4) {\r\n\t\t\t\t\t\t\tb(Y)\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tsetTimeout(arguments.callee, 10)\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t})()\r\n\t\t\t\t} else {\r\n\t\t\t\t\tX.parentNode.removeChild(X)\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfunction b(Z) {\r\n\t\t\tvar Y = c(Z);\r\n\t\t\tif (Y) {\r\n\t\t\t\tfor (var X in Y) {\r\n\t\t\t\t\tif (typeof Y[X] == \"function\") {\r\n\t\t\t\t\t\tY[X] = null\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tY.parentNode.removeChild(Y)\r\n\t\t\t}\r\n\t\t}\r\n\t\tfunction c(Z) {\r\n\t\t\tvar X = null;\r\n\t\t\ttry {\r\n\t\t\t\tX = j.getElementById(Z)\r\n\t\t\t} catch (Y) {}\r\n\t\t\treturn X\r\n\t\t}\r\n\t\tfunction C(X) {\r\n\t\t\treturn j.createElement(X)\r\n\t\t}\r\n\t\tfunction i(Z, X, Y) {\r\n\t\t\tZ.attachEvent(X, Y);\r\n\t\t\tI[I.length] = [Z, X, Y]\r\n\t\t}\r\n\t\tfunction F(Z) {\r\n\t\t\tvar Y = M.pv,\r\n\t\t\t\tX = Z.split(\".\");\r\n\t\t\tX[0] = parseInt(X[0], 10);\r\n\t\t\tX[1] = parseInt(X[1], 10) || 0;\r\n\t\t\tX[2] = parseInt(X[2], 10) || 0;\r\n\t\t\treturn (Y[0] > X[0] || (Y[0] == X[0] && Y[1] > X[1]) || (Y[0] == X[0] && Y[1] == X[1] && Y[2] >= X[2])) ? true : false\r\n\t\t}\r\n\t\tfunction v(ac, Y, ad, ab) {\r\n\t\t\tif (M.ie && M.mac) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t\tvar aa = j.getElementsByTagName(\"head\")[0];\r\n\t\t\tif (!aa) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t\tvar X = (ad && typeof ad == \"string\") ? ad : \"screen\";\r\n\t\t\tif (ab) {\r\n\t\t\t\tn = null;\r\n\t\t\t\tG = null\r\n\t\t\t}\r\n\t\t\tif (!n || G != X) {\r\n\t\t\t\tvar Z = C(\"style\");\r\n\t\t\t\tZ.setAttribute(\"type\", \"text/css\");\r\n\t\t\t\tZ.setAttribute(\"media\", X);\r\n\t\t\t\tn = aa.appendChild(Z);\r\n\t\t\t\tif (M.ie && M.win && typeof j.styleSheets != D && j.styleSheets.length > 0) {\r\n\t\t\t\t\tn = j.styleSheets[j.styleSheets.length - 1]\r\n\t\t\t\t}\r\n\t\t\t\tG = X\r\n\t\t\t}\r\n\t\t\tif (M.ie && M.win) {\r\n\t\t\t\tif (n && typeof n.addRule == r) {\r\n\t\t\t\t\tn.addRule(ac, Y)\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tif (n && typeof j.createTextNode != D) {\r\n\t\t\t\t\tn.appendChild(j.createTextNode(ac + \" {\" + Y + \"}\"))\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfunction w(Z, X) {\r\n\t\t\tif (!m) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t\tvar Y = X ? \"visible\" : \"hidden\";\r\n\t\t\tif (J && c(Z)) {\r\n\t\t\t\tc(Z).style.visibility = Y\r\n\t\t\t} else {\r\n\t\t\t\tv(\"#\" + Z, \"visibility:\" + Y)\r\n\t\t\t}\r\n\t\t}\r\n\t\tfunction L(Y) {\r\n\t\t\tvar Z = /[\\\\\\\"<>\\.;]/;\r\n\t\t\tvar X = Z.exec(Y) != null;\r\n\t\t\treturn X && typeof encodeURIComponent != D ? encodeURIComponent(Y) : Y\r\n\t\t}\r\n\t\tvar d = function() {\r\n\t\t\t\tif (M.ie && M.win) {\r\n\t\t\t\t\twindow.attachEvent(\"onunload\", function() {\r\n\t\t\t\t\t\tvar ac = I.length;\r\n\t\t\t\t\t\tfor (var ab = 0; ab < ac; ab++) {\r\n\t\t\t\t\t\t\tI[ab][0].detachEvent(I[ab][1], I[ab][2])\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tvar Z = N.length;\r\n\t\t\t\t\t\tfor (var aa = 0; aa < Z; aa++) {\r\n\t\t\t\t\t\t\ty(N[aa])\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tfor (var Y in M) {\r\n\t\t\t\t\t\t\tM[Y] = null\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tM = null;\r\n\t\t\t\t\t\tfor (var X in swfobject) {\r\n\t\t\t\t\t\t\tswfobject[X] = null\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tswfobject = null\r\n\t\t\t\t\t})\r\n\t\t\t\t}\r\n\t\t\t}();\r\n\t\treturn {\r\n\t\t\tregisterObject: function(ab, X, aa, Z) {\r\n\t\t\t\tif (M.w3 && ab && X) {\r\n\t\t\t\t\tvar Y = {};\r\n\t\t\t\t\tY.id = ab;\r\n\t\t\t\t\tY.swfVersion = X;\r\n\t\t\t\t\tY.expressInstall = aa;\r\n\t\t\t\t\tY.callbackFn = Z;\r\n\t\t\t\t\to[o.length] = Y;\r\n\t\t\t\t\tw(ab, false)\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (Z) {\r\n\t\t\t\t\t\tZ({\r\n\t\t\t\t\t\t\tsuccess: false,\r\n\t\t\t\t\t\t\tid: ab\r\n\t\t\t\t\t\t})\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\tgetObjectById: function(X) {\r\n\t\t\t\tif (M.w3) {\r\n\t\t\t\t\treturn z(X)\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\tembedSWF: function(ab, ah, ae, ag, Y, aa, Z, ad, af, ac) {\r\n\t\t\t\tvar X = {\r\n\t\t\t\t\tsuccess: false,\r\n\t\t\t\t\tid: ah\r\n\t\t\t\t};\r\n\t\t\t\tif (M.w3 && !(M.wk && M.wk < 312) && ab && ah && ae && ag && Y) {\r\n\t\t\t\t\tw(ah, false);\r\n\t\t\t\t\tK(function() {\r\n\t\t\t\t\t\tae += \"\";\r\n\t\t\t\t\t\tag += \"\";\r\n\t\t\t\t\t\tvar aj = {};\r\n\t\t\t\t\t\tif (af && typeof af === r) {\r\n\t\t\t\t\t\t\tfor (var al in af) {\r\n\t\t\t\t\t\t\t\taj[al] = af[al]\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\taj.data = ab;\r\n\t\t\t\t\t\taj.width = ae;\r\n\t\t\t\t\t\taj.height = ag;\r\n\t\t\t\t\t\tvar am = {};\r\n\t\t\t\t\t\tif (ad && typeof ad === r) {\r\n\t\t\t\t\t\t\tfor (var ak in ad) {\r\n\t\t\t\t\t\t\t\tam[ak] = ad[ak]\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif (Z && typeof Z === r) {\r\n\t\t\t\t\t\t\tfor (var ai in Z) {\r\n\t\t\t\t\t\t\t\tif (typeof am.flashvars != D) {\r\n\t\t\t\t\t\t\t\t\tam.flashvars += \"&\" + ai + \"=\" + Z[ai]\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\tam.flashvars = ai + \"=\" + Z[ai]\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif (F(Y)) {\r\n\t\t\t\t\t\t\tvar an = u(aj, am, ah);\r\n\t\t\t\t\t\t\tif (aj.id == ah) {\r\n\t\t\t\t\t\t\t\tw(ah, true)\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tX.success = true;\r\n\t\t\t\t\t\t\tX.ref = an\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tif (aa && A()) {\r\n\t\t\t\t\t\t\t\taj.data = aa;\r\n\t\t\t\t\t\t\t\tP(aj, am, ah, ac);\r\n\t\t\t\t\t\t\t\treturn\r\n\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\tw(ah, true)\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif (ac) {\r\n\t\t\t\t\t\t\tac(X)\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t})\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (ac) {\r\n\t\t\t\t\t\tac(X)\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\tswitchOffAutoHideShow: function() {\r\n\t\t\t\tm = false\r\n\t\t\t},\r\n\t\t\tua: M,\r\n\t\t\tgetFlashPlayerVersion: function() {\r\n\t\t\t\treturn {\r\n\t\t\t\t\tmajor: M.pv[0],\r\n\t\t\t\t\tminor: M.pv[1],\r\n\t\t\t\t\trelease: M.pv[2]\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\thasFlashPlayerVersion: F,\r\n\t\t\tcreateSWF: function(Z, Y, X) {\r\n\t\t\t\tif (M.w3) {\r\n\t\t\t\t\treturn u(Z, Y, X)\r\n\t\t\t\t} else {\r\n\t\t\t\t\treturn undefined\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\tshowExpressInstall: function(Z, aa, X, Y) {\r\n\t\t\t\tif (M.w3 && A()) {\r\n\t\t\t\t\tP(Z, aa, X, Y)\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\tremoveSWF: function(X) {\r\n\t\t\t\tif (M.w3) {\r\n\t\t\t\t\ty(X)\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\tcreateCSS: function(aa, Z, Y, X) {\r\n\t\t\t\tif (M.w3) {\r\n\t\t\t\t\tv(aa, Z, Y, X)\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\taddDomLoadEvent: K,\r\n\t\t\taddLoadEvent: s,\r\n\t\t\tgetQueryParamValue: function(aa) {\r\n\t\t\t\tvar Z = j.location.search || j.location.hash;\r\n\t\t\t\tif (Z) {\r\n\t\t\t\t\tif (/\\?/.test(Z)) {\r\n\t\t\t\t\t\tZ = Z.split(\"?\")[1]\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (aa == null) {\r\n\t\t\t\t\t\treturn L(Z)\r\n\t\t\t\t\t}\r\n\t\t\t\t\tvar Y = Z.split(\"&\");\r\n\t\t\t\t\tfor (var X = 0; X < Y.length; X++) {\r\n\t\t\t\t\t\tif (Y[X].substring(0, Y[X].indexOf(\"=\")) == aa) {\r\n\t\t\t\t\t\t\treturn L(Y[X].substring((Y[X].indexOf(\"=\") + 1)))\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\treturn \"\"\r\n\t\t\t},\r\n\t\t\texpressInstallCallback: function() {\r\n\t\t\t\tif (a) {\r\n\t\t\t\t\tvar X = c(R);\r\n\t\t\t\t\tif (X && l) {\r\n\t\t\t\t\t\tX.parentNode.replaceChild(l, X);\r\n\t\t\t\t\t\tif (Q) {\r\n\t\t\t\t\t\t\tw(Q, true);\r\n\t\t\t\t\t\t\tif (M.ie && M.win) {\r\n\t\t\t\t\t\t\t\tl.style.display = \"block\"\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif (E) {\r\n\t\t\t\t\t\t\tE(B)\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\ta = false\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}();\r\n\r\nfunction bdc_showCompanionAdSection(adstring) {\r\n\tcleanAd();\r\n\tvar vca_div = document.createElement(\"div\");\r\n\tvca_div.setAttribute(\"id\", \"bdc_videoCompanionAdSection\");\r\n\tvca_div.innerHTML = adstring;\r\n\tdocument.getElementById(\"Col2Top\").appendChild(vca_div);\r\n\t$(\"#bdc_videoCompanionAdSection\").slideDown(1000);\r\n}\r\n\r\nfunction cleanAd() {\r\n\tvar x = document.getElementById(\"Col2Top\");\r\n\twhile (x.lastChild) {\r\n\t\tx.removeChild(x.lastChild);\r\n\t}\r\n}\r\n// YourTown Boston neighborhoods/suburbs toggle\r\n\r\nfunction ytFlipTowns(resp) {\r\n\tvar isSuburbs = 0;\r\n\tif (resp.type == 'default') isSuburbs = 1;\r\n\tflipTownList(isSuburbs, false);\r\n}\r\n\r\nfunction flipTownList(isSuburbs, flashToggle) {\r\n\tif (isSuburbs == 0) {\r\n\t\t$('#townList').hide();\r\n\t\t$('#neighborhoodList').show();\r\n\t\tif (typeof(flashToggle) == 'undefined') {\r\n\t\t\tdocument.getElementById(\"state_towns\").jsZoomToTown('boston');\r\n\t\t}\r\n\t} else {\r\n\t\t$('#neighborhoodList').hide();\r\n\t\t$('#townList').show();\r\n\t\tif (typeof(flashToggle) == 'undefined') {\r\n\t\t\tdocument.getElementById(\"state_towns\").jsZoomToDefault();\r\n\t\t}\r\n\t}\r\n}\r\n// End YourTown neighborhoods/suburbs toggle\r\n/* To populate the Real Estate search box */\r\n\r\nfunction reSearchTextDisplay() {\r\n\tvar searchChild = document.getElementById('suggest1').firstChild;\r\n\tvar searchChildValue = \"Enter city, town or neighborhood\";\r\n\tsearchChild.value = searchChildValue;\r\n\tsearchChild.onblur = function() {\r\n\t\tif (searchChild.value == \"\") searchChild.value = searchChildValue;\r\n\t};\r\n\tsearchChild.onfocus = function() {\r\n\t\tsearchChild.value = \"\";\r\n\t};\r\n\treturn false;\r\n}\r\n// PointsLocal widget function \r\n\r\nfunction loadPoints(design_id, element_id, proxy, options) {\r\n\tvar pointsdata = \"\";\r\n\tvar s_leadin;\r\n\tvar id = \"#\" + element_id;\r\n\tvar pointscall = proxy + design_id;\r\n\t$(document).ready(function() {\r\n\t\t$.get(pointscall, {}, function(data) {\r\n\t\t\t$(data).find('item').each(function() {\r\n\t\t\t\tvar title = $(this).find('title').text();\r\n\t\t\t\tvar url = $(this).find('url').text();\r\n\t\t\t\tvar sourcename = $(this).find('sourcename').text();\r\n\t\t\t\tvar description = $(this).find('description').text();\r\n\t\t\t\tvar show_leadin = $(this).find('showdescription').text();\r\n\t\t\t\ts_leadin = show_leadin;\r\n\t\t\t\tvar date = $(this).find('date').text();\r\n\t\t\t\tvar tmpDate = new Date(date);\r\n\t\t\t\tvar image = $(this).find('image').text();\r\n\t\t\t\tvar show_image = 1;\r\n\t\t\t\tif (show_leadin != 1) {\r\n\t\t\t\t\tpointsdata += '<li><a href=\"' + url + '\"><b>' + title + '</b></a> <span class=\"attr\">' + sourcename + ', ' + (parseInt(tmpDate.getMonth()) + 1) + '/' + tmpDate.getDate() + '/' + tmpDate.getFullYear() + '</span></li>';\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (show_image == 1 && image) {\r\n\t\t\t\t\t\tpointsdata += '<div class=\"padTop4\"></div><div class=\"img100h3Left\"><a href=\"' + url + '\">' + '<img src=\"' + image + '\" /></a><h3><a href=\"' + url + '\">' + title + '</a></h3><div class=\"tt\"><span>' + description + ' <span class=\"attr\">' + sourcename + ', ' + (parseInt(tmpDate.getMonth()) + 1) + '/' + tmpDate.getDate() + '/' + tmpDate.getFullYear() + '</span></span></div><div class=\"cf\"></div></div><div class=\"padTop4\"></div>';\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tpointsdata += '<div class=\"padTop4\"></div><div class=\"img100h3Left\"><h3><a href=\"' + url + '\">' + title + '</a></h3><div class=\"tt\"><span>' + description + ' <span class=\"attr\">' + sourcename + ', ' + (parseInt(tmpDate.getMonth()) + 1) + '/' + tmpDate.getDate() + '/' + tmpDate.getFullYear() + '</span></span></div><div class=\"cf\"></div></div><div class=\"padTop4\"></div>';\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t\tif (s_leadin != 1) {\r\n\t\t\t\tpointsdata = '<ul class=\"linklist\">' + pointsdata + '</ul>';\r\n\t\t\t}\r\n\t\t\t$(id).append(pointsdata);\r\n\t\t});\r\n\t});\r\n} //end pointsLocal\r\njQuery(function($) {\r\n\t$('.generic-scroller').each(function() {\r\n\t\tvar scroller = $(this),\r\n\t\t\tpos_prop = scroller.hasClass('generic-scroller-horizontal') ? 'left' : 'top',\r\n\t\t\tsize_prop = pos_prop === 'left' ? 'width' : 'height',\r\n\t\t\touter = scroller.find('.generic-scroller-outer'),\r\n\t\t\tinner = outer.children().eq(0);\r\n\t\tif (inner.children().length <= 1) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t// Allow interactive controls to be hidden until ready.\r\n\t\tscroller.addClass('generic-scroller-js');\r\n\t\t// Add hover class for prev/next button mouseover.\r\n\t\tscroller.find('.generic-scroller-prev_next').bind('mouseenter mouseleave', function(e) {\r\n\t\t\t$(this).toggleClass('generic-scroller-prev_next-hover', e.type === 'mouseenter');\r\n\t\t});\r\n\t\t// Prev button click.\r\n\t\tscroller.find('.generic-scroller-prev').click(function() {\r\n\t\t\tvar pos = parseInt(inner.css(pos_prop)),\r\n\t\t\t\tscroller_size = outer[size_prop](),\r\n\t\t\t\tobj = {};\r\n\t\t\tinner.children(':last').prependTo(inner);\r\n\t\t\tinner.css(pos_prop, -scroller_size);\r\n\t\t\tobj[pos_prop] = 0;\r\n\t\t\tinner.stop(true, true).animate(obj);\r\n\t\t});\r\n\t\t// Next button click.\r\n\t\tscroller.find('.generic-scroller-next').click(function() {\r\n\t\t\tvar pos = parseInt(inner.css(pos_prop)),\r\n\t\t\t\tscroller_size = outer[size_prop](),\r\n\t\t\t\tobj = {};\r\n\t\t\tobj[pos_prop] = pos - scroller_size;\r\n\t\t\tinner.stop(true, true).animate(obj, function() {\r\n\t\t\t\tinner.children(':first').appendTo(inner);\r\n\t\t\t\tinner.css(pos_prop, 0);\r\n\t\t\t});\r\n\t\t});\r\n\t});\r\n});\r\n// Quote Scroller.\r\njQuery(function($) {\r\n\t$('.quote-scroller li').each(function() {\r\n\t\tvar li = $(this),\r\n\t\t\ta = li.find('a').eq(0),\r\n\t\t\thref = a.attr('href'),\r\n\t\t\thit;\r\n\t\tif (href) {\r\n\t\t\tli.addClass('clickable');\r\n\t\t\thit = a.clone().html('&nbsp;').addClass('button-hitarea').appendTo(li);\r\n\t\t\tli.bind('mouseenter mouseleave', function(e) {\r\n\t\t\t\tli.toggleClass('hover', e.type === 'mouseenter');\r\n\t\t\t});\r\n\t\t}\r\n\t});\r\n});\r\n// BCOM-1439: billboardSlider\r\n(function($) {\r\n\tvar ns = $.fn.billboardSlider = function(options) {\r\n\t\t\toptions = $.extend({}, ns.options, options);\r\n\t\t\treturn this.each(function() {\r\n\t\t\t\tvar that = $(this),\r\n\t\t\t\t\t// Get cookie name.\r\n\t\t\t\t\tcname = that.attr('data-cname'),\r\n\t\t\t\t\t// Get widget state based on cookie.\r\n\t\t\t\t\tcollapsed = getCookie(cname),\r\n\t\t\t\t\t// To cancel the timeout.\r\n\t\t\t\t\ttimeout_id;\r\n\t\t\t\t// If already initialized, skip!\r\n\t\t\t\tif (that.data('billboardSlider')) {\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\t// Set already-initialized flag\r\n\t\t\t\tthat.data('billboardSlider', true);\r\n\t\t\t\tif (!collapsed) {\r\n\t\t\t\t\t// Close billboard after a delay (unless canceled).\r\n\t\t\t\t\ttimeout_id = setTimeout(toggle, options.delay);\r\n\t\t\t\t} else {\r\n\t\t\t\t\ttoggle(true);\r\n\t\t\t\t}\r\n\t\t\t\t// Toggle the clicked element\r\n\r\n\t\t\t\tfunction toggle(instantly) {\r\n\t\t\t\t\tvar speed = instantly ? 0 : options.speed;\r\n\t\t\t\t\tthat.children('.slider-expanded').stop(true, true).animate({\r\n\t\t\t\t\t\theight: 'toggle'\r\n\t\t\t\t\t}, speed).siblings('div').stop(true, true).animate({\r\n\t\t\t\t\t\theight: 'toggle'\r\n\t\t\t\t\t}, speed);\r\n\t\t\t\t};\r\n\t\t\t\t// Binding the toggle function to click.\r\n\t\t\t\tthat.find('.slider-toggle').click(function(e) {\r\n\t\t\t\t\te.preventDefault();\r\n\t\t\t\t\tvar date = new Date();\r\n\t\t\t\t\tdate.setDate(date.getDate() + options.expiration_days);\r\n\t\t\t\t\tsetCookie(cname, 1, date);\r\n\t\t\t\t\ttimeout_id && clearTimeout(timeout_id);\r\n\t\t\t\t\ttoggle();\r\n\t\t\t\t});\r\n\t\t\t});\r\n\t\t};\r\n\t// Set up some reasonable global defaults.\r\n\tns.options = {\r\n\t\tdelay: 10000,\r\n\t\tspeed: 500,\r\n\t\texpiration_days: 7\r\n\t};\r\n\t// Initialize any sliders that weren't explicitly initialized.\r\n\t$(function() {\r\n\t\t// $('.slider-billboard').billboardSlider();\r\n\t\tns.call($('.slider-billboard'));\r\n\t});\r\n})(jQuery);\r\n// BCOM-1755 re-do Weather Map tabs (originally done w/Protoype) \r\n$(document).ready(function() {\r\n\t// Weather map tabs \r\n\t$(\".weatherMapsContent\").hide(); // Hide tab content \r\n\t$(\"ul.weatherMapTabs li:first\").addClass(\"active\").show(); // Show 1st element by default \r\n\t$(\".weatherMapsContent:first\").show(); // Ditto \r\n\t$(\"ul.weatherMapTabs li\").click(function() { // tab is clicked \r\n\t\t$(\"ul.weatherMapTabs li\").removeClass(\"active\"); // reset active \r\n\t\t$(this).addClass(\"active\"); // make new active \r\n\t\t$(\".weatherMapsContent\").hide(); // hidecurrent content so we can show selected \r\n\t\tvar activeTab = $(this).find(\"a\").attr(\"href\"); // find id by href \r\n\t\t$(activeTab).fadeIn();\r\n\t\treturn false;\r\n\t});\r\n\t// Temp toggle F/C \r\n\t$(\"#tempToggle .temp a\").click(function() {\r\n\t\t$(\"#tempToggle .temp\").toggleClass(\"active\");\r\n\t\t$(\".currentDeg\").toggleClass(\"active\");\r\n\t});\r\n}); /* Travel drop-down widget revisited */\r\nvar count = 0;\r\n\r\nfunction clickLink(containerID) {\r\n\tvar widgetkeyword = '';\r\n\tif (count == 0) {\r\n\t\tcount++;\r\n\t} else if (count == 1) {\r\n\t\tvar mylist = document.getElementById(containerID);\r\n\t\tvar urlString = mylist.options[mylist.selectedIndex].value;\r\n\t\tif (urlString != 'none') {\r\n\t\t\twindow.location = mylist.options[mylist.selectedIndex].value\r\n\t\t}\r\n\t\tcount = 0;\r\n\t}\r\n}\r\n// Enable print styles\r\n$(function() {\r\n\t// Bind to blog print link\r\n\t$('a#blogPrint').click(function() {\r\n\t\t// Launch print dialog\r\n\t\tprint();\r\n\t\treturn false;\r\n\t});\r\n});\r\n/* Daily Dose health widget,\r\n * enable category toggling */\r\n$(function() {\r\n\tvar filterTeaseButtons = $('li.filter-single-category').not('#more_categories');\r\n\t// Bind toggling to click\r\n\tfilterTeaseButtons.click(function() {\r\n\t\tvar that = $(this);\r\n\t\tvar curID = that.attr('id');\r\n\t\tvar curTease = $('li.filter-single-tease#' + curID + '_tease');\r\n\t\tthat.addClass('active').siblings().removeClass('active');\r\n\t\tcurTease.addClass('active').siblings().removeClass('active');\r\n\t});\r\n}); /* empty mbox function */\r\n\r\nfunction mboxCreate() {}; /* Allows for omniture tracking to be appended to deals widgets with some specificity */\r\n$(function() {\r\n\tvar all = document.getElementsByTagName(\"a\"),\r\n\t\ts = \"?s_campaign=\",\r\n\t\tp = \"?p1=\";\r\n\tfor (var i = all.length; i >= 0; i--) {\r\n\t\tif ($(all[i]).attr(\"data-campaign\")) {\r\n\t\t\tvar us = \"_\",\r\n\t\t\t\tcurrent = $(all[i]),\r\n\t\t\t\ttrackposn = current.attr(\"data-posn\"),\r\n\t\t\t\ttrackposn2 = current.attr(\"data-posntwo\"),\r\n\t\t\t\tomnitureName = \"Deals\",\r\n\t\t\t\thref = current.attr(\"href\"),\r\n\t\t\t\tmerchantAbbr = current.text().split(' ').slice(0, 2).join(''); //scavanged from deals widget\r\n\t\t\t;\r\n\t\t\t//deals with custom set deals\r\n\t\t\tif (current.attr(\"data-campaign\") === \"s\") {\r\n\t\t\t\t$(all[i]).attr('href', href + s + omnitureName + us + var5 + trackposn + us + trackposn2);\r\n\t\t\t}\r\n\t\t\t//deals with appended deals\r\n\t\t\tif (current.attr(\"data-campaign\") === \"s\" && current.attr(\"data-posntwo\") === \"deal\") {\r\n\t\t\t\t$(all[i]).attr('href', href + s + omnitureName + us + var5 + trackposn + us + merchantAbbr);\r\n\t\t\t}\r\n\t\t\tif (current.attr(\"data-campaign\") === \"p\") {\r\n\t\t\t\t$(all[i]).attr('href', href + p + trackposn + us + var5 + trackposn2);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n});\r\nvar _vrq = _vrq || [];\r\n_vrq.push(['id', 55]);\r\nif (typeof pgType != 'undefined' && pgType == 'Homepage') {\r\n\t_vrq.push(['automate', true]);\r\n} else {\r\n\t_vrq.push(['automate', false]);\r\n}\r\n_vrq.push(['track', function() {}]);\r\n(function(d, a) {\r\n\tvar s = d.createElement(a),\r\n\t\tx = d.getElementsByTagName(a)[0];\r\n\ts.async = true;\r\n\ts.src = 'http://a.visualrevenue.com/vrs.js';\r\n\tx.parentNode.insertBefore(s, x);\r\n})(document, 'script');\r\nvar radioType = \"header\";\r\n\r\nfunction constantContact() {\r\n\tsetTimeout(function() {\r\n\t\tcheckNowPlaying()\r\n\t}, 60000);\r\n}\r\n\r\nfunction scrollerDome() {\r\n\t$('.scrollMeAway').bind('marquee', function() {\r\n\t\tvar ob = $(this);\r\n\t\tvar tw = ob.width();\r\n\t\tvar ww = ob.parent().width();\r\n\t\tob.css({\r\n\t\t\tright: -tw\r\n\t\t});\r\n\t\tob.animate({\r\n\t\t\tright: ww\r\n\t\t}, 10000, 'linear', function() {\r\n\t\t\tob.trigger('marquee');\r\n\t\t});\r\n\t}).trigger('marquee');\r\n}\r\n\r\nfunction checkNowPlaying() {\r\n\tif (radioType != 'none') {\r\n\t\tvar randomMeAway = Math.floor(Math.random() * 101);\r\n\t\tvar $elSongArtist = $(\"#now-playing-\" + radioType + \" .np-song-artist\");\r\n\t\tvar $elSongTitle = $(\"#now-playing-\" + radioType + \" .np-song-title\");\r\n\t\tvar jsonURL = 'http://cache.boston.com/ae/radio/nowplaying.json?check=' + randomMeAway;\r\n\t\t$.getJSON(jsonURL, function(data) {\r\n\t\t\tif ($elSongArtist.text() != data.nowplaying.artist) {\r\n\t\t\t\t$elSongArtist.replaceWith('<span class=\"np-song-artist\">' + data.nowplaying.artist + '</span>');\r\n\t\t\t\t$elSongTitle.replaceWith('<span class=\"np-song-title\">' + data.nowplaying.track + '</span>');\r\n\t\t\t\tscrollerDome();\r\n\t\t\t} else {\r\n\t\t\t\tscrollerDome();\r\n\t\t\t}\r\n\t\t});\r\n\t\tconstantContact();\r\n\t}\r\n}\r\n//$(function() {checkNowPlaying();})\r\n// adds the 'wmode=transparent' param to any object on the page\r\n//\r\n// (04/19/12) - Commented this out, as it causes IE6-8 to choke.\r\n// Appending params to an object in IE can be done, I believe, just not this way.\r\n// See http://bugs.jquery.com/ticket/11280 for more info - Eddie\r\n/*\r\n$(function(){\r\n var wmodeSet = '<param name=\"wmode\" value=\"transparent\" />';\r\n $(\".tcCentered object\").append(wmodeSet);\r\n $(\".videoplayer object\").append(wmodeSet);\r\n});\r\n*/\r\nvar bcom_cookie = {\r\n\tget: function(the_cookie) { // Returns value of the_cookie\r\n\t\tvar cookie_array = document.cookie.split(';'),\r\n\t\t\tthis_cookie, cookie_name, cookie_value, i;\r\n\t\tfor (i = 0; i < cookie_array.length; i++) {\r\n\t\t\tthis_cookie = cookie_array[i].split('=');\r\n\t\t\tcookie_name = $.trim(this_cookie[0]);\r\n\t\t\tcookie_value = $.trim(this_cookie[1]);\r\n\t\t\tif (cookie_name == the_cookie) {\r\n\t\t\t\treturn unescape(cookie_value);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t},\r\n\tset: function(cookie_name, value, expiration_days, escape_this) { // Sets a cookie\r\n\t\tvar expiry_date = new Date();\r\n\t\texpiry_date.setDate(expiry_date.getDate() + expiration_days);\r\n\t\t//var the_cookie = escape(value) + ((expiration_days == null) ? '' : '; expires='+expiry_date.toUTCString()) + '; path=/';\r\n\t\t// Not escaping cookie value lets login redirect work as intended\r\n\t\tvar the_cookie = value + ((expiration_days == null) ? '' : '; expires=' + expiry_date.toUTCString()) + '; path=/';\r\n\t\tdocument.cookie = cookie_name + '=' + the_cookie + ';domain=.boston.com';\r\n\t}\r\n}\r\nvar bcom_regi = {\r\n\tmax_count: 50,\r\n\t// Max pathCnt cookie value before redirect\r\n\tvalid_ref: [ // Array of valid referral URLs\r\n\t'google.com', 'search.yahoo.com'],\r\n\tpage_status: function() { // Determines whether page is behind the annoyance wall\r\n\t\tvar regi_status = document.getElementsByTagName('body')[0].getAttribute('data-regi');\r\n\t\tregi_status = regi_status == 'outside' ? false : true;\r\n\t\treturn regi_status;\r\n\t},\r\n\tcheck_ref: function() { // Checks referrer URL against valid referrers\r\n\t\tvar ref_domain = document.referrer.split('/')[2],\r\n\t\t\tvalid_ref = bcom_regi.valid_ref,\r\n\t\t\ti;\r\n\t\tfor (i = 0; i < valid_ref.length; i++) {\r\n\t\t\tif (ref_domain == valid_ref) {\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false\r\n\t},\r\n\tcheck_login: function() {\r\n\t\t// Check for pathAuth cookie - if one exists, do nothing\r\n\t\tif (!bcom_cookie.get('pathAuth')) {\r\n\t\t\t// Check referer against exceptions - if match, do nothing\r\n\t\t\tif (!bcom_regi.check_ref()) {\r\n\t\t\t\t// Check pathCnt cookie\r\n\t\t\t\tvar path_count = bcom_cookie.get('pathCnt');\r\n\t\t\t\tpath_count = path_count == false ? 1 : parseInt(path_count);\r\n\t\t\t\tif (1) { // disable regi wall\r\n\t\t\t\t\t//if( path_count <= bcom_regi.max_count ){\r\n\t\t\t\t\t// Increment pathCnt cookie by 1, then do nothing\r\n\t\t\t\t\tpath_count++;\r\n\t\t\t\t\tbcom_cookie.set('pathCnt', path_count);\r\n\t\t\t\t} else {\r\n\t\t\t\t\t// Redirect to login page\r\n\t\t\t\t\tdocument.location = 'https://www.boston.com/Boston/eom/SysConfig/WebPortal/Boston/Framework/regi/regi-login-register.jsp';\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n};\r\n$(document).ready(function() {\r\n\t// Set the pathUrl cookie\r\n\tbcom_cookie.set('pathUrl', document.location.href);\r\n});\r\n\r\n// For ad-timing script\r\n// (function (win, undefined) {\r\n// var timers = {},\r\n// console = (win.console || {\r\n// log: function () {}\r\n// });\r\n// \r\n// function AdTimer() {\r\n// if (this === win) {\r\n// return new AdTimer();\r\n// }\r\n// this.running = false;\r\n// return this;\r\n// }\r\n// \r\n// AdTimer.prototype.start = function () {\r\n// if (this.running) {\r\n// return this;\r\n// }\r\n// \r\n// this.running = true;\r\n// this.start_time = new Date().getTime();\r\n// return this;\r\n// };\r\n// \r\n// AdTimer.prototype.stop = function () {\r\n// if (!this.running) {\r\n// return this;\r\n// }\r\n// this.running = false;\r\n// this.stop_time = new Date().getTime();\r\n// this._report();\r\n// return this;\r\n// };\r\n// \r\n// AdTimer.prototype._report = function () {\r\n// var spent = (this.stop_time - this.start_time) / 1000;\r\n// \r\n// this.report = {\r\n// total: spent,\r\n// minutes: Math.floor(spent / 60),\r\n// seconds: Math.floor(spent % 60)\r\n// };\r\n// \r\n// return this;\r\n// };\r\n// \r\n// \r\n// /**\r\n// * External functions that give access to new AdTimers \r\n// * as well as the structure that holds them all\r\n// */\r\n// function startTimer(namespace, event) {\r\n// \r\n// if (!timers.hasOwnProperty(namespace)) {\r\n// timers[namespace] = {};\r\n// }\r\n// \r\n// if (timers[namespace][event]) {\r\n// timers[namespace][event].stop();\r\n// delete timers[namespace][event];\r\n// }\r\n// \r\n// timers[namespace][event] = new AdTimer();\r\n// timers[namespace][event].start();\r\n// return;\r\n// }\r\n// \r\n// function stopTimer(namespace, event) {\r\n// var s, dateString, nameString, date = new Date();\r\n// \r\n// \r\n// if (!timers[namespace] || !timers[namespace][event]) {\r\n// return {};\r\n// }\r\n// timers[namespace][event].stop();\r\n// \r\n// dateString = (date.getMonth() + 1) + '-' + date.getDate();\r\n// nameString = (namespace + ' | ' + dateString + ' | ' + event + ' | ' + timers[namespace][event].report.seconds);\r\n// \r\n// console.log(nameString);\r\n// \r\n// s = s_gi('nytbglobe');\r\n// s.tl(this, 'o', nameString);\r\n// s.tl(window, 'o', 'window | ' + nameString);\r\n// \r\n// return timers[namespace][event].report;\r\n// }\r\n// \r\n// function showAll() {\r\n// return timers;\r\n// }\r\n// \r\n// if (!win.startTimer && !win.stopTimer && !win.getTimers) {\r\n// win.startTimer = startTimer;\r\n// win.stopTimer = stopTimer;\r\n// win.getTimers = showAll;\r\n// }\r\n// \r\n// }(window));\r\n/* JS - Regi Wall */\r\nif (typeof bcom === \"undefined\") {\r\n\tbcom = {};\r\n} else if (typeof bcom.util !== \"object\") {\r\n\tbcom.util = {\r\n\t\tgetCookie: function(key, _document, _$) {\r\n\t\t\tvar cookie;\r\n\t\t\tvar cookiePairStrings, pairCount, index;\r\n\t\t\tvar currentPair, currentKey;\r\n\t\t\tvar value;\r\n\t\t\t_document = _document || document;\r\n\t\t\t_$ = _$ || $;\r\n\t\t\tcookie = _document.cookie\r\n\t\t\tcookiePairStrings = cookie.split(';');\r\n\t\t\tpairCount = cookiePairStrings.length;\r\n\t\t\tfor (index = 0; index < pairCount; index++) {\r\n\t\t\t\tcurrentPair = cookiePairStrings[index].split('=');\r\n\t\t\t\tcurrentKey = _$.trim(currentPair[0]);\r\n\t\t\t\tif (currentKey === key) {\r\n\t\t\t\t\tvalue = currentPair[1];\r\n\t\t\t\t\tvalue = _$.trim(value);\r\n\t\t\t\t\tvalue = unescape(value);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn value;\r\n\t\t},\r\n\t\tgetCookieInt: function(key, _document, _$) {\r\n\t\t\tvar value;\r\n\t\t\tvalue = bcom.util.getCookie(key, _document, _$);\r\n\t\t\tvalue = value || \"0\";\r\n\t\t\tvalue = parseInt(value, 10);\r\n\t\t\treturn value;\r\n\t\t},\r\n\t\t_buildCookieString: function(key, value, expirationDays, _today) {\r\n\t\t\tvar expiryDate;\r\n\t\t\tvar cookieFragments;\r\n\t\t\tcookieFragments = [];\r\n\t\t\tcookieFragments.push(key + \"=\" + value);\r\n\t\t\tif (typeof expirationDays !== \"undefined\") {\r\n\t\t\t\texpiryDate = _today || new Date();\r\n\t\t\t\texpiryDate.setDate(expiryDate.getDate() + expirationDays);\r\n\t\t\t\tcookieFragments.push(\"expires=\" + expiryDate.toUTCString());\r\n\t\t\t}\r\n\t\t\tcookieFragments.push(\"path=/\");\r\n\t\t\tcookieFragments.push(\"domain=.boston.com\");\r\n\t\t\treturn cookieFragments.join(\";\");\r\n\t\t},\r\n\t\tsetCookie: function(key, value, expirationDays) {\r\n\t\t\tdocument.cookie = bcom.util._buildCookieString(key, value, expirationDays);\r\n\t\t},\r\n\t\tincrementCookie: function(key, _document, _$) {\r\n\t\t\tvar value;\r\n\t\t\tvalue = bcom.util.getCookieInt(key, _document, _$);\r\n\t\t\tbcom.util.setCookie(key, value + 1);\r\n\t\t},\r\n\t\tgetQueryValue: function(key, _window) {\r\n\t\t\tvar search;\r\n\t\t\tvar keyValuePairs, pairsCount, index;\r\n\t\t\tvar pairString, pair, currentKey;\r\n\t\t\tvar value;\r\n\t\t\t_window = _window || window;\r\n\t\t\tsearch = _window.location.search.substr(1);\r\n\t\t\tkeyValuePairs = search.split(\"&\");\r\n\t\t\tpairsCount = keyValuePairs.length;\r\n\t\t\tfor (index = 0; index < pairsCount; index++) {\r\n\t\t\t\tpairString = keyValuePairs[index];\r\n\t\t\t\tpair = pairString.split(\"=\");\r\n\t\t\t\tcurrentKey = pair.shift();\r\n\t\t\t\tif (currentKey === key) {\r\n\t\t\t\t\tvalue = pair.join(\"=\");\r\n\t\t\t\t\tif (pair.length === 0) {\r\n\t\t\t\t\t\tvalue = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn value;\r\n\t\t}\r\n\t};\r\n}\r\nif (typeof bcom === \"undefined\") {\r\n\tbcom = {};\r\n}\r\nbcom.nonMethodeRegi = {\r\n\tpageCountLimit: 20,\r\n\tgetCurrentCanonicalUrl: function(_document) {\r\n\t\treturn $('link[rel=canonical]').attr('href');\r\n\t},\r\n\t_whitelistedRegiPages: function() {\r\n\t\tvar pathArray = ['', '/news/', '/yourtown/', '/business/', '/sports/', '/lifestyle/', '/ae/', '/thingstodo/', '/travel/', '/yourtown/yourcampus/'];\r\n\t\treturn bcom.nonMethodeRegi._addCanonicalDomain('www', pathArray);\r\n\t},\r\n\t_whitelistedRegiPaths: function() {\r\n\t\treturn bcom.nonMethodeRegi._addCanonicalDomain('www', ['/ae/radio/player', '/bigpicture', '/news/traffic', '/cars', '/jobs', '/realestate', '/search', '/help', '/pass-it-on', '/images/test', '/images/ads', '/news/weather', '/multimedia', '/marketing', '/advertisers']).concat(bcom.nonMethodeRegi._addCanonicalDomain('yourtown', [''])).concat(\r\n\t\tbcom.nonMethodeRegi._addCanonicalDomain('yourcampus', ['']));\r\n\t},\r\n\t_addCanonicalDomain: function(context, array) {\r\n\t\t$.each(array, function(index, value) {\r\n\t\t\tarray[index] = 'http://' + context + '.boston.com' + value;\r\n\t\t});\r\n\t\treturn array;\r\n\t},\r\n\tisPageBehindRegiWall: function() {\r\n\t\tvar behindRegi = false;\r\n\t\tvar canonicalUrl = bcom.nonMethodeRegi.getCurrentCanonicalUrl();\r\n\t\t$.each(bcom.nonMethodeRegi._whitelistedRegiPages(), function(index, value) {\r\n\t\t\tif (canonicalUrl === value) {\r\n\t\t\t\tbehindRegi = true;\r\n\t\t\t}\r\n\t\t});\r\n\t\t$.each(bcom.nonMethodeRegi._whitelistedRegiPaths(), function(index, value) {\r\n\t\t\tif (canonicalUrl.indexOf(value) != -1) {\r\n\t\t\t\tbehindRegi = true;\r\n\t\t\t}\r\n\t\t});\r\n\t\treturn behindRegi;\r\n\t},\r\n\tisURLEscaped: function(_window) {\r\n\t\t_window = _window || window;\r\n\t\treturn (_window.location.toString().indexOf('__') != -1) ? true : false;\r\n\t},\r\n\tisLoggedIn: function() {\r\n\t\treturn bcom.util.getCookie('pathAuth');\r\n\t},\r\n\tshouldIncrementPageCount: function() {\r\n\t\tif (bcom.nonMethodeRegi.isLoggedIn()) return;\r\n\t\tif (bcom.nonMethodeRegi.isPageBehindRegiWall()) return;\r\n\t\treturn true;\r\n\t},\r\n\tshouldRedirectToLogin: function() {\r\n\t\tvar pageCount;\r\n\t\tif (bcom.nonMethodeRegi.isLoggedIn()) return;\r\n\t\tif (bcom.nonMethodeRegi.isURLEscaped()) return;\r\n\t\tif (bcom.nonMethodeRegi.isPageBehindRegiWall()) return;\r\n\t\tpageCount = bcom.util.getCookieInt('pathCnt');\r\n\t\treturn pageCount > bcom.nonMethodeRegi.pageCountLimit;\r\n\t}\r\n};\r\nbcom.util.setCookie('pathUrl', document.location.href);\r\nif (bcom.nonMethodeRegi.shouldIncrementPageCount()) {\r\n\tbcom.util.incrementCookie('pathCnt');\r\n}\r\nif (bcom.nonMethodeRegi.shouldRedirectToLogin()) {\r\n\tdocument.location = 'http://www.boston.com/register';\r\n}" }, { "alpha_fraction": 0.4990619122982025, "alphanum_fraction": 0.5056285262107849, "avg_line_length": 21.22916603088379, "blob_id": "23b8c60741995b9e7ec03705dd202ff34906e0a6", "content_id": "8421f8d50f3d36d4e2392d12d15044927ba5f590", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1066, "license_type": "permissive", "max_line_length": 56, "num_lines": 48, "path": "/servers/demo-scaleout/html/avinetworks/static/avi/js/scripts.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "/* Mobi Nav */\n\n\t$(\"#header .menu\").click(function() {\n\t $('#header ul').toggle();\n\t $('#header ul').toggleClass('mobi_nav');\n\t $('#header .arrow').toggle();\n\t $(\"#header ul.mobi_nav li a\").click(function() {\n\t\t $('#header ul').hide();\n\t\t $('#header .arrow').hide();\n\t\t});\n\t});\n\n\n/* Text Toggle */\n\n\t$(\"#team ul li .more\").click(function() {\n\t\t$(this).parent().parent().find('.text').slideToggle();\n\t\tvar spanVal = $(this).text();\n\t\tif(spanVal == 'Read more'){\n\t\t\t$(this).text('Read less');\n\t\t} else {\n\t\t\t$(this).text('Read more');\n\t\t};\n });\n\n $(\"#investors ul li .more\").click(function() {\n\t\t$(this).parent().parent().find('.text').slideToggle();\n\t\tvar spanVal = $(this).text();\n\t\tif(spanVal == 'Read Bio'){\n\t\t\t$(this).text('Close Bio');\n\t\t} else {\n\t\t\t$(this).text('Read Bio');\n\t\t};\n });\n\n/* Scrolling */\n\n\tif (($('#wrap').width()) < 767) {\n\t\t$('.content').pageScroller({\n\t\t navigation: '#nav',\n\t\t scrollOffset: -51 \n\t\t});\n\t} else {\n\t\t$('.content').pageScroller({\n\t\t navigation: '#nav',\n\t\t scrollOffset: -93 \n\t\t});\n\t};" }, { "alpha_fraction": 0.5183179974555969, "alphanum_fraction": 0.5253564119338989, "avg_line_length": 33.203704833984375, "blob_id": "ac3b7a315bea49dae3de76d216d50929566b89ff", "content_id": "3eb6155c17adec7088a45ed48e7f3f3de614ba7a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5541, "license_type": "permissive", "max_line_length": 167, "num_lines": 162, "path": "/servers/demo-scaleout/html/nyc-3/default.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "/* \n$Id: default.js 135745 2013-11-22 23:01:32Z hetal.thakkar $\n(c)2013 The New York Times Company \n*/\n\n/**\n * Places a growl on the page.\n * Generally used to display how many articles user has left.\n *\n * @method growl\n * @public\n *\n * @return {Object}\n */\n(function(root, factory) {\n 'use strict';\n\n // exports for NYT5\n if (typeof define === \"function\" && define.amd) {\n define(['foundation/hosts', 'jquery/nyt', 'auth/mtr', 'foundation/views/page-manager'], function(hosts, $, mtr, pageManager) {\n return factory(hosts, $, mtr, pageManager);\n });\n } else if (typeof root.NYTD === 'object') {\n //NYT4\n NYTD.AuthGrowl = factory(NYTD.Hosts, NYTD.jQuery, NYTD.Meter);\n }\n\n} (this, function(host, $, mtr, pageManager) {\n\n 'use strict';\n\n var growl = {};\n var wwwHost = host.www || host.wwwHost;\n var meterCount;\n\n /**\n * Closes the growl\n * @method close\n * @public\n */\n growl.close = function() {\n if (!growl || !growl.container) return;\n growl.container.fadeOut('slow', function() {\n if (growl && growl.container) {\n growl.container.unbind('click');\n growl.container.remove();\n }\n });\n };\n\n /**\n * Gets the current meter count\n * @method getMeterCount\n * @private\n *\n * @return {String}\n */\n var getMeterCookieCount = function() {\n var count = document.cookie.match(/v=i.([0-9]+)/);\n if (count) return count[1];\n };\n\n /**\n * Gets any keywords or query strings specific to this growl\n * to help on adx targetting\n * @method getData\n * @private\n *\n * @return Object\n */\n var getData = function() {\n var keywords, query;\n var pageType = (typeof define === \"function\" && define.amd) ? 'nyt5' : 'nyt4';\n var element = $('#growlCampaignScript');\n\n var keywords = element.attr('data-keywords');\n keywords = (keywords && keywords.length > 0) ? keywords : '';\n\n var query = element.attr('data-query');\n query = (query && query.length > 0) ? query : '';\n\n return {keywords: keywords, query: query};\n };\n\n /**\n * Makes adx call to get growl creative and adds it to the page if exists\n * @method addGrowl\n * @private\n */\n var addGrowl = function(mtrData){\n var data = getData();\n\n // if we already have a growl open, then we close it\n growl.close();\n\n // don't show growl is either meter or gateway are down\n if (mtrData.gatewayOn === false || mtrData.meterOn === false) { return; }\n\n $.getJSON(wwwHost + '/adx/bin/adxrun.html?v=3&jsonp=?&keywords='+data.keywords+'&page=www.nytimes.com/growl&type=fastscript&positions=Left9&query='+data.query,\n function(data) {\n // if it doesn't have any ads, quit\n if (!data || !data.ads) return;\n // quit if by the time we got the growl creative, the user has already changed page\n // this happens most on ajax applications such as video, nyt5, etc\n if (mtrData.pageCount != getMeterCookieCount()) {\n return;\n }\n\n function setGrowlPosition() {\n var left = $(\"#masthead\").offset().left;\n\n if (left > 0) {\n growl.container.css({left: left});\n } else {\n growl.container.removeAttr(\"style\");\n }\n }\n\n // place the growl creative\n var body = $('body');\n if (data.ads.Left9 && body) {\n // removes previous growl, if there is one\n if (growl.container) {\n growl.container.off('click').remove();\n }\n // TODO: strip out scripts\n body.append(data.ads.Left9.creative);\n // get new container\n growl.container = $(\".nytdGrowlUIContainer\");\n\n if (pageManager) {\n pageManager.listenTo(pageManager, 'nyt:page-resize', setGrowlPosition);\n pageManager.listenTo(pageManager, 'nyt:page-ready', setGrowlPosition);\n }\n\n //bind a click event that will close container\n growl.container.on('click', '.nytdGrowlNotifyCross', function() {\n growl.close();\n });\n // dispatch event notifying the page that growl has loaded\n $(document).trigger('NYTD:AuthGrowlLoaded', {count: mtrData.pageCount});\n // Set timeout to remove grow if cookie changes\n // this is so dynamic applications can implement swipe gestures and \n // not have the growl stick on the page with the wrong count\n }\n if (data.ads.ADX_CLIENTSIDE && body) {\n // display confirmation\n body.append(data.ads.ADX_CLIENTSIDE.creative);\n }\n }\n );\n };\n\n // we can only load the growl after the front end meter has loaded\n // listens for MeterLoaded events\n $(document).on('NYTD:MeterLoaded', function(evt, data) { addGrowl(data); });\n // just in case meter has fired event before this script loaded...\n if (mtr && mtr.loaded) { addGrowl(mtr); }\n\n return growl;\n\n}));\n" }, { "alpha_fraction": 0.6516854166984558, "alphanum_fraction": 0.6685393452644348, "avg_line_length": 12.692307472229004, "blob_id": "52b4100b7f9ca2d85252cd0c229ac038b7599840", "content_id": "1bcf6ede540daec4e4d56c6d011fe5145a88b67f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 178, "license_type": "permissive", "max_line_length": 34, "num_lines": 13, "path": "/servers/waf/main.sh", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\necho '[+] Starting mysql...'\nservice mysql start\n\necho '[+] Starting apache'\nservice apache2 start\n\nwhile true\ndo\n tail -f /var/log/apache2/*.log\n exit 0\ndone\n" }, { "alpha_fraction": 0.7843137383460999, "alphanum_fraction": 0.7843137383460999, "avg_line_length": 16, "blob_id": "52fceeee2c5befd2d2e6f3ecca21d8d10749ff89", "content_id": "922176eb414f77c885e1bbeb3105b8b2814c4a22", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 51, "license_type": "permissive", "max_line_length": 31, "num_lines": 3, "path": "/servers/demo-scaleout/dockerfile", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "FROM nginx:alpine\n\nCOPY html /usr/share/nginx/html\n" }, { "alpha_fraction": 0.7199455499649048, "alphanum_fraction": 0.7199455499649048, "avg_line_length": 78.2035903930664, "blob_id": "08f7b91c49dfe0a1aef963bd64917247615cd276", "content_id": "fb39b9d1bfbcd5bacc80275c6c7e6b293c39aaa1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 13226, "license_type": "permissive", "max_line_length": 131, "num_lines": 167, "path": "/servers/demo-scaleout/html/nyc-5/destinations_select_list.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "function writeRegionCountryDropdown() {\n\tdocument.write(\"<select name=\\\"region\\\" class=\\\"region\\\" onchange=\\\"updateSubRegion(this)\\\">\\n\");\n\tdocument.write(\"<option>Select a Region or Country</option>\\n\");\n\tdocument.write(\"<option>--------------------</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa\\\">Africa</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia\\\">Asia</option>\\n\");\n\tdocument.write(\"<option value=\\\"australia-and-pacific\\\">Australia and Pacific</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda\\\">Caribbean and Bermuda</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america\\\">Central and South America</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe\\\">Europe</option>\\n\");\n\tdocument.write(\"<option value=\\\"middle-east\\\">Middle East</option>\\n\");\n\tdocument.write(\"<option value=\\\"north-america\\\">North America</option>\\n\");\n\tdocument.write(\"<option value=\\\"north-america/united-states\\\">United States</option>\\n\");\n\tdocument.write(\"<option></option>\\n\");\n\tdocument.write(\"<option>--- Countries and Territories ---</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/afghanistan\\\">Afghanistan</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/albania\\\">Albania</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/algeria\\\">Algeria</option>\\n\");\n\tdocument.write(\"<option value=\\\"australia-and-pacific/american-samoa\\\">American Samoa</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/andorra\\\">Andorra</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/anguilla\\\">Anguilla</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/antigua-and-barbuda\\\">Antigua and Barbuda</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/argentina\\\">Argentina</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/aruba\\\">Aruba</option>\\n\");\n\tdocument.write(\"<option value=\\\"australia-and-pacific/australia\\\">Australia</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/austria\\\">Austria</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/bangladesh\\\">Bangladesh</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/barbados\\\">Barbados</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/belgium\\\">Belgium</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/belize\\\">Belize</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/bermuda\\\">Bermuda</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/bhutan\\\">Bhutan</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/bolivia\\\">Bolivia</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/bosnia-and-herzegovina\\\">Bosnia and Herzegovina</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/botswana\\\">Botswana</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/brazil\\\">Brazil</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/britain\\\">Britain</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/bulgaria\\\">Bulgaria</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/cambodia\\\">Cambodia</option>\\n\");\n\tdocument.write(\"<option value=\\\"north-america/canada\\\">Canada</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/cayman-islands\\\">Cayman Islands</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/chile\\\">Chile</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/china\\\">China</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/colombia\\\">Colombia</option>\\n\");\n\tdocument.write(\"<option value=\\\"australia-and-pacific/cook-islands\\\">Cook Islands</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/costa-rica\\\">Costa Rica</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/croatia\\\">Croatia</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/cuba\\\">Cuba</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/curacao\\\">Curacao</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/cyprus\\\">Cyprus</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/czech-republic\\\">Czech Republic</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/denmark\\\">Denmark</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/dominica\\\">Dominica</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/dominican-republic\\\">Dominican Republic</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/ecuador\\\">Ecuador</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/egypt\\\">Egypt</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/el-salvador\\\">El Salvador</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/britain/england\\\">England</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/estonia\\\">Estonia</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/ethiopia\\\">Ethiopia</option>\\n\");\n\tdocument.write(\"<option value=\\\"australia-and-pacific/fiji\\\">Fiji</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/finland\\\">Finland</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/france\\\">France</option>\\n\");\n\tdocument.write(\"<option value=\\\"australia-and-pacific/french-polynesia\\\">French Polynesia</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/georgia\\\">Georgia</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/germany\\\">Germany</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/gibraltar\\\">Gibraltar</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/greece\\\">Greece</option>\\n\");\n\tdocument.write(\"<option value=\\\"north-america/greenland\\\">Greenland</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/grenada\\\">Grenada</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/guadeloupe\\\">Guadeloupe</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/guatemala\\\">Guatemala</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/honduras\\\">Honduras</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/hungary\\\">Hungary</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/iceland\\\">Iceland</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/india\\\">India</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/indonesia\\\">Indonesia</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/ireland\\\">Ireland</option>\\n\");\n\tdocument.write(\"<option value=\\\"middle-east/israel\\\">Israel</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/italy\\\">Italy</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/ivory-coast\\\">Ivory Coast</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/jamaica\\\">Jamaica</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/japan\\\">Japan</option>\\n\");\n\tdocument.write(\"<option value=\\\"middle-east/jordan\\\">Jordan</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/kazakhstan\\\">Kazakhstan</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/kenya\\\">Kenya</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/kyrgyzstan\\\">Kyrgyzstan</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/laos\\\">Laos</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/latvia\\\">Latvia</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/libya\\\">Libya</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/lithuania\\\">Lithuania</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/luxembourg\\\">Luxembourg</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/madagascar\\\">Madagascar</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/malaysia\\\">Malaysia</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/maldives\\\">Maldives</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/mali\\\">Mali</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/malta\\\">Malta</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/martinique\\\">Martinique</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/mauritius\\\">Mauritius</option>\\n\");\n\tdocument.write(\"<option value=\\\"north-america/mexico\\\">Mexico</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/monaco\\\">Monaco</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/mongolia\\\">Mongolia</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/montenegro\\\">Montenegro</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/morocco\\\">Morocco</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/mozambique\\\">Mozambique</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/myanmar\\\">Myanmar</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/namibia\\\">Namibia</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/nepal\\\">Nepal</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/netherlands\\\">Netherlands</option>\\n\");\n\tdocument.write(\"<option value=\\\"australia-and-pacific/new-zealand\\\">New Zealand</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/nicaragua\\\">Nicaragua</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/niger\\\">Niger</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/britain/northern-ireland\\\">Northern Ireland</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/norway\\\">Norway</option>\\n\");\n\tdocument.write(\"<option value=\\\"middle-east/oman\\\">Oman</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/panama\\\">Panama</option>\\n\");\n\tdocument.write(\"<option value=\\\"australia-and-pacific/papua-new-guinea\\\">Papua New Guinea</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/peru\\\">Peru</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/philippines\\\">Philippines</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/poland\\\">Poland</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/portugal\\\">Portugal</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/puerto-rico\\\">Puerto Rico</option>\\n\");\n\tdocument.write(\"<option value=\\\"middle-east/qatar\\\">Qatar</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/romania\\\">Romania</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/russia\\\">Russia</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/rwanda\\\">Rwanda</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/saba\\\">Saba</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/britain/scotland\\\">Scotland</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/senegal\\\">Senegal</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/serbia\\\">Serbia</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/seychelles\\\">Seychelles</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/singapore\\\">Singapore</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/slovakia\\\">Slovakia</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/slovenia\\\">Slovenia</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/south-africa\\\">South Africa</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/south-korea\\\">South Korea</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/spain\\\">Spain</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/sri-lanka\\\">Sri Lanka</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/st-barthelemy\\\">St. Barthelemy</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/st-kitts-and-nevis\\\">St. Kitts and Nevis</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/st-lucia\\\">St. Lucia</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/st-vincent-and-the-grenadines\\\">St. Vincent and the Grenadines</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/suriname\\\">Suriname</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/sweden\\\">Sweden</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/switzerland\\\">Switzerland</option>\\n\");\n\tdocument.write(\"<option value=\\\"middle-east/syria\\\">Syria</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/taiwan\\\">Taiwan</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/tanzania\\\">Tanzania</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/thailand\\\">Thailand</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/the-bahamas\\\">The Bahamas</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/trinidad-and-tobago\\\">Trinidad and Tobago</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/tunisia\\\">Tunisia</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/turkey\\\">Turkey</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/turks-and-caicos\\\">Turks and Caicos</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/uganda\\\">Uganda</option>\\n\");\n\tdocument.write(\"<option value=\\\"middle-east/united-arab-emirates\\\">United Arab Emirates</option>\\n\");\n\tdocument.write(\"<option value=\\\"north-america/united-states\\\">United States</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/uruguay\\\">Uruguay</option>\\n\");\n\tdocument.write(\"<option value=\\\"australia-and-pacific/vanuatu\\\">Vanuatu</option>\\n\");\n\tdocument.write(\"<option value=\\\"central-and-south-america/venezuela\\\">Venezuela</option>\\n\");\n\tdocument.write(\"<option value=\\\"asia/vietnam\\\">Vietnam</option>\\n\");\n\tdocument.write(\"<option value=\\\"caribbean-and-bermuda/virgin-islands\\\">Virgin Islands</option>\\n\");\n\tdocument.write(\"<option value=\\\"europe/britain/wales\\\">Wales</option>\\n\");\n\tdocument.write(\"<option value=\\\"middle-east/yemen\\\">Yemen</option>\\n\");\n\tdocument.write(\"<option value=\\\"africa/zimbabwe\\\">Zimbabwe</option>\\n\");\n\tdocument.write(\"</select>\\n\");\n}" }, { "alpha_fraction": 0.5852145552635193, "alphanum_fraction": 0.5893503427505493, "avg_line_length": 34.175758361816406, "blob_id": "4cd875c4c85318daf3359242f8607683b19c1379", "content_id": "b4a3c1601396a9e814b71e95dfbdd960129ced48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5803, "license_type": "permissive", "max_line_length": 659, "num_lines": 165, "path": "/servers/demo-scaleout/html/jquery.sharebox.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "jQuery(document).ready(function(){\n\tSharebox.init();\n});\n\nvar Sharebox = {\n\t\"settings\": [\n\t {'id': '#share_link', 'box': '#sharebox', 'closer': '#shareclosebox', 'offset': [ -273, 29 ], 'sendlink':'#send_link'},\n \t\t\t\t\t\t {'id': '#embed_link', 'box': '#embedbox', 'closer': '#embedclosebox', 'offset': [ -278, 29 ], 'sendlink': null}\n\t\t\t\t\t\t ],\n\n\t\"init\":function() {\n\t\tvar self = this;\n\t\tself.inject_share_box();\n\t\tself.init_link_handlers();\n\t\tjQuery.each(this.settings, function(i, value) {\n\t\t\tself.attach_handler(value);\n\t\t});\n\t\tvar sendlink = jQuery(\"#send_link\");\n\t\tjQuery(sendlink).removeAttr('onclick');\n\t\t\n\t\tjQuery(sendlink).click(function(){\n\t\t//\tself.send_to_friend();\n\t\t//\treturn false;\n\t\t}).css('opacity', '0.5');\n\t},\n\t\"inject_share_box\": function() {\n\t var self = this;\n\t if(jQuery('#sharebox')) {jQuery('#sharebox').remove();}\n\t if(jQuery.browser.msie && jQuery.browser.version > 7) {\n\t jQuery('head').prepend('<link rel=\"stylesheet\" type=\"text/css\" href=\"shared/style_ie.css\"');\n }\n jQuery('body').append(self.create_template());\n\t},\n\t\"attach_handler\":function (setting) {\n\t\tvar self = this;\n\t\tif(!jQuery(setting.id)) {return};\n\t\tvar box = jQuery(setting.box);\n\n\t\tjQuery(setting.id).click(function() {\n\t\t jQuery('body').append(box.remove());\n\n\t\t\tbox.clonePosition(this, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsetWidth: false,\n\t \t\t\t\t\t\t\t\t\t\t\t\t\tsetHeight: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toffsetTop:setting.offset[1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toffsetLeft:setting.offset[0]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\n\t\t\tif(!box.css('z-index')) {\n\t\t\t\tbox.css('z-index', 1);\n\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\tbox.show();\n\t\t\t\n\n jQuery(setting.closer).unbind().click(function() {\n box.hide();\n return false;\n });\n\n\t\t\treturn false;\n\t\t})\n\t},\n\n\t\"send_to_friend\": function() {\n\t\tvar fromaddr = jQuery('#sharesender').val();\n\t\tvar toaddr = jQuery('#sharerecipiants').val();\n\t\tvar link = window.location.href;\n\t\tvar title = document.title;\n\t\tvar templates = 'gallery';\n\n\t\tthis.send_email({'email': toaddr, 'from':fromaddr, 'link': link, 'template':templates, 'title':title});\n\t},\n\t\"send_email\": function(data) {\n\t\tjQuery.post('shared/send_to_a_friend/send.php', data, function(data){jQuery('#sharebox').hide();});\n\t},\n\t\"init_link_handlers\":function() {\n\t\tjQuery('#sharelinks li a[onclick]').each(function(){\n\t\t\tjQuery(this).removeAttr('onclick');\n\t\t});\n\t\tvar self = this;\n\t\tjQuery('#sharelinks a').each(function() {\n\t\t\tjQuery(this).click(function() {\n\t\t\t\tself.log_click(jQuery(this).children('strong')[0].innerHTML, this.href);\n\t\t\t})\n\t\t})\n\t},\n\t\"log_click\":function(type, url) {\n\t\t\tjQuery.get('shared/shared.php?type=' + type + '&url=' + url);\n\t},\n\n\t\"services\": [\n\t {\n \t 'service':'digg',\n \t\t'url' : 'http://digg.com/submit?title={title}&amp;url={url}',\n \t\t'alt' : 'Digg this',\n \t\t'name' : 'Digg'\n \t},\n \t{\n \t 'service':'delicious',\n \t\t'url' : 'http://del.icio.us/post?t&amp;v=4&amp;noui&amp;jump=close&amp;title={title}&amp;url={url}',\n \t\t'alt' : 'bookmark on delicious',\n \t\t'name' : 'Delicious'\n \t},\n \t{\n \t 'service':'stumbleupon',\n \t\t'url' : 'http://www.stumbleupon.com/submit?title={title}&amp;url={url}',\n \t\t'alt' : 'stumbleupon',\n \t\t'name' : 'StumbleUpon'\n \t},\n \t{\n \t 'service':'technorati',\n \t\t'url' : 'http://technorati.com/faves?add={url}',\n \t\t'alt' : 'technorati',\n \t\t'name' : 'Technorati'\n \t},\n \t{\n \t 'service':'yahoo',\n \t\t'url' : 'http://bookmarks.yahoo.com/toolbar/savebm?t={title}&amp;u={url}',\n \t\t'alt' : 'yahoo',\n \t\t'name' : 'Yahoo'\n \t},\n \t{\n \t 'service':'facebook',\n \t 'url' : 'http://www.facebook.com/sharer.php?u={url}&amp;t={title}',\n \t\t'alt' : 'facebook',\n \t\t'name' : 'Facebook'\n \t},\n \t{\n \t 'service': 'twitter',\n \t 'url' : '/tiny_url_proxy.php?loc=' + escape(window.location.href) + '&amp;title=' + escape(document.title) + '&amp;mode=twitter',\n \t\t'alt' : 'send to twitter',\n \t\t'name' : 'Twitter'\n \t}\n ],\n \"template\":\"<div id=\\'sharebox\\' style=\\'display:none;\\'><a id=\\'shareclosebox\\' href=\\'javascript:void(0)\\'></a><div id=\\'sharetoptext\\'><span class=\\'sharetext sharefloatleft\\'><strong>SHARE</strong></span><br style=\\'clear:both;\\'/></div><div id=\\'sharelinks\\'>{links}</div><br /><br style=\\'clear:both;\\'/></div>\",\n \"email\":\"<br /><div id=\\'shareemail\\'><span class=\\'sharetext\\'><strong>E-MAIL</strong></span><br /><span class=\\'sharepad sharedescription\\'><label for=\\'sharesender\\'><strong>Your name</strong></label></span><input name=\\'sender\\' id=\\'sharesender\\' class=\\'shareinput\\' /><span class=\\'sharepad sharedescription\\'><label for=\\'sharerecipiants\\'><strong>Recipient\\'s e-mail address</strong><span class=\\'shareitalics\\'>(separate addresses with commas)</span></label></span><input name=\\'recipients\\' id=\\'sharerecipiants\\' class=\\'shareinput\\' /></div><span id=\\'sharesend\\'><a id='send_link' href=\\'javascript:void(0)\\'><strong>SEND</strong></a></span>\",\n \"make_link\":function(object) {\n return \"<a href=\\\"\" + this.build_share_url(object.url) + \"\\\"><img src=\\\"shared/\" + object.service + \"_icon_16.png\\\" alt=\\\"\" + object.alt + \"\\\"><strong>\" + object.name + \"</strong></a>\";\n },\n \"twitter_message\":function() {\n var tiny_url = get_tiny_url();\n return document.title + ': ' + tiny_url;\n },\n \"build_share_url\": function(url){\n var replacements = {'{url}': window.location.href, '{title}': document.title};\n jQuery.each(replacements, function(match, replace) {\n url = url.replace(match, escape(replace));\n });\n return url;\n },\n \"image_path\": function(name) {\n return \"shared/\" + name + \"_icon_16.png\";\n },\n \"create_template\": function() {\n var links = [\"<ul>\"];\n var self = this;\n jQuery.each(self.services, function(){\n links.push('<li>' + self.make_link(this) + '</li>');\n })\n links.push('</ul>');\n return self.template.replace('{links}', links.join(''));\n }\n\n}" }, { "alpha_fraction": 0.6246483325958252, "alphanum_fraction": 0.6296048164367676, "avg_line_length": 29.100807189941406, "blob_id": "be030c8fda3657316d3b5d655a4c88718764b040", "content_id": "b6e615a38333e8a1279b98c3ab4008a0baa1f8b7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7465, "license_type": "permissive", "max_line_length": 84, "num_lines": 248, "path": "/servers/demo-scaleout/html/nyc-5/travel_v1.1.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "/*\n$Id: travel_v1.1.js 44254 2010-08-30 05:07:18Z sowmya_m04 $\n*/\n// set sub content group if it exists\nvar subcontentGroup = getMetaTag(\"WT.cg_s\");\nif (subcontentGroup == \"\") {\n if(/\\/travel\\/escapes\\//.test(nyt_path)) {\n subcontentGroup = \"Escapes\";\n } else if (/\\/travel\\/tmagazine\\//.test(nyt_url)) {\n subcontentGroup = \"T Travel\";\n }\n}\naddMetaTag(\"WT.cg_s\", subcontentGroup);\n\n// set page type\nvar pageType = getMetaTag(\"WT.z_gpt\");\nvar pageSubType = getMetaTag(\"WT.z_gpst\");\nvar pageSubSubType = getMetaTag(\"WT.z_gpsst\");\nvar pageSubSubSubType = getMetaTag(\"WT.z_gpssst\");\nvar metaTom = getMetaTag(\"tom\");\nvar metaCol = getMetaTag(\"col\");\n\nif(pageType == \"Article\" && pageSubType == \"News\") {\n if (metaCol != \"\") {\n pageSubSubType = metaCol;\n } else if (/\\/travel\\/escapes\\//.test(nyt_path)) {\n pageSubSubType = \"Escapes\";\n } else if (/\\/travel\\/tmagazine\\//.test(nyt_path)) {\n pageSubSubType = \"T Travel\";\n }\n}\n\nif (pageType == \"\" || pageType == \"Other\") {\n if(/^http:\\/\\/travel\\.nytimes\\.com\\/$/.test(nyt_url)\n || /^\\/pages\\/travel\\/index.html$/.test(nyt_path)) {\n pageType = \"Section Front\";\n } else if(/^\\/pages\\/travel\\/escapes\\/$/.test(nyt_path)\n || /^\\/pages\\/travel\\/escapes\\/index.html/.test(nyt_path)) {\n pageType = \"Section Front\";\n pageSubType = \"SubSection Front\";\n } else if(/^\\/pages\\/travel\\/tmagazine\\/$/.test(nyt_path)\n || /^\\/pages\\/travel\\/tmagazine\\/index.html/.test(nyt_path)) {\n pageType = \"Section Front\";\n pageSubType = \"SubSection Front\";\n } else if(/\\/frugal-traveler\\//.test(nyt_path)) {\n pageType = \"Topic\";\n pageSubType = \"Series\";\n } else if(/\\/overview.html$/.test(nyt_path)) {\n pageType = \"Topic\";\n pageSubType = \"Travel Guide\";\n pageSubSubType = \"Overview\";\n } else if(/\\/overview-detail.html$/.test(nyt_path)) {\n pageType = \"Topic\";\n pageSubType = \"Travel Guide\";\n pageSubSubType = \"Overview\";\n } else if(/\\/hotels.html$/.test(nyt_path)) {\n pageType = \"Topic\";\n pageSubType = \"Travel Guide\";\n pageSubSubType = \"Where to Stay\";\n pageSubSubSubType = \"Suggestions\";\n } else if(/\\/hotel-detail.html$/.test(nyt_path)) {\n pageType = \"Topic\";\n pageSubType = \"Venue Detail\";\n pageSubSubType = \"Where to Stay\";\n pageSubSubSubType = \"Review\";\n } else if(/\\/hotel-listings.html$/.test(nyt_path)) {\n pageType = \"Topic\";\n pageSubType = \"Travel Guide\";\n pageSubSubType = \"Where to Stay\";\n pageSubSubSubType = \"Listings\";\n } else if(/\\/restaurants.html$/.test(nyt_path)) {\n pageType = \"Topic\";\n pageSubType = \"Travel Guide\";\n pageSubSubType = \"Where to Eat\";\n pageSubSubSubType = \"Suggestions\";\n } else if(/\\/restaurant-detail.html$/.test(nyt_path)) {\n pageType = \"Topic\";\n pageSubType = \"Venue Detail\";\n pageSubSubType = \"Where to Eat\";\n pageSubSubSubType = \"Review\";\n } else if(/\\/restaurant-listings.html$/.test(nyt_path)) {\n pageType = \"Topic\";\n pageSubType = \"Travel Guide\";\n pageSubSubType = \"Where to Eat\";\n pageSubSubSubType = \"Listings\";\n } else if(/\\/attractions.html$/.test(nyt_path)) {\n pageType = \"Topic\";\n pageSubType = \"Travel Guide\";\n pageSubSubType = \"What to Do\";\n pageSubSubSubType = \"Suggestions\";\n } else if(/\\/attraction-detail.html$/.test(nyt_path)) {\n pageType = \"Topic\";\n pageSubType = \"Venue Detail\";\n pageSubSubType = \"What to Do\";\n pageSubSubSubType = \"Review\";\n } else if(/\\/attraction-listings.html$/.test(nyt_path)) {\n pageType = \"Topic\";\n pageSubType = \"Travel Guide\";\n pageSubSubType = \"What to Do\";\n var listingType = getQueryParameter(\"type\");\n\t if (listingType != \"\") {\n\t if (listingType == \"Attraction\") {\n pageSubSubSubType = \"Listings\";\n } else {\n pageSubSubSubType = listingType;\n }\n }\n } else if(/\\/when-to-go.html$/.test(nyt_path)) {\n pageType = \"Topic\";\n pageSubType = \"Travel Guide\";\n pageSubSubType = \"When to Go\";\n } else if(/\\/where-to-go.html$/.test(nyt_path)) {\n pageType = \"Topic\";\n pageSubType = \"Travel Guide\";\n pageSubSubType = \"Where to Go\";\n } else if(/\\/maps.html/.test(nyt_path)) {\n pageType = \"Topic\";\n pageSubType = \"Travel Guide\";\n\tpageSubSubType = \"Maps\";\n } else if (/\\/frommers\\//.test(nyt_path)) {\n pageType = \"Article\";\n pageSubType = \"Travel Guide\";\n } else if(/\\/slideshow\\//.test(nyt_path)) {\n pageType = \"Multimedia\";\n pageSubType = \"Slideshow\";\n } else if(/\\/travsearch.html/.test(nyt_path)) {\n pageType = \"Search\";\n pageSubType = \"Results\";\n } else {\n pageType = \"Other\";\n }\n}\noverwriteMetaTag(\"WT.z_gpt\", pageType);\naddMetaTag(\"WT.z_gpst\", pageSubType);\naddMetaTag(\"WT.z_gpsst\", pageSubSubType);\naddMetaTag(\"WT.z_gpssst\", pageSubSubSubType);\n\n// set partner page\nvar partnerPage;\nif (/\\/frommers\\//.test(nyt_path)) {\n partnerPage = \"Frommers\";\n addMetaTag(\"WT.z_pc\", partnerPage);\n}\n\n// get location specific information\nvar wt_region;\nvar wt_country;\nvar wt_state;\nvar wt_city;\nvar wt_destination;\nif ((pageType == \"Topic\") || (pageType == \"Article\" && partnerPage == \"Frommers\")) {\n var startRE = /\\/travel\\/guides\\//g;\n var endRE = /\\/[A-Za-z0-9\\-_]+\\.html/g;\n var tempArray0 = startRE.exec(nyt_path);\n var tempArray1 = endRE.exec(nyt_path);\n if (tempArray0 != null && tempArray1 != null) {\n var locationString = nyt_path.substring(startRE.lastIndex, tempArray1.index);\n var locationArray = locationString.split(\"/\");\n wt_region = locationArray[0];\n wt_country = locationArray[1];\n wt_state = locationArray[2];\n wt_city = locationArray[3];\n }\n}\n\n// set wt_region\nif (wt_region != undefined) {\n addMetaTag(\"WT.z_tRegion\", wt_region);\n}\n\n// set wt_country\nif (wt_country != undefined) {\n wt_destination = wt_country;\n //addMetaTag(\"WT.z_tCountry\", wt_country);\n}\n\n// set wt_state\nif (wt_state != undefined) {\n wt_destination = wt_state;\n //addMetaTag(\"WT.z_tState\", wt_state);\n}\n\n// set wt_city\nif (wt_city != undefined) {\n wt_destination = wt_city;\n //addMetaTag(\"WT.z_tCity\", wt_city;\n}\n\n// set wt_destination\nif (wt_destination != undefined) {\n addMetaTag(\"WT.z_tDest\", wt_destination);\n}\n\n// set refer\nvar refer = getQueryParameter(\"refer\");\nif (refer != \"\") {\n addMetaTag(\"WT.z_gref\", refer);\n}\n\n// set critics pick\n\n// set venue type\nif (/\\/hotel-detail.html$/.test(nyt_path)) {\n addMetaTag(\"WT.z_tvt\", \"Hotel\");\n} else if (/\\/restaurant-detail.html$/.test(nyt_path)) {\n addMetaTag(\"WT.z_tvt\", \"Restaurant\");\n} else if (/\\/attraction-detail.html$/.test(nyt_path)) {\n addMetaTag(\"WT.z_tvt\", \"Attraction\");\n}\n\n// set venue name\nif (/\\/hotel-detail.html$/.test(nyt_path)\n || /\\/restaurant-detail.html$/.test(nyt_path)\n || /\\/attraction-detail.html$/.test(nyt_path)) {\n var venueName = \"\";\n var docTitle = document.title;\n if (docTitle != undefined) {\n var endIndex = docTitle.indexOf(\" - \");\n venueName = docTitle.substring(0, endIndex);\n }\n addMetaTag(\"WT.z_tvn\", venueName);\n}\n// set venue id\nvar vid = getQueryParameter(\"vid\");\nif (vid != \"\") {\n addMetaTag(\"WT.z_tvid\", vid);\n}\n\n// set activity\n\n// set search type\n\n// for travel search only\nvar searchResults;\nvar wt_tross = \"\";\nvar wt_tross_r = \"\";\n\nif (pageType == \"Search\" && pageSubType == \"Results\") {\n wt_tross = getQueryParameter(\"term\");\n searchResults = document.getElementById(\"noResults\");\n if (null == searchResults) {\n wt_tross_r = \"1\";\n } else {\n wt_tross_r = \"0\";\n }\n}\naddMetaTag(\"WT.z_tross\", wt_tross);\naddMetaTag(\"WT.z_tross_r\", wt_tross_r);\n" }, { "alpha_fraction": 0.49563294649124146, "alphanum_fraction": 0.5046987533569336, "avg_line_length": 33.65134048461914, "blob_id": "681d1742327ec97be35a8a10925b086e2981ea4d", "content_id": "d88eba58991bfc699c5d2eff53fdeccb04f52bbd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 9045, "license_type": "permissive", "max_line_length": 125, "num_lines": 261, "path": "/servers/demo-scaleout/html/nyc-3/latestNewsModule.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "if (window['console'] === undefined) {\n window.console = { log: function(){} };\n}\n\nvar NYTD = window.NYTD|| {};\nNYTD.LatestNews = NYTD.LatestNews || {};\nNYTD.LatestNews.Updates = NYTD.LatestNews.Updates || false;\n\nNYTD.LatestNews.App = {\n init: function() {\n this.Sources = { \"The New York Times\" : { kicker: \"NYTimes\", klass: \"nyt\" },\n \"International Herald Tribune\" : { kicker: \"IHT\", klass: \"iht\" },\n \"AP\" : { kicker: \"AP\", klass: \"ap\" },\n \"Reuters\" : { kicker: \"Reuters\", klass: \"reuters\" } };\n\n this.view = 'all';\n this.module = $('moduleLatestNews');\n this.highlightColor = '#fffef0';\n this.timeForUpdates = 60;\n\n if (this.module) {\n\n var d = new Date();\n var i = this;\n var p = 0;\n\n this.module.removeClassName('latestNewsModuleStatic');\n this.est = (d.getTimezoneOffset()/60)-4;\n this.updateTimesStamps();\n this.updateSourceName();\n this.setupEvents();\n\n new PeriodicalExecuter(function(pe) {\n i.updateTimesStamps();\n if (NYTD.LatestNews.Updates && NYTD.LatestNews.Updates.hasUpdates) {\n if (p++%2) { /* skip every 2nd call to space polling */\n i.requestItems();\n }\n }\n }, (this.timeForUpdates/2));\n }\n },\n\n setupEvents: function() {\n var instance = this;\n this.module.select('li').each(function(li){\n Event.observe(li, 'click', instance.selectSource.bindAsEventListener(this));\n });\n },\n\n selectSource: function(e) {\n /* Avoiding addition of custom classes in this case since choices limited to 2 */\n var target;\n if (!e) var e = window.event;\n if (e.target) target = e.target;\n else if (e.srcElement) target = e.srcElement;\n if (target.nodeType == 3) target = target.parentNode;\n var li = (target.nodeName==\"LI\") ? target : target.parentNode;\n var app = NYTD.LatestNews.App;\n\n // Update Source links\n app.module.select('li').each(function(item) {\n if (li===item) {\n item.addClassName('selected');\n } else {\n item.removeClassName('selected');\n }\n });\n app.updateView(app.module.select('div.story'));\n },\n\n getCurrentSource: function() {\n var first = this.module.select('li.first');\n var unDef;\n if (first!=unDef) {\n this.src = first[0].hasClassName('selected') ? 'all' : 'nyt';\n return this.src;\n }\n return 'all';\n },\n\n updateView: function(stories, hasEffects) {\n var hasEffects = hasEffects || false;\n var src = this.getCurrentSource();\n var highlight = this.highlightColor;\n\n this.updateTimesStamps();\n\n // Display appropiately sourced stories\n stories.each(function(story) {\n\n var storySrc = story.select('.byline')[0].title;\n var showStory = (src=='all' || (src=='nyt' && storySrc=='The New York Times')) ? true : false;\n\n if (showStory) {\n if (hasEffects) {\n new Effect.Appear(story, { duration: 2, queue: 'end', afterFinish: function(e){\n new Effect.Highlight(story, { startcolor: highlight, endcolor: '#ffffff', restorecolor: '#ffffff' });\n } });\n } else {\n story.show();\n }\n } else {\n story.hide();\n }\n });\n },\n\n requestItems: function() {\n var url = NYTD.LatestNews.Updates.location + \"?\" + this.uncacheParam();\n var instance = this;\n new Ajax.Request(url, {\n method: 'get',\n onSuccess: function(response) {\n instance.insertItems(response.responseText);\n },\n onException: function(req,exception) {\n console.log('onException: Request over', req, exception);\n }\n });\n },\n\n insertItems: function(html) {\n var tsList = this.module.select('span.timestamp');\n var lastTime = tsList[0].readAttribute('title');\n var tmp = document.createElement('div');\n tmp.innerHTML = html; // Hold, but DOM accessible\n var items = $(tmp).select('div.story'); // Wrap in $ for IE\n var newStories = [];\n var content = this.module.select('div.scrollContent')[0];\n\n // Push new updates to top\n for (var i=items.length-1; i>=0; i--) {\n\n var story = items[i];\n var created = story.select('span.timestamp')[0].title;\n\n if (story!=undefined && this.isNewerThan(created, lastTime)) {\n\n // Prep story\n story.style.display = 'none';\n story.style.backgroundColor = this.highlightColor;\n\n var source = story.select('span.byline')[0];\n if (this.Sources[source.title]!=undefined) {\n source.innerHTML = this.Sources[source.title].kicker;\n }\n\n // Insert story\n newStories.push(story);\n content.insert({ top: story });\n\n // Remove last Story to maintain the same number\n var storyList = content.select('div.story');\n storyList[storyList.length-1].remove();\n }\n }\n\n if (newStories.length>0) {\n this.updateView(newStories, true);\n }\n },\n\n drawItem: function(item) {\n if (item==undefined) { return ''; };\n\n var story = document.createElement('div');\n var source = this.getSource(item.source);\n var row;\n\n story.addClassName('story');\n story.addClassName('singleRuleBottom');\n story.style.display = 'none';\n\n row = ' <span class=\"item\">';\n row += ' <h6 class=\"timestamp\" title=\"' + item.created + '\">' +this.readableTimestamp(item.created)+ '</h6>';\n row += ' <h6 class=\"byline ' + source.klass + '\">' + source.kicker + '</h6>';\n row += ' </span>';\n row += ' <h5><a href=\"' +item.url+ '\">' +item.headline+ '</a></h5>';\n\n story.innerHTML = row;\n return story;\n },\n\n getSource: function(source){\n var unDef;\n if (this.Sources[source]!=unDef) {\n return this.Sources[source];\n }\n return { kicker: \"\", klass: \"\" };\n },\n\n updateTimesStamps: function () {\n var instance = this;\n instance.module.select('span.timestamp').each(function(span){\n span.innerHTML = instance.readableTimestamp(span.title) || span.title;\n });\n },\n\n updateSourceName: function () {\n var instance = this;\n instance.module.select('span.byline').each(function(span){\n if (instance.Sources[span.title]!=undefined) {\n span.innerHTML = instance.Sources[span.title].kicker;\n }\n });\n },\n\n readableTimestamp: function(timestamp) {\n var tsFull = this.timestampToDate(timestamp) || 0;\n var now = new Date();\n now.setHours(now.getHours() + this.est);\n var dif = (now.getTime() - tsFull.getTime()) / 1000; // ms to s\n\n switch(true) {\n case (dif < 60):\n tsText = \"Moments ago\";\n break;\n case (dif < 120):\n tsText = \"1 minute ago\";\n break;\n case (dif < 3600):\n tsText = Math.round(dif/60)+\" minutes ago\";\n break;\n default:\n var tsHour = (tsFull.getHours()%12);\n var tsMin = tsFull.getMinutes();\n tsMin = (tsMin<10) ? \"0\" + tsMin : tsMin;\n tsHour = (tsHour==0) ? 12 : tsHour;\n tsText = tsHour +\":\"+ tsMin + \" \" + ((tsFull.getHours()>11) ? \"PM\" : \"AM\") + \" ET\";\n }\n return tsText;\n },\n\n timestampToDate: function(ts) {\n if (ts!=undefined) {\n // Example format: 2010-03-09T13:46:38-05:00\n return new Date(ts.substr(0, 19).replace(/-/g,'/').replace(/T/g,' '));\n } else {\n return new Date();\n }\n },\n\n isNewerThan: function(firstDate, secondDate) {\n if(!secondDate) return false;\n var firstDate = this.timestampToDate(firstDate) || 0;\n var secondDate = this.timestampToDate(secondDate) || 0;\n if (firstDate.getTime() > secondDate.getTime()) {\n return true;\n }\n return false;\n },\n\n uncacheParam: function() {\n return String((new Date()).getTime()).substring(0,10); // to nearest second\n }\n};\n\nEvent.observe(window, \"load\", function () {\n NYTD.LatestNews.App.init(); // magic\n});\n\n" }, { "alpha_fraction": 0.679355800151825, "alphanum_fraction": 0.6910688281059265, "avg_line_length": 27.45833396911621, "blob_id": "51ee2ac233ef6dfeb7df8ac75974a9f4b54e2c08", "content_id": "d552ead6d78fe2a9c9ed4041c2167263aad9dea2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2049, "license_type": "permissive", "max_line_length": 89, "num_lines": 72, "path": "/servers/demo-scaleout/html/nyc-3/tabset.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "/* $Id: tabset.js 103281 2012-07-11 16:14:19Z konige $\n * The tool to use if you need a set of tabs.\n *\n * USE: NYTD.TabSet(\"idOfTabSetContainerDiv\");\n */\n\nNYTD.TabSet = function( target ) {\n\tfunction root() {\n\t\treturn $(target);\n\t}\n\n\tfunction subSelect(queryString) {\n\t\treturn root().select(queryString);\n\t}\n\n\tfunction activateTabLink(event) {\n\t\tblankTabsAndContent();\n\t\tselectTab(event.findElement('li'));\n\t\tevent.element().blur();\n\t\tevent.stop();\n\t}\n\n\tfunction blankTabsAndContent() {\n\t\tapi.getTabs().invoke(\"removeClassName\", \"selected\");\n\t\tapi.getTabContent().invoke(\"removeClassName\", \"active\");\n\t}\n\n\tfunction selectTab(tabNode) {\n\t\tif (tabNode) {\n\t\t var index = api.getTabs().indexOf(tabNode);\n\t\t\tactivateTab(tabNode, api.getTabContent()[index]);\n\t\t}\n\t}\n\n\tfunction activateTab(tabNode, contentNode) {\n\t\tif (tabNode && contentNode) {\n\t\t\ttabNode.addClassName(\"selected\");\n\t\t\tcontentNode.addClassName(\"active\");\n\t\t}\n\t}\n\n\tvar api = {\n\t\tsubSelect: function(queryString) { return subSelect(queryString); },\n\t\tgetRoot: function() { return root() },\n\t\tselectedTabNotFound: function() { return subSelect(\"ul.tabs li.selected\").length < 1},\n\t\tactiveContentNotFound: function() { return subSelect(\".tabContent.active\").length < 1},\n\t\tgetTabs: function() { return subSelect(\"ul.tabs li\")},\n\t\tgetTabLinks: function() { return subSelect(\"ul.tabs li a\")},\n\t\tgetTabContent: function() { return subSelect(\".tabContent\")},\n\t\tactivateTab: function(tabNode, contentNode) {activateTab(tabNode, contentNode);},\n\t\tactivateTabLinks: function() {return activateTabLink;}\n\t};\n\n\tapi.getTabs().invoke(\"observe\", \"click\", activateTabLink); \n\tif(api.selectedTabNotFound() || api.activeContentNotFound()) {\n\t\tblankTabsAndContent();\n\t\tactivateTab(api.getTabs()[0], api.getTabContent()[0]);\n\t\t}\n\treturn api;\n};\n\n// Automatically tab-i-fy nodes with a class of tabAutoLoad\ndocument.observe(\"dom:loaded\", function() {\n\t$$(\".tabAutoLoad\").each(function(tabSet){\n\t\tnew NYTD.TabSet(tabSet);\n\t});\n});\n\n// Compatibility\nif(!($$(\"body#home\"))) {\n var Accordian = NYTD.TabSet;\n}\n" }, { "alpha_fraction": 0.5880343914031982, "alphanum_fraction": 0.5921564102172852, "avg_line_length": 40.21844482421875, "blob_id": "85fc3f6d487ea874f6f22df966e0f1656e40932b", "content_id": "1e29a267df952b0e0b9b0d122c1abc04392edf9e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 8491, "license_type": "permissive", "max_line_length": 152, "num_lines": 206, "path": "/servers/demo-scaleout/html/nyc-3/autosuggest.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "/* \n$Id: autosuggest.js 122664 2013-03-12 19:55:23Z surya.sanagavarapu $\nAutosuggest from a json feed\nRequires NYTD.jQuery & a config\n(c) 2012 The New York Times Company\n*/\n\nvar NYTD = NYTD || {};\nNYTD.Search = NYTD.Search || {};\n\nNYTD.Search.Suggest = (function(jQuery) {\n var $queryResults = jQuery(\".autoSuggestQueryResults\");\n \n function init() {\n initSearchBoxes();\n }\n\n function initSearchBoxes() {\n var searchBoxObject = NYTD.Search.Config.SearchBoxes; //get searchboxes from config\n for (var key in searchBoxObject) { //set up each\n if (searchBoxObject.hasOwnProperty(key)) {\n setEventHandlers(searchBoxObject[key]);\n setSearchPrompt(searchBoxObject[key]);\n }\n }\n }\n\n function setEventHandlers(configData) { //UI interactions\n var searchBoxLocation = configData.DOMselector;\n jQuery(searchBoxLocation)\n .on(\"focus\",\".autoSuggestQuery\",clearSearchField)\n .on(\"keydown\",\".autoSuggestQuery\",function(event) {navigateItems(event,searchBoxLocation);})\n .on(\"keyup\",\".autoSuggestQuery\",function(event) {typeSearch(event,this,configData);})\n .on(\"focusout\",\".autoSuggestQuery\",hideSuggestions)\n //.on(\"mouseover\",\".autoSuggestQueryResults li\",function(event) {browse(this,searchBoxLocation);})\n\n // provide hooks for user event handlers\n .on(\"keydown\", configData.keydownCallback || $.noop)\n .on(\"click\", configData.clickCallback || $.noop)\n .on(\"submit\", \"form\", configData.submitCallback || $.noop);\n }\n \n function browse(item,searchBoxLocation) { //browse an item in the dropdown\n var $searchField = jQuery(searchBoxLocation).find(\".autoSuggestQuery\");\n jQuery(\".autoSuggestQueryResults\").find(\"li\").removeClass(\"selectedItem\");\n jQuery(item).addClass(\"selectedItem\");\n browsedQuery = jQuery(item).find(\"a\").data(\"query\"); //get query from markup\n if (browsedQuery) {\n $searchField.val(browsedQuery);\n }\n }\n\n function navigateItems(event,searchBoxLocation) { //user types the \"up\" and \"down\" keys to navigate items in the dropdown\n var $itemsList = jQuery(searchBoxLocation).find(\".autoSuggestQueryResults\"),\n $searchField = jQuery(searchBoxLocation).find(\".autoSuggestQuery\"),\n $selectedItem = $itemsList.find(\"li\").hasClass(\"selectedItem\"),\n browsedQuery,\n itemToSelect;\n if (event.keyCode == 40) { //\"down\"\n if ($selectedItem) { //an element is already selected\n if ($itemsList.find(\"li:last-child\").hasClass(\"selectedItem\")) { //the last item is selected, so select the first in the list\n itemToSelect = $itemsList.find(\"li:first-child\");\n }\n else { //otherwise just choose the next item\n itemToSelect = $itemsList.find(\"li.selectedItem\").next(\"li\");\n }\n }\n else { //none is selected, so choose the first\n itemToSelect = $itemsList.find(\"li:first-child\");\n }\n browse(itemToSelect,searchBoxLocation);\n }\n if (event.keyCode == 38) { //\"up\"\n if ($selectedItem) { //an element is already selected\n if ($itemsList.find(\"li:first-child\").hasClass(\"selectedItem\")) { //the first item is selected...\n itemToSelect = $itemsList.find(\"li:last-child\"); //so select the last\n }\n else { //otherwise just choose the previous one\n itemToSelect = $itemsList.find(\"li.selectedItem\").prev(\"li\");\n }\n }\n else { //none is selected, so choose the last\n itemToSelect = $itemsList.find(\"li:last-child\");\n }\n browse(itemToSelect,searchBoxLocation);\n }\n }\n\n function setSearchPrompt(configData) { //capture or fill in the initial search prompt\n var searchBoxLocation = configData.DOMselector,\n $searchPrompt = jQuery(searchBoxLocation).find(\".autoSuggestQuery\");\n $searchPrompt.attr(\"autocomplete\", \"off\");\n if (configData.promptInTextField) {\n var searchPromptInConfig = configData.promptInTextField;\n $searchPrompt.val(searchPromptInConfig);\n $searchPrompt.attr(\"data-searchprompt\",searchPromptInConfig); //save the prompt in a data attr\n }\n }\n\n function clearSearchField() { //search field should only be cleared if the stored search prompt is the same that is currently displayed in the field\n var $target = jQuery(this);\n if ($target.val() == $target.attr(\"data-searchprompt\")) {\n $target.val(\"\");\n }\n }\n\n function typeSearch(event, theSearchField, configData) {\n if (event.keyCode == 40 || event.keyCode == 38) { //navigating up or down?\n }\n else { //do suggest\n if (configData.minimumCharSearch) { //get minimum number of characters to search on\n characterSearchThreshold = configData.minimumCharSearch;\n }\n else {\n characterSearchThreshold = 2;\n }\n if ((jQuery(theSearchField).val().length < characterSearchThreshold)) { //under the threshold? hide the suggest\n hideSuggestions();\n }\n else { //start the suggest\n startSuggest(theSearchField, configData);\n }\n }\n }\n\n function startSuggest(theSearchField, configData) {\n var theQuery = jQuery(theSearchField).val(), //what to suggest on\n APIcall = configData.serviceLocation, //where is the API?\n payload = configData.nameOfQueryCall + theQuery, //querystring\n requesttype = configData.dataType,\n method = configData.getMethod;\n\n if (theQuery != \"\") { //did they actually type something??\n jQuery.ajax({\n url: APIcall,\n dataType: requesttype,\n data: payload,\n type: method\n }).done(function(data,status,xhr) {\n processSuccessfulResponse(data,configData,theQuery);\n }).fail(function(){\n processFailedResponse();\n });\n }\n }\n\n function showSuggestions(DOMselector) { //show\n var $target = jQuery(DOMselector).find(\".autoSuggestQueryResults\");\n $target.show();\n $target.addClass(\"active\");\n }\n\n function hideSuggestions() {\n $queryResults.fadeOut('fast', function() {\n $queryResults.removeClass(\"active\");\n });\n }\n\n function clearSuggestions() { //remove all suggestions\n $queryResults.empty();\n }\n\n function processSuccessfulResponse(response,configData,theQuery) { //response is good\n clearSuggestions();\n var theResultsNode = configData.resultsNode, //where are the results in the json?\n DOMselector = configData.DOMselector, //where to put them?\n dropdownTemplate = configData.suggestedItemTemplate, //what is the template?\n items = [],\n findQuery = RegExp('(' + theQuery + ')', \"gi\"); //case-insensitive regex search for the query, ready for search & replace\n\n if (response[theResultsNode] == \"\") { //anything to suggest?\n hideSuggestions();\n }\n\n else {\n showSuggestions(DOMselector);\n for (var j = 0; j < response[theResultsNode].length; j++) {\n var val = response[theResultsNode][j];\n\n //search for the query term in the results and make all instances bold\n if (typeof val === \"string\") {\n boldedResult = val.replace(findQuery, '<b>$1</b>');\n items.push(dropdownTemplate(j, val, boldedResult));\n }\n }\n if (configData.footerTemplate) {\n items.push(configData.footerTemplate(theQuery));\n }\n jQuery(items.join('')).appendTo(DOMselector + ' .autoSuggestQueryResults'); //add to listings ul\n }\n }\n\n function processFailedResponse(response) {\n //API failed\n }\n\n return {\n init: init,\n showSuggestions: showSuggestions,\n hideSuggestions: hideSuggestions\n };\n})(NYTD.jQuery);\n\nNYTD.jQuery(document).ready(function() {\n NYTD.Search.Suggest.init();\n});\n" }, { "alpha_fraction": 0.498694509267807, "alphanum_fraction": 0.5056570768356323, "avg_line_length": 27.370370864868164, "blob_id": "3dcf5924a2d4230a17c14f0dd9c48b7d920ae914", "content_id": "6311f829c170b089f9d0d004e1559d7feb52ab72", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2298, "license_type": "permissive", "max_line_length": 186, "num_lines": 81, "path": "/servers/demo-scaleout/html/server.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "\"use strict\";\nvar express = require('express'),\n fs = require('fs'),\n app = express(),\n //TODO: Save to some share instead of the local folder so when this is ran on multiple machines it doesn't have issues\n log_location = __dirname + '/har_logs/';\n\napp.use(setHeaders);\napp.use(express.bodyParser());\napp.use(app.router);\n\napp.get('/api/pages', getHtmlFiles);\napp.post('/api/har', saveHarFile);\napp.use(express.static(__dirname));\n\nvar port = process.env.PORT || 9999;\nconsole.log('Starting node on: ' + port);\n//app.listen(port);\napp.listen(port, '10.40.14.100');\n\nfunction createDateString() {\n var d = new Date();\n return d.getUTCFullYear() + \"_\" + d.getUTCMonth() + \"_\" + d.getUTCDate() + \"__\" + d.getUTCHours() + \"_\" + d.getUTCMinutes() + \"_\" + d.getUTCSeconds() + \"__\" + d.getUTCMilliseconds();\n}\n\nfunction saveHarFile(req, res) {\n if (req.body && req.body.har) {\n\n var dateString = createDateString(),\n fileName = log_location + dateString + '.har';\n\n fs.writeFile(fileName, req.body.har, function(err) {\n if (err) {\n res.json({\n msg: 'Error while writing file: ' + err\n });\n } else {\n res.json({\n msg: 'har file saved as: ' + fileName\n });\n }\n });\n } else {\n res.json({\n msg: 'Error, there was no body or har!'\n });\n }\n}\n\nfunction setHeaders(req, res, next) {\n res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');\n res.setHeader('Pragma', 'no-cache');\n res.setHeader('Expires', '0');\n next();\n}\n\nfunction getHtmlFiles(req, res) {\n fs.readdir(__dirname, function(err, files) {\n if (err) {\n res.json({\n error: 'failed to read directory: ' + __dirname\n });\n\n }\n var htmlPages = [];\n for (var i = files.length - 1; i >= 0; i--) {\n var file = files[i];\n if (file.match(/\\.html$/i)) {\n htmlPages.push(file);\n }\n };\n htmlPages = htmlPages.sort();\n res.json({\n pages: htmlPages\n // pages: [\n // \"index.html\",\n // \"nut.html\"\n // ]\n });\n });\n}\n" }, { "alpha_fraction": 0.6931432485580444, "alphanum_fraction": 0.6972165703773499, "avg_line_length": 28.459999084472656, "blob_id": "f7dbac1eeb79d18e33609b262e3931987ff03205", "content_id": "0a23bae28234ed01cfb2c2081db6ac95295edb65", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1473, "license_type": "permissive", "max_line_length": 169, "num_lines": 50, "path": "/servers/demo-scaleout/html/nyc-4/DropDown.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "function DropDown( dropDownId ){\n\tif( window.dropDowns && window.dropDowns[dropDownId] ){\t\t// already registered\n\t\treturn window.dropDowns[dropDownId];\n\t} else {\t\t\t\t\t\t\t\t\t\t\t\t\t// unregistered\n\t\tthis.elementId = dropDownId;\n\t\tthis.mouseOver = false;\n\t\tthis.timeoutID;\n\t\t\n\t\tvar ddObj = this.getElement();\n\t\n//\t\tif( ddObj.className != \"dropDown\" ) throw new Error( this.elementId + \" is not a valid DropDown. Please make sure you have provided it a CSS class of 'dropDown'.\" );\n\t\t\n\t\t//register\n\t\tif( !window.dropDowns )\twindow.dropDowns = new Object();\n\t\twindow.dropDowns[this.dropDownId] = this;\n\t}\t\t\t\t\n}\n\nDropDown.prototype.show = function(){\n\tvar ddObj = this.getElement();\n\tddObj.style.visibility = \"visible\";\n\t\n\tddObj.onmouseout = function( event ){\n\t\twindow.dropDowns[this.elementId].mouseOver = false;\n\t\tthis.timeoutID = window.setTimeout( \"window.dropDowns['\" + this.elementId + \"'].checkOver();\" , 500 );\n\t\t\n\t}\n\t\n\tddObj.onmouseover = function( event ){\n\t\twindow.dropDowns[this.elementId].mouseOver = true;\n\t\twindow.clearTimeout(this.timeoutID);\n\t}\n}\n\nDropDown.prototype.TimeOut = function(){\n\tvar ddObj = this;\n\tthis.timeoutID = window.setTimeout( function(){ddObj.checkOver();} , 500 );\n}\n\nDropDown.prototype.hide = function(){\n\tthis.getElement().style.visibility = \"hidden\";\n}\n\nDropDown.prototype.getElement = function(){\n\treturn document.getElementById( this.elementId );\n}\n\nDropDown.prototype.checkOver = function(){\n\tif( this.mouseOver == false ) this.hide();\n}\n" }, { "alpha_fraction": 0.7291666865348816, "alphanum_fraction": 0.7291666865348816, "avg_line_length": 47, "blob_id": "37ef65f317aa5b5fca680191f19050a873bda66b", "content_id": "2df5b2abb85a55bfd8c27e7b7e3bcf5d5d6e3e1c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 48, "license_type": "permissive", "max_line_length": 47, "num_lines": 1, "path": "/servers/demo-scaleout/html/natgeo.old/s.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "/* Node completed recruitment, nothing to do */\n" }, { "alpha_fraction": 0.5586080551147461, "alphanum_fraction": 0.5970696210861206, "avg_line_length": 21.75, "blob_id": "6bd68245e5d5e07dcae3b9ba825041bf20dfc8d3", "content_id": "119f72c25043144a951c418348b4c19927c01310", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 546, "license_type": "permissive", "max_line_length": 84, "num_lines": 24, "path": "/servers/demo-scaleout/html/stream.php", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "<?php\n\t$total_loop = 10;\n\tif (isset($_GET['duration'])){\n\t\t$total_loop = (int)$_GET['duration'];\n\t}\n\tfunction generateRandomString($length = 4096) {\n \t$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n \t$randomString = '';\n\n \tfor ($i = 0; $i < $length; $i++) {\n \t$randomString .= $characters[rand(0, strlen($characters) - 1)];\n \t}\n \treturn $randomString;\n\t}\n\t$string = generateRandomString();\n\t$loop = 0;\n\twhile ($loop < $total_loop)\n\t{\n\t\techo $string;\n\t\tflush();\n\t\t$loop ++;\n\t\tsleep(1);\n\t}\n?>\n" }, { "alpha_fraction": 0.5900474190711975, "alphanum_fraction": 0.5910347700119019, "avg_line_length": 25.103092193603516, "blob_id": "c4a34f973eac939793a89b4756784c1a13ddac42", "content_id": "7fa2d78af3174b7e29576c74b8fb687871631240", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 5064, "license_type": "permissive", "max_line_length": 99, "num_lines": 194, "path": "/demo-install.sh", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "root_check() {\n if ! [ $(id -u) = 0 ]; then\n echo \"=====> this script must be run as root\"\n exit 1\n fi\n}\n\n\n\ndistro_check() {\n if command -v apt-get &> /dev/null; then\n pkg_mgr=\"apt-get\"\n apt-get update\n elif command -v yum &> /dev/null; then\n pkg_mgr=\"yum\"\n yum install -y firewalld\n elif [ \"$(uname)\" == \"Darwin\" ]; then\n pkg_mgr=\"mac\"\n fi\n}\n\n\ncheck_for_pip() {\n if command -v pip &> /dev/null; then\n echo \"=====> python-pip is already installed \"\n else\n echo \"=====> python-pip is missing, installing \"\n if [ $pkg_mgr = \"yum\" ]; then\n if ! yum repolist | grep epel; then\n echo \"=====> epel repo is required for python-pip install, installing epel \"\n yum install -y epel-release\n fi\n echo \"=====> installing python-pip \"\n yum install -y python-pip\n elif [ $pkg_mgr = \"apt-get\" ]; then\n apt-get install -y python-pip\n elif [ $pkg_mgr = \"mac\" ]; then\n easy_install pip\n fi\n fi\n}\n\n\n\ncheck_for_dockerpy() {\n if python -c \"import docker\" &> /dev/null; then\n echo \"=====> docker-py already installed\"\n else\n echo \"=====> docker-py is missing, installing\"\n pip install docker-py --upgrade\n fi\n}\n\n\ncheck_for_avisdk() {\n if python -c \"import avi\" &> /dev/null; then\n echo \"=====> avisdk already installed\"\n else\n echo \"=====> avisdk is missing, installing\"\n pip install avisdk --upgrade\n fi\n}\n\n\n\ncheck_for_ansible() {\n if command -v ansible &> /dev/null; then\n echo \"=====> ansible is already installed\"\n else\n echo \"=====> ansible is missing, installing\"\n check_for_pip\n pip install 'ansible==2.5.0' --upgrade\n fi\n}\n\n\ncheck_for_ansible_roles() {\n if ansible-galaxy list avinetworks.docker | grep \"not found\" &> /dev/null; then\n echo \"=====> ansible avinetworks.docker role not installed\"\n ansible-galaxy install avinetworks.docker\n else\n echo \"=====> ansible avinetworks.docker role already installed\"\n fi\n if ansible-galaxy list avinetworks.avicontroller | grep \"not found\" &> /dev/null; then\n echo \"=====> ansible avinetworks.avicontroller role not installed\"\n ansible-galaxy install avinetworks.avicontroller\n else\n echo \"=====> ansible avinetworks.avicontroller role already installed\"\n fi\n if ansible-galaxy list avinetworks.avisdk | grep \"not found\" &> /dev/null; then\n echo \"=====> ansible avinetworks.avisdk role not installed\"\n ansible-galaxy install avinetworks.avisdk\n else\n echo \"=====> ansible avinetworks.avisdk role already installed\"\n fi\n if ansible-galaxy list avinetworks.aviconfig | grep \"not found\" &> /dev/null; then\n echo \"=====> ansible avinetworks.aviconfig role not installed\"\n ansible-galaxy install avinetworks.aviconfig\n else\n echo \"=====> ansible avinetworks.aviconfig role already installed\"\n fi\n}\n\n\n\ncheck_for_unzip() {\n if command -v unzip &> /dev/null; then\n echo \"=====> unzip is already installed\"\n else\n echo \"=====> unzip is missing, installing\"\n if [ $pkg_mgr = \"yum\" ]; then\n yum install -y unzip\n elif [ $pkg_mgr = \"apt-get\" ]; then\n apt-get install -y unzip\n fi\n fi\n}\n\n\ncheck_for_curl() {\n if command -v curl &> /dev/null; then\n echo \"=====> curl is already installed\"\n else\n echo \"=====> curl is missing, installing\"\n if [ $pkg_mgr = \"yum\" ]; then\n yum install -y curl\n else\n apt-get install -y curl\n fi\n fi\n}\n\n\ndependency_check() {\n echo \"=====> Checking for dependencies\"\n check_for_ansible\n check_for_dockerpy\n check_for_avisdk\n check_for_unzip\n check_for_curl\n check_for_ansible_roles\n}\n\n\ndownload_files() {\n curl -sSLk https://github.com/avinetworks/avi-corp-demo/archive/master.zip --output avidemo.zip\n unzip -nq avidemo.zip\n}\n\n\nplaybook_install_demo() {\n echo \"=====> Begin executing ansible playbooks to install demo\"\n ansible-playbook -i avi-corp-demo-master/hosts avi-corp-demo-master/demo_single_host.yml\n}\n\n\nplaybook_metrics_install() {\n echo \"=====> Begin executing ansible playbooks to install metrics\"\n ansible-playbook -i avi-corp-demo-master/metrics_hosts avi-corp-demo-master/metrics_install.yml\n}\n\n\nplaybook_metrics_delete() {\n echo \"=====> Begin executing ansible playbooks to delete metrics\"\n ansible-playbook -i avi-corp-demo-master/metrics_hosts avi-corp-demo-master/metrics_delete.yml\n}\n\n\ncheck_for_args() {\n for a in \"${cmd_args[@]}\"; do\n if [[ \"$a\" == \"metrics-install\" ]]; then\n playbook_metrics_install\n elif [[ \"$a\" == \"metrics-delete\" ]]; then\n playbook_metrics_delete\n fi\n done\n }\n\n\n\n\n\n\n#-----------------------------------\n\n\nroot_check\ndistro_check\ndependency_check\ndownload_files\nplaybook_install_demo\n\ncmd_args=(\"$@\")\ncheck_for_args\n" }, { "alpha_fraction": 0.6293622255325317, "alphanum_fraction": 0.6413959264755249, "avg_line_length": 17.886363983154297, "blob_id": "100ac266693fcc724724ad40a6418772b76c3379", "content_id": "ec7e29684c665207462bba39dad4655e87a5f77b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 831, "license_type": "permissive", "max_line_length": 106, "num_lines": 44, "path": "/client/scaleout/startup.py", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport subprocess\nfrom multiprocessing import Process\nimport os\nimport time\n\n\n\n#----- USE ENV VARS TO FIND VS IPs\n#----- os.environ\n\n\n\n\n#----- Add VS FQDN entries\n#cmd = 'echo \"169.254.10.2 scaleout.demovip.avi.local\" >> /etc/hosts'\n#result = subprocess.check_output(cmd, shell=True)\n#time.sleep(1)\n\n\n\n\n\nscript_list = [\n '/usr/bin/python /opt/avi/client/scaleout/traffic-ecc.py >> /opt/avi/client/scaleout/traffic-ecc.log',\n '/usr/bin/python /opt/avi/client/scaleout/traffic-rsa.py >> /opt/avi/client/scaleout/traffic-rsa.log'\n ]\n\n\ndef run_script(script):\n result = subprocess.check_output(script, shell=True)\n\n\n\n\nwhile True:\n proc = []\n for s in script_list:\n p = Process(target = run_script, args = (s,))\n p.start()\n proc.append(p)\n for p in proc:\n p.join()\n" }, { "alpha_fraction": 0.553504467010498, "alphanum_fraction": 0.5659071207046509, "avg_line_length": 31.115385055541992, "blob_id": "05b5a1e9d851e0c1e47c95ac1782345447662617", "content_id": "118e80f756ea70d4da2507b9efb54d9f0445bfee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3467, "license_type": "permissive", "max_line_length": 258, "num_lines": 104, "path": "/servers/demo-scaleout/html/boston.tmp/bcom_etaf_scripts.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "\t/* bcom_etaf_scripts \r\n\t\tE-Mail to A Fiend. \r\n\t\tOriginal mess started by rbrennan. \r\n\t\t11/10/10 rb - trying to clean things up a little. :/ \r\n\t\t02/22/11 JN - band-aiding until Methode saves us all (riiigghhttt)\r\n\t\t03/07/11 FD - Checking out this bandaid. I realized that the interpretation of \r\n\t\twhat the window is varies between browsers. When testing be sure to check on different browser window sizes.\r\n\t\tI recomend just having the etaf box appear at cursor position.\r\n\t*/ \r\n\t\r\n\t\r\n\t//This is a band-aid - don't hate me for it (side note: a Firefox specific bug, wtf?!)\r\n\t/********************************************/\r\n\tfunction wtfFF() {\r\n\tvar agt=navigator.userAgent.toLowerCase();\r\n\tif (agt.indexOf(\"firefox\") != -1) return 1;\r\n\telse return 0;}\r\n\t/*******************************************/\r\n\t\r\n\tfunction showETOF(pageX, pageY) {\r\n\t\ttheETOF = $('#bdc_emailWidget');\r\n\t\tetofHeight = theETOF.height();\r\n\t\tetofWidth = theETOF.width();\r\n\t\tetofXLocation = etofWidth + 100;\r\n\t\tetofYLocation = etofHeight;\r\n\t\tetofYLocation = etofHeight + 10;\r\n\t\tif(etofXLocation < 0) {etofXLocation = 1};\r\n\t\t$(theETOF).css({left: etofXLocation + 'px' , top: etofYLocation + 'px' }); \r\n\t\t$(\"#pointer_top\").show(); \r\n\t\t$(\"#pointer_bottom\").hide(); \r\n\t\t$(\"#message\").val('');\r\n\t\t$(\"#theEMTOFForm\").show();\r\n\t\t$(\"#bdc_EMTOF_sent\").hide();\r\n\t\t$(theETOF).show() ; \r\n\t}\r\n\r\n\tfunction validateEMTOF() { \r\n var emailRegexStr = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$/;\r\n var semail = document.getElementById(\"sender_email\");\r\n var remail = document.getElementById(\"recipient_email\");\r\n var validatedOK = true;\r\n var date = new Date();\r\n var curDate = null;\r\n var remailList = remail.value.split(/ *, */); \r\n for(var i = 0; i < remailList.length; ++i) {\r\n\tif ( emailRegexStr.test(remailList[i]) == false ){\r\n\t remail.className = 'error'; validatedOK = false;\r\n\t break;\r\n\t} else { \r\n\t remail.className = 'noerr';\r\n\t} \r\n} \r\n \r\n if ( emailRegexStr.test(semail.value) == false ){\r\n\tsemail.className = 'error'; validatedOK = false;\r\n } else { \r\n\tsemail.className = 'noerr';\r\n } \r\n \r\n return validatedOK;\r\n}\r\n\r\n\r\n\t/// Init JQuery event listener, form submit etc \r\n\t$(function() {\r\n\t\t\r\n\t\t// reset email input field onclick, but only the first time. \r\n\t\t$(\"#recipient_email\").focus(function(e) {\r\n\t\t\trecEmail = document.getElementById(\"recipient_email\") ;\r\n\t\t\tif (recEmail.defaultValue == recEmail.value ) { \r\n\t\t\t\t\trecEmail.value = '' ; \r\n\t\t\t} \r\n\t\t\t\t} ) \r\n\t\t\t\t$(\"#recipient_email\").blur() ; \r\n\r\n\t\t//default\r\n\t\t$(\".etaf\").click(function(e){\r\n\t\t\tthisPageX = e.pageX ; \r\n\t\t\tthisPageY = e.pageY ; \r\n\t\t\tshowETOF(e.pageX, e.pageY);\r\n\t\t})\r\n\t\t\t\t\r\n\t\t// submit form \r\n\t\t$(\"#bdc_emailWidget .form-button\").click(function() {\r\n\t\t\tvalid = validateEMTOF() ; \r\n\t\t\tif(valid ) { \r\n\t\t\t\tvar dataString = 'sender_name='+ $(\"#sender_name\").val() + '&sender_email=' + $(\"#sender_email\").val() + '&recipient_email=' + $(\"#recipient_email\").val() + '&message=' + $(\"#message\").val() + '&story_url=' + encodeURIComponent($(\"#story_url\").val()) ;\r\n\t\t\t\t$.ajax({\r\n\t\t\t\t\ttype: \"POST\",\r\n\t\t\t\t\turl: \"/emtaf/\",\r\n\t\t\t\t\tdata: dataString,\r\n\t\t\t\t\tsuccess: function(){\r\n\t\t\t\t\t\t$('#theEMTOFForm').hide();\r\n\t\t\t\t\t\t$('#bdc_EMTOF_sending').show();\r\n\t\t\t\t\t\t$('#bdc_EMTOF_sending').fadeOut(3000, function(){ \r\n\t\t\t\t\t\t\t$('#bdc_emailWidget').fadeOut(3000);\r\n\t\t\t\t\t\t\t$('#bdc_EMTOF_sent').show();\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t} \r\n\t\t\t\t}); \r\n\t\t\t } \r\n\t\t\treturn false;\r\n\t\t});\r\n\t});\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5573770403862, "alphanum_fraction": 0.5573770403862, "avg_line_length": 61, "blob_id": "416d9f22cd925b7cb02c5d3d936fdad88fb66811", "content_id": "d37d49574a13a22e1ae174535f951e90f0d22984", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 61, "license_type": "permissive", "max_line_length": 61, "num_lines": 1, "path": "/servers/demo-scaleout/html/boston.tmp/varccauds.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "ccauds={\"Profile\": {\"tpid\":\"\",\"Audiences\": {\"Audience\":[]}}};" }, { "alpha_fraction": 0.6083743572235107, "alphanum_fraction": 0.6256157755851746, "avg_line_length": 21.61111068725586, "blob_id": "f43980258eaf9130524354122e7b736d58edf7d3", "content_id": "97b20c2e1607cea54975ecd40e49462beefa0008", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 406, "license_type": "permissive", "max_line_length": 51, "num_lines": 18, "path": "/servers/demo-scaleout/html/natgeo/nodetag.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "(function(){ \n var d=document,w=window;\n function r(){\n\tvar z=d.createElement('SCRIPT');\n\tz.src='http://content.dl-rms.com/dt/s/19347/s.js';\n\td.getElementsByTagName('head')[0].appendChild(z);\n }\n\n if(Math.random()<1) {\n if (d.readyState==\"complete\"){\n\tr();\n } else if (w.addEventListener){ \n\tw.addEventListener(\"load\", r, false);\n } else if (w.attachEvent){ \n\tw.attachEvent(\"onload\", r);\n }\n }\n})();" }, { "alpha_fraction": 0.5982292294502258, "alphanum_fraction": 0.6081359386444092, "avg_line_length": 36.78480911254883, "blob_id": "a321c66d292ba5fcbf5433273a5df465f2b2f9d9", "content_id": "a204204a92dfa82c06df843cc5879c5f452945fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 41790, "license_type": "permissive", "max_line_length": 506, "num_lines": 1106, "path": "/servers/demo-scaleout/html/natgeo/general-cb1384346507.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "jQuery.fn.reloadAds= (function($){\nreturn function(){\n this.find(\"[data-ngsadid]\").each(function(idx){\n var adid = $(this).attr(\"data-ngsadid\")\n WPF_admanager && WPF_admanager.displayAd( adid )\n });\n}\n})(jQuery);\n// helper for determining string endings\nString.prototype.endsWith = function(str){\n var lastIndex = this.lastIndexOf(str);\n return (lastIndex != -1) && (lastIndex + str.length == this.length);\n}\n\n// hide article text until paginated\nif($('.article_text').length > 0) {\n $('.article_text').addClass(\"hidden\");\n}\n\n// triggers styles for js enabled users\n$('html').addClass('js');\n\n//ensure we don't overwrite an existing instance\nif (!window.addthis_share) {\n var addthis_share = {};\n}\n\n//declare how and where to use url shortening\nwindow.addthis_share.url_transforms = {\n shorten : {\n twitter: 'bitly'\n }\n};\n\n//configure our url shortening service\nwindow.addthis_share.shorteners = {\n bitly: {\n login: 'natgeo',\n apiKey: 'R_62083d1fa7328bb178db7ffd7d496df9'\n }\n}\n\n// Page check to see if Nirvana body class needs to be added for NGM contests\nfunction nirvanaPageCheck() {\n var path = [];\n path = window.location.pathname.split(\"/\");\n for (var i in path) {\n if (path[i].length && path[i] === \"photo-contest\") {\n if (!$(\"body\").hasClass(\"nirvana\")) {\n $(\"body\").addClass(\"nirvana\");\n }\n }\n }\n};\n\n/* $(document).ready() code -- executed after page load completes */\n$(document).ready(function() {\n var $dl = $('div.dl'),\n $newsletter = $('#newsletter input'),\n $carousel = $('div.carousel'),\n $factSlides = $carousel.find('.fact_slides');\n\n /*---- DL Code ----*/\n if( ($dl.length > 0) && (typeof($.fn.dynamiclead) != \"undefined\") ) {\n $dl.find('h3').addClass('hidden');\n $dl.find('.credit').removeClass('hidden');\n\n $dl.find('ul').dynamiclead({\n slideArray: ((typeof(DLslides)!=\"undefined\")?DLslides:[{url:'',link:'',headline:'',caption:''}])\n });\n }\n\n /*---- Put label text inside input for Newsletters ----*/\n if($newsletter.length > 0) {\n $newsletter.labelify({ text: \"label\" });\n }\n\n\n /*---- Initialize Carousels ----*/\n// callback function exclusively for Kids Carousel\nfunction kidsCarouselInitCallback(carousel, state) {\n if (state == \"init\" || state == \"reset\") {\n $(\"ul.kidscarousel.jcarousel-list-horizontal li\").each(function(index) {\n var kcTitle = $(this).children(\"a\").attr(\"title\");\n var kcHref = $(this).children(\"a\").attr(\"href\");\n $(this).prepend('<a class=\"kidscarousel_frame\" href=\"'+kcHref+'\" title=\"'+kcTitle+'\">&nbsp;</a>');\n $(this).children(\"a.kidscarousel_frame\").hover(\n function () {\n $(this).next(\"a\").next(\"p\").children(\"a\").addClass(\"pretty_underline\");\n },\n function () {\n $(this).next(\"a\").next(\"p\").children(\"a\").removeClass(\"pretty_underline\");\n }\n );\n });\n\n }\n};\n\n// callback function when an item becomes the first one visible\nfunction mycarousel_itemFirstInCallback(carousel, item, idx, state) {\n $(item).next().removeClass(\"carousel_first_visible\");\n $(item).addClass(\"carousel_first_visible\");\n};\n\n// callback function when an item is no longer the first one in the visible range\nfunction mycarousel_itemVisibleOutCallbackAfterAnimation(carousel, item, idx, state) {\n $(item).removeClass(\"carousel_first_visible\");\n};\n\n if($carousel.length > 0) {\n $factSlides.jcarousel({\n scroll: 1,\n visible: 1,\n initCallback: fact_slides_initCallback,\n itemFirstInCallback: fact_slides_itemFirstInCallback\n });\n if($factSlides.find('.jcarousel_prev').length > 0) {\n $factSlides.find('.jcarousel_prev').after();\n }\n\n\t\t$carousel.each(function(){\n\n\t\t\tvar $currentCarousel = $(this);\n\n\t\t\tif (!($currentCarousel.is(':hidden') || $currentCarousel.parents(':hidden').length)) {\n\n\t\t $currentCarousel.find('.one').jcarousel({\n\t\t scroll: 1,\n\t\t visible: 1\n\t\t });\n\n\t\t $currentCarousel.find('.three').jcarousel({\n\t\t scroll: 3,\n\t\t visible: 3\n\t\t });\n\n\t\t $currentCarousel.find('.seven').jcarousel({\n\t\t scroll: 7,\n\t\t visible: 7\n\t\t });\n\n\t\t $currentCarousel.find('.four').jcarousel({\n\t\t scroll: 4,\n\t\t visible: 4\n\t\t });\n\n\t\t $currentCarousel.find('.kidscarousel').jcarousel({\n\t\t scroll: 4,\n\t\t visible: 5,\n\t\t initCallback: kidsCarouselInitCallback\n\t\t });\n\n\t\t $currentCarousel.find('.kidsecommercecarousel').jcarousel({\n\t\t scroll: 1,\n\t\t visible: 3,\n\t\t itemFirstInCallback: mycarousel_itemFirstInCallback,\n\t\t itemVisibleOutCallback: {\n\t\t onAfterAnimation: mycarousel_itemVisibleOutCallbackAfterAnimation\n\t\t }\n\t\t });\n\n\t\t $currentCarousel.find('.magazine').jcarousel({\n\t\t scroll: 5\n\t\t });\n\n\t\t $currentCarousel.find('.iphone').jcarousel({\n\t\t scroll: 2,\n\t\t visible: 2\n\t\t });\n\n\t\t $currentCarousel.find('.restrain').removeClass('restrain');\n\t\t\t}\n\t\t});\n\n $('ul.magazine li:nth-child(5n), ul.magazine li:last').css('border', 'none');\n\n if ($('ul.magazine li').length == 5) {\n $('.magazine div.jcarousel-prev, .magazine div.jcarousel-next').hide();\n } else {\n $('.magazine div.jcarousel-prev, .magazine div.jcarousel-next').show();\n }\n }\n /*---- Build link list columns ----*/\n $(' .columns > ol, .columns > ul').each(function() {\n var $this = $(this);\n if (!($this.parent().parent().hasClass('full_width'))) {\n $this.columns({\n cols:2\n });\n }else {\n $this.columns({\n cols:3\n });\n }\n });\n /*---- Share Button Home Code ----*/\n if($('body.home #share, body.level_2 #share').length > 0) {\n $('body.home #share, body.level_2 #share').addClass('collapsed');\n }\n if($('#nav_share').length > 0) {\n $('#nav_share li a').addClass('hiddenText');\n $('#nav_share li').slice(4).addClass('hidden');\n $('#nav_share').append('<li class=\"more_link\"><a href=\"\">More</a></li>');\n var moreLink = $('#nav_share .more_link');\n moreLink.click(function () {\n $('#share').toggleClass('collapsed');\n $('#nav_share li').slice(4, -1).toggleClass('hidden');\n if (moreLink.text() =='More'){\n moreLink.html('<a href=\"\">Collapse</a>');\n } else {\n moreLink.html('<a href=\"\">More</a>');\n }\n return false;\n });\n }\n /*---- Hide Share Email Form ----*/\n if($('#share_email').length > 0) {\n $('#share_email').addClass('hidden');\n }\n /*---- Prepend Print Link to Article Rating div ----*/\n // Causing some error, possibly related to Share Links scripts; user not affected - LB 061009\n if($('#article_rating').length > 0) {\n $('#article_rating').before('<div id=\"print_link\"><a href=\"#\" onclick=\"ngsprint();return false;\">Printer Friendly</a></div>');\n }\n /*---- Most Popular Tabs Code ----*/\n if($('div.tabbed_box').length > 0) {\n $('div.tabbed_box').each(function() {\n // Show just the first tab\n var sections = $('.popularity_type', this);\n sections.hide();\n $(sections[0]).show();\n\n // Build the tab-links\n var ul = $('<ul class=\"nav nav_tabbed\">');\n sections.each(function(index) {\n var section_obj = $(this);\n var heading = $('h4', this).html();\n var li = $('<li class=\"nav_0'+(index+1)+'\">');\n $('h4', this).remove();\n li.append(\n $('<h4><a href=\"#\">'+heading+'</a></h4>').click(function() {\n // Show just this section.\n sections.hide();\n section_obj.show();\n\n // And mark just this tab\n tabs.removeClass('selected');\n li.addClass('selected');\n return false;\n }));\n ul.append(li);\n })\n\n $('div.wrap', this).before(ul);\n\n // Compile the list of new tabs we just made, and select the first one.\n var tabs = $('li', ul);\n $(tabs[0]).addClass('selected');\n });\n }\n /*---- Table Striping ----*/\n if($('table.striped').length > 0) {\n $('table.striped tr:odd').addClass('striped');\n //$('table.striped tr:odd').css('background-color','#f4f4f4');\n }\n /*---- Article Rating functionality ----*/\n\n /*---- Video Icon Overlay ----*/\n if($('.video').length > 0) {\n $('.video').each(function(){\n var vid_thumb_width = $('img', this).attr('width');\n if (vid_thumb_width == 160) {\n var overlay_position = 10;\n } else {\n var overlay_position = 5;\n };\n var vid_link = $('a', this).attr('href');\n\n if (vid_thumb_width == 160 || vid_thumb_width == 100) {\n $('img', this).after('<img src=\"'+((typeof(staticURL)!=\"undefined\")?staticURL:'/')+'sites/common/i/presentation/video_overlay.png\" class=\"overlay\" alt=\"Video Icon Overlay\" style=\"left: '+ overlay_position +'px; bottom: '+ overlay_position +'px;\"/>');\n };\n });\n }\n\n /*---- Article Pagination functionality ----*/\n // check for the article content container by class\n if(typeof pageSet != \"undefined\" && $('.article_text').length > 0) {\n // create a new pageSet object\n articlePages = new pageSet({\n oPageContainer:((typeof($)!=\"undefined\")?$(\".article_text\")[0]:document.getElementsByClassName('article_text')[0]),\n oMatchRE:new RegExp(\"page_*break\"),\n strMatchTagName: \"comment\",\n activePageIndex:jss.current_page(),\n pageItemClass: \"article-page-item\",\n callback: function(delaySecs) {\n delaySecs=((delaySecs&&!isNaN(parseInt(delaySecs)))?parseInt(delaySecs):.5);\n if(typeof(ngsPageView)!=\"undefined\") {\n if(typeof(callTmr)!=\"undefined\"){\n clearTimeout(callTmr);\n };\n callTmr = setTimeout(\"ngsPageView();\",(delaySecs*1000));\n }\n }\n });\n\n if(articlePages.pages.length>1) {\n $($(\".article_text\").get(0)).append('<div class=\"nav-article-pages pagination\"></div>');\n $(\".nav-article-pages\").pagination(Math.ceil(articlePages.pages.length), {\n items_per_page:1,\n num_display_entries: 14,\n current_page: jss.current_page(),\n callback:articlePages.viewPage,\n link_to: \"#\"+articlePages.hashVar+\"=__id__\",\n prev_text: \"&laquo; Previous\",\n next_text: \"Next &raquo;\"\n });\n articlePages.viewPage(articlePages.activePageIndex);\n articlePages.readyState = \"4:COMPLETED\";\n }\n $('.article_text').removeClass(\"hidden\");\n }\n\n if(FlashApps[0] != undefined){ loadFlashApps();}\n if(rssFeeds[0] != undefined){ loadRssReaders();}\n if(factsBoxes[0] != undefined){ loadFactsBoxes();}\n if(typeof(VEMaps)!=\"undefined\" && typeof(VEMaps[0]) != \"undefined\" && VEMaps[0] != undefined) {loadVEMaps();}\n if(typeof(oneMaps)!=\"undefined\" && typeof(oneMaps[0]) != \"undefined\" && oneMaps[0] != undefined) {loadOneMaps();}\n\n /*---- Set Equal Heights on Columns ----*/\n if ($.fn.equalHeights) {\n $('.homepage .subsection, .homepage #content_page_specific, .article .subsection, .small_article .subsection, .home .subsection, .article #content_page_specific, .small_article #content_page_specific, .home #content_page_specific, .level_2 #content_page_specific, .level_2 #content_page_specific .subsection, .a_z #content_page_specific, .mobile .promo_collection .horizontal, .subscriptions, .subscriptions2, .mobile .small_article').not('.natgeov .subsection, nav .subscriptions').equalHeights(true);\n }\n /*---- Collapse Any Empty Ad Units ----*/\n var kidsSecondaryAd = ((document.getElementById(\"advertisingModule210x50\") && document.getElementById(\"advertisingModule210x50\").length > 1)?document.getElementById(\"advertisingModule210x50\")[0]:((document.getElementById(\"advertisingModule210x50\"))?document.getElementById(\"advertisingModule210x50\"):false));\n if(kidsSecondaryAd) {\n collapseEmptyHeaderAds();\n if (kidsSecondaryAd && $(kidsSecondaryAd).find('iframe').length > 0) {\n $(kidsSecondaryAd).find('iframe').get(0).onload = function() { collapseEmptyHeaderAds(); };\n }\n } else {\n collapseEmptyHeaderAds({expandDuration:888});\n }\n getLoadTimes();\n});\n\n/*---- Print function ----*/\nfunction ngsprint() {\n window.print();\n}\n\njQuery.expr[':'].regex = function(elem, index, match) {\n var matchParams = match[3].split(','),\n validLabels = /^(data|css):/,\n attr = {\n method: matchParams[0].match(validLabels) ? matchParams[0].split(':')[0] : 'attr',\n property: matchParams.shift().replace(validLabels,'')\n },\n regexFlags = 'ig',\n regex = new RegExp(matchParams.join('').replace(/^\\s+|\\s+$/g,''), regexFlags);\n return regex.test(jQuery(elem)[attr.method](attr.property));\n}\n\ngetLeadingZeros = function(opts) {\n var n = ((typeof(opts['n'])!=\"undefined\"&&!isNaN(parseInt(opts['n'])))?opts['n']:0);\n var digits = ((typeof(opts['digits'])!=\"undefined\"&&!isNaN(parseInt(opts['digits'])))?opts['digits']:3);\n return ((n.toString().length>=digits)?n:( (n + 1) * parseFloat( parseFloat('0').toFixed( digits - 1 ) + 1 ) ).toFixed(digits).toString().split('.')[1]);\n}\n\n/* FUNCTION: wrapByRegEx({parentSelectorText:[STRING],matchRegEx:[REGULAR EXPRESSION or ARRAY OF REGULAR EXPRESSIONS],wrapHTML:[STRING or ARRAY OF STRINGS],idDigits:[NUMBER]})\n--- wraps matching text nodes with supplied HTML snippet, using id attribute if [[id]] is present in the HTML snippet and idDigits > 0 ---\n*/\nwrapByRegEx = function(opts) {\n var parentSelectorText = ((typeof(opts[\"parentSelectorText\"])!=\"undefined\")?opts[\"parentSelectorText\"]:null);\n if(parentSelectorText==null) {\n return false;\n }\n var idDigits = ((typeof(opts[\"idDigits\"])!=\"undefined\"&&!isNaN(parseInt(opts[\"idDigits\"])))?parseInt(opts[\"idDigits\"]):-1);\n var matchRegEx = ((typeof(opts[\"matchRegEx\"])!=\"undefined\")?((typeof(opts[\"matchRegEx\"])!=\"string\"&&typeof(opts[\"matchRegEx\"].length)!=\"undefined\")?opts[\"matchRegEx\"]:[opts[\"matchRegEx\"]]):null);\n var wrapHTML = ((typeof(opts[\"wrapHTML\"])!=\"undefined\")?((typeof(opts[\"wrapHTML\"])!=\"string\"&&typeof(opts[\"wrapHTML\"].length)!=\"undefined\")?opts[\"wrapHTML\"]:[opts[\"wrapHTML\"]]):null);\n var s_regExCombined = \"\";\n var is_ignoreCase = false;\n $(matchRegEx).each(function(i){\n s_regExCombined += \"(\"+this.source + \")\"+((i==matchRegEx.length-1)?\"\":\"|\");\n is_ignoreCase = ((this.ignoreCase)?true:is_ignoreCase);\n });\n var combinedMatchRegEx = new RegExp(s_regExCombined,((is_ignoreCase)?\"i\":\"\"));\n var n = 1;\n var a_allNodes = $(parentSelectorText)\n .contents()\n .filter( function() {\n if((this.nodeType == Node.TEXT_NODE) && (this.data+'').match(combinedMatchRegEx)!=null) {\n var s_nodeData = (this.data+'');\n var o_textNode = this;\n $(matchRegEx).each(function(i){\n if(s_nodeData.match(this)) {\n var s_matchFlags = ( (this.ignoreCase) ? \"i\":\"\" ) + ( (this.global) ? \"g\":\"\" ) + ( ( this.multiline)?\"m\":\"\" );\n var matchRE = ( ( (this.source+'').match(/(^|[^\\\\])\\(|[^\\\\]\\)/) ? this : new RegExp( \"(\" + this.source + \")\" , s_matchFlags ) ) );\n var is_useMatchText = (wrapHTML[i].match(/\\[\\[matchText\\]\\]/) != null);\n var s_wrapped = ( (idDigits) ?\n wrapHTML[i].replace( /\\[\\[id\\]\\]/g, getLeadingZeros({n:n,digits:idDigits}) ) :\n wrapHTML[i] );\n var s_wrapped = ( (is_useMatchText) ? s_wrapped.replace(/\\[\\[matchText\\]\\]/gi,\"\\$1\") : s_wrapped);\n var s_replaceText = s_nodeData.replace( matchRE , s_wrapped );\n $(o_textNode).replaceWith(s_replaceText);\n n++;\n }\n });\n }\n });\n}\n\nparseXML = function(xml) {\n if( window.ActiveXObject && window.GetObject ) {\n var dom = new ActiveXObject( 'Microsoft.XMLDOM' );\n dom.loadXML( xml );\n return dom;\n }\n if( window.DOMParser ) {\n return new DOMParser().parseFromString( xml, 'text/xml' );\n }\n throw new Error( 'No XML parser available' );\n}\n\n\n// NG RICH MEDIA FUNCTIONS\nvar FlashApps = [];\naddFlashApp = function(dataObj){\n FlashApps.push(dataObj);\n}\n\nloadFlashApps = function(){\n var totApps = FlashApps.length;\n for(var i=0;i<totApps;i++){\n createFlashObject(FlashApps[i]);\n }\n}\ncreateFlashObject = function(dataObj){\n $(dataObj.div).css(\"visibility\",\"visible\");\n if(dataObj.customXML){\n loadSWF();\n } else {\n var richMediaXML;\n parseRichMediaXML();\n }\n function parseRichMediaXML(){\n try {\n richMediaXML = parseXML(dataObj.currentXML);\n } catch(err) {\n $(dataObj.div).append(\"<p><strong>ERROR PARSING XML</strong></p>\");\n }\n loadSWF();\n }\n function loadSWF(){\n\n var params = {};\n params.allowscriptaccess = \"always\";\n if(dataObj.type == \"Quiz\"){\n params.wmode = \"transparent\";\n params.scale = \"exactfit\";\n } else if(dataObj.type == \"game\"){\n params.wmode = \"window\";\n params.scale = \"noscale\";\n } else if(dataObj.type == \"Quiz - Travel Country\"){\n params.wmode = \"opaque\";\n params.scale = \"default\";\n } else {\n params.wmode = \"opaque\";\n params.scale = \"noscale\";\n }\n\n params.menu = \"false\";\n params.quality = \"best\";\n params.bgcolor = dataObj.bgcolor;\n params.base = dataObj.filePath;\n params.salign = \"tl\";\n\n //Javascript workaround until the Object tag is working\n var tempSite = window.location.host;\n var siteDomain = \"http://\" + tempSite;\n\n var flashvars = {};\n flashvars.css = dataObj.css;\n flashvars.siteDomain = siteDomain;\n\n // For Dynamic content that needs dimensions\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n flashvars.width = dataObj.width;\n flashvars.height = dataObj.height;\n\n // QUIZ ////////////////////////////////////////////////////\n flashvars.cssFile = flashvars.css;\n flashvars.imagePath = dataObj.filePath;\n flashvars.parentDiv = dataObj.parentDiv;\n // END QUIZ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n\n if(dataObj.customXML){\n flashvars.xml = dataObj.xmlURL;\n flashvars.xmlfile = dataObj.xmlURL;// for quizzes\n flashvars.xmlFile = dataObj.xmlURL;// for other interactives\n } else {\n if(dataObj.xml != \"\"){\n flashvars.xml = dataObj.xml;\n flashvars.xmlfile = flashvars.xml;// For quizzes\n flashvars.xmlFile = flashvars.xml;// For other interactives\n }\n $(richMediaXML).find(\"richmedia\").children().each(function(){\n flashvars[this.tagName] = $(this).text();\n });\n };\n\n var attributes = {};\n attributes.id = dataObj.slug;\n\n if(dataObj.width == undefined||dataObj.width == \"\"||dataObj.height == \"\"||dataObj.height == undefined||dataObj.version == \"\"||dataObj.version == undefined){\n $(dataObj.div).append(\"<p><strong>ERROR IN RICH MEDIA TYPE: Please check your settings</strong></p>\");\n return;\n } else {\n swfobject.embedSWF(dataObj.flashURL, dataObj.slug, dataObj.width, dataObj.height, dataObj.version, false, flashvars, params, attributes);\n }\n }\n}\n\n\nloadGalleryVideo = function(div,slug,siteid,w,h,adenabled,autoplay){\n var params = {allowfullscreen:true,allowscriptaccess:\"always\",wmode:\"opaque\",menu:\"false\",quality:\"best\",bgcolor:\"#FFFFFF\",scale:\"noscale\",salign:\"tl\"};\n var flashvars = {slug:slug,siteid:siteid,adenabled:adenabled || 'true',autoplay:autoplay || 'true'};\n var attributes = {id:slug};\n var noFlashStr = '<img style=\"vertical-align:middle;\" width=\"30\" height=\"30\" alt=\"Adobe Flash Player\" src=\"http://wwwimages.adobe.com/www.adobe.com/shockwave/download/images/flashplayer_100x100.jpg\"/> This video requires the latest version of Flash Player. <a href=\"http://get.adobe.com/flashplayer/\">Click here to download.</a>';\n\n if(w == undefined) w = 437;\n if(h == undefined) h = 246;\n var fW = String(w);\n var fH = String(h+31);\n\n flashvars.width = w;\n flashvars.height = h;\n\n swfobject.embedSWF(\"http://images.nationalgeographic.com/wpf/sites/video/swf/ngplayer_satellite.swf\", div, fW, fH, \"9\", false, flashvars, params, attributes, loadH5Video);\n\n function loadH5Video(e){\n var useragent = navigator.userAgent;\n var supported = false;\n\n if(useragent.search('iPhone') >= 0 || useragent.search('iPad') >= 0) supported = true;\n else if(useragent.search('Safari')){\n var sPos = useragent.indexOf('Intel Mac OS X ')+15;\n var ePos = useragent.indexOf(';',sPos);\n var version = useragent.substring(sPos,ePos).split('_');\n\n if(parseInt(version[0]) >= 10 && parseInt(version[1]) >= 6) supported = true;\n }\n\n if(!e.success && supported){\n $('#'+div).html(\"<video style='background-color:#000;' src='http://h5media.nationalgeographic.com/video/player/media-mp4/\"+slug+\"/mp4/variant-playlist.m3u8' poster='http://video.nationalgeographic.com/video/player/media/\"+slug+\"/\"+slug+\"_480x360.jpg' controls width='\"+w+\"' height='\"+h+\"'></video>\");\n }\n else {\n $('#'+div).html(noFlashStr);\n }\n }\n}\n\n\nloadVideo = function(div,slug,siteid,w,h,adenabled,autoplay){\n // Add the video script to the document header\n var headID = document.getElementsByTagName('head')[0];\n var videoScript = document.createElement('script');\n var videoPlayerURL = (siteid == 'videoplayerkids') ? \"sites/video/swf/ngkidsplayer_v2.1.swf\" :\"sites/video/swf/ngplayer_v2.5.swf\";\n\n videoScript.type = \"text/javascript\";\n videoScript.src = staticURL+'sites/video/j/natgeov-video.js';\n \n // Add the geolocater script to the document header\n var geoScript = document.createElement('script');\n geoScript.type = \"text/javascript\";\n geoScript.src = \"http://j.maxmind.com/app/country.js\";\n headID.appendChild(geoScript);\n \n // Wait for video script to completely load before continuing\n videoScript.onload = videoScript.onreadystatechange = function() {\n var done, _ref;\n if (!done && (!this.readyState || this.readyState === \"loaded\" || this.readyState === \"complete\")) {\n done = true;\n\n // Access video data and construct embed code to pass to NGPlayer\n $.getJSON(\"http://\" + window.location.host + \"/video/api/get/video/by-slug/\" + slug + \"/json/\", null, function(jsonp) {\n var videoslug = jsonp.video.smil;\n if(window.location.host == \"localhost\"||window.location.host.substr(0,1) == \"1\"){\n var tempslug = videoslug.split('.com');\n videoslug = \"http://\" + window.location.host + tempslug[1];\n }\n\t\tvar vpOptions = new NGPlayer.Options({\n $container : $('#'+div+''),\n slug : videoslug,\n title : jsonp.video.title,\n caption : jsonp.video.description,\n poster : jsonp.video.still,\n restricted : \"\" || \"false\",\n siteid : siteid,\n permalink : jsonp.video.url,\n width : w || 437,\n height : h || 246,\n autoplay : autoplay || \"true\",\n bgcolor : \"#FFF\",\n share : (siteid == \"videoplayerkids\") ? \"false\" : \"true\",\n allowEmbed : (siteid == \"videoplayerkids\") ? \"false\" : \"true\",\n cuepoints : jsonp.video.cuepoints || \"\",\n swfURL : staticURL+videoPlayerURL,\n adenabled : adenabled || \"true\",\n adprogramid : \"4a67dd6268de7\",\n HTML5src : jsonp.video.HTML5src,\n isKids : (siteid == \"videoplayerkids\")\n });\n\n // Adjust height for Flash encoded videos but not HTML5\n // This is not feature detection as our current encoding is specific for iOS\n // A more accurate and future appropriate test will need to be written once videos are re-encoded\n if ((/ipod|ipad|iphone/).test(navigator.userAgent.toLowerCase()) === false) {\n vpOptions.height = vpOptions.height + 31;\n }\n\n // Update poster URL with hostname from permalink if it does not contain a full URL\n // Partial URLs start with a leading slash\n if (!vpOptions.poster.match(/(http:\\/\\/|https:\\/\\/)/igm)) {\n vpOptions.poster = \"http://\" + vpOptions.permalink.match(RegExp('^(?:f|ht)tp(?:s)?\\://([^/]+)', 'im'))[1] + jsonp.video.still;\n }\n\n // If still does not exist, use legacy image\n if (!vpOptions.poster || vpOptions.poster == '') {\n vpOptions.poster = \"http://video.nationalgeographic.com/video/player/media/\"+slug+\"/\"+slug+\"_480x360.jpg\";\n }\n\n // Update the DART Ad Program ID if this is a Kids site\n if (window.location.hostname === \"kids.nationalgeographic.com\"||siteid == \"videoplayerkids\") {\n vpOptions.adprogramid = \"4fa81b8d31446\";\n }\n\n // Generic function to convert an array to an object\n function objConv(a) {\n var o = {};\n for(var i=0;i<a.length;i++)\n {\n o[a[i]]='';\n }\n return o;\n }\n\n // Determine if video is restricted in the user's country\n var country_code = 'US';\n try{\n country_code = geoip_country_code();\n }catch(exception){\n console.log(\"error while trying to get the country: \"+exception);\n }\n if (jsonp.video.is_us_only === \"true\") {\n if (country_code === \"US\") {\n vpOptions.restricted = \"false\";\n } else {\n vpOptions.restricted = \"true\";\n }\n } else if (jsonp.video.is_us_only === \"false\") {\n denyList = objConv(jsonp.video.country_code_deny_list);\n allowList = objConv(jsonp.video.country_code_allow_list);\n\n if (country_code in denyList) {\n vpOptions.restricted = \"true\";\n } else if (!country_code in denyList || denyList == \"undefined\") {\n if (country_code in allowList) {\n vpOptions.restricted = \"false\";\n } else {\n vpOptions.restricted = \"false\";\n }\n }\n } else {\n vpOptions.restricted = \"false\";\n }\n\n // Let's start the show!\n window.videoPlayer = new NGPlayer(vpOptions);\n });\n }\n }\n headID.appendChild(videoScript);\n}\n\n// INTERACTIVE MAP FUNCTIONS\nvar VEMaps = [];\naddMapToPage = function(mapObj){\n VEMaps.push(mapObj);\n}\n\nloadVEMaps = function(){\n for(var i=0;i<VEMaps.length;i++){\n renderVEMap(VEMaps[i]);\n }\n}\n\nrenderVEMap = function(mapObj){\n var bingMap = null;\n bingMap = new VEMap(mapObj.div);\n bingMap.LoadMap(new VELatLong(mapObj.latitude,mapObj.longitude), mapObj.zoom, mapObj.viewType, mapObj.lockMap);\n if(mapObj.showMini)bingMap.ShowMiniMap(mapObj.miniXposition, 5);\n if(!mapObj.showTools)bingMap.HideDashboard();\n}\n\n//ONEMAP FUNCTIONS\nvar oneMaps = [];\naddOneMapToPage = function(mapObj){\n oneMaps.push(mapObj);\n}\n\nloadOneMaps = function(){\n for(var i=0;i<oneMaps.length;i++){\n renderOneMap(oneMaps[i]);\n }\n}\n\nrenderOneMap = function(mapObj){\n $(mapObj.div).RenderOneMap({collection_id:mapObj.collection_id, search:null, fixed:mapObj.fixed, DefaultTileset:mapObj.tile_set, DefaultLat:mapObj.latitude, DefaultLon:mapObj.longitude, DefaultZoom:mapObj.zoom});\n //collection_id: coll_id, //To load a single collection worth of results (not used with search:)\n //search: searchterm, //A string value used to filter results (not used with collection_id:)\n //fixed: false, //Stops the map from moving\n //DefaultTileset: null, //Takes an id value for a tileset (you can check the values using the REST svc)\n //DefaultLat: null, //Map Center Lat/Lon in float-parseable format\n //DefaultLon: null,\n //DefaultZoom: null //Map Zoom level from 1-21\n}\n\n\n//Carousel Callback\n\nfunction fact_slides_initCallback(carousel) {\n var count = $('ul.fact_slides li').length;\n $('div.fact_slides .jcarousel-prev').after('<p class=\"count\"><span class=\"current\"></span> of '+count+'</p>');\n};\n\n\nfunction fact_slides_itemFirstInCallback(carousel, idx, item) {\n $('div.fact_slides span.current').html(item);\n\n};\n\nvar taxonomy;\nvar hasTaxonomy = false;\nfunction highlightNavItem(){\n var navClass;\n if(taxonomy.site == 'environment.nationalgeographic.com'){\n navClass = '#navigation_tophat_primary li.nav4 ul li:contains('+taxonomy.name+')';\n } else if(taxonomy.site == 'photography.nationalgeographic.com'){\n navClass = '#navigation_tophat_primary li.nav2 ul li:contains('+taxonomy.name+')';\n } else if(taxonomy.site == 'travel.nationalgeographic.com'){\n navClass = '#navigation_tophat_primary li.nav5 ul li:contains('+taxonomy.name+')';\n } else if(taxonomy.site == 'animals.nationalgeographic.com'){\n navClass = '#navigation_tophat_primary li.nav3 ul li:contains('+taxonomy.name+')';\n } else if(taxonomy.site == 'adventure.nationalgeographic.com'){\n navClass = '#navigation_tophat_primary li.nav6 ul li:contains('+taxonomy.name+')';\n } else if(taxonomy.site == 'ocean.nationalgeographic.com'){\n navClass = '#navigation_tophat_primary li.nav4 ul li:contains(The Ocean)';\n } else if(taxonomy.site == 'video.nationalgeographic.com'){\n navClass = '#navigation_tophat_primary li.nav9 ul li:contains('+taxonomy.name+')';\n } else {\n return;\n }\n\n if($(navClass).length == 0)return;\n $(navClass).addClass('highlighted');\n}\n\n\nfunction hiLiteSubNavByTaxonomy(){\n $('#container div.general ul.nav li a').filter(function() {\n var htmlTax = taxonomy.name.replace(/&/g,\"&amp;\");\n var subnav = new RegExp('^ *'+taxonomy.name+' *$');\n var subnavHtml = new RegExp('^ *'+htmlTax+' *$');\n if(subnav.test($(this).html())){\n $(this).parents(\"li:first\").addClass('selected');\n } else if(subnavHtml.test($(this).html())){\n $(this).parents(\"li:first\").addClass('selected');\n }\n });\n}\n\nvar loadTimes = {}\ntimerCount = function(prop){\n if(typeof startTime == 'undefined'){\n startTime = 0;\n }\n var curTime = new Date().getTime();\n var elapsedTime = curTime - startTime;\n loadTimes[prop] = elapsedTime;\n}\n\ngetLoadTimes = function(){\n for(var timeStamp in loadTimes){\n $('#test_comments').append('<p>'+timeStamp+' = '+loadTimes[timeStamp]+' ms</p>')\n }\n}\n\n// OPA Ad functionality object\n/* see #1468 comments for more detail on usage */\nngsAdvertisingOPA = function(opts) {\n var o = this;\n o.opts = ((opts)?opts:{});\n o.setOption = function(opt,val) {\n if(typeof(o[opt])==\"undefined\") {\n o.defaults[opt]=val;\n }\n return o[opt]=val;\n }\n o.getOption = function(v) {\n return ((typeof(o[v])!=\"undefined\")?o[v]:((typeof(o.opts[v])!=\"undefined\")?o.opts[v]:o.defaults[v]));\n };\n o.defaults = {\n state: 'initializing',\n height: ((o.opts && o.opts.height)?o.opts.height:66),\n onCollapse: ((o.opts && o.opts.onCollapse)?o.opts.onCollapse:null),\n onCollapseComplete: ((o.opts && o.opts.onCollapseComplete)?o.opts.onCollapseComplete:null),\n collapseHeight: ((o.opts && o.opts.collapseHeight)?o.opts.collapseHeight:66),\n collapseDuration: ((o.opts && o.opts.collapseDuration)?o.opts.collapseDuration:750),\n onExpand: ((o.opts && o.opts.onExpand)?o.opts.onExpand:null),\n onExpandComplete: ((o.opts && o.opts.onExpandComplete)?o.opts.onExpandComplete:null),\n expandHeight: ((o.opts && o.opts.expandHeight)?o.opts.expandHeight:418),\n expandDuration: ((o.opts && o.opts.expandDuration)?o.opts.expandDuration:1250),\n container: ((o.opts && o.opts.container)?o.opts.container:(($('div.pushdown.advertisement').length>0)?$('div.pushdown.advertisement').get(0):null))\n };\n o.init = function(opts) {\n var opts = ((opts)?opts:o.defaults);\n for(var d in o.defaults) {\n o[d] = o.getOption(d);\n }\n for(var v in opts) {\n o[v] = o.getOption(v);\n }\n if(typeof(o.initCallback)!=\"undefined\") {\n o.initCallback();\n }\n o.setOption('state','initialized');\n return o;\n };\n o.collapse = function(opts) {\n if(o.container) {\n o.setOption('state','collapsing');\n if(o.onCollapse) {\n o.onCollapse();\n }\n $(o.container).animate(\n {'height':o.collapseHeight},\n o.collapseDuration,\n function() {\n o.setOption('state','collapsed');\n if(o.onCollapseComplete) {\n o.onCollapseComplete();\n }\n }\n );\n }\n };\n o.expand = function(opts) {\n if(o.container) {\n o.setOption('state','expanding');\n if(o.onExpand) {\n o.onExpand();\n }\n $(o.container).animate(\n {'height':o.expandHeight},\n o.expandDuration,\n function() {\n o.setOption('state','expanded');\n if(o.onExpandComplete) {\n o.onExpandComplete();\n }\n }\n );\n }\n };\n o.spoof = function() {\n _adModExpand = function(adO) {\n o.expand();\n $(adO).unbind('mouseover');\n $(adO).bind('click',function(){_adModCollapse(adO);});\n };\n _adModCollapse = function(adO) {\n o.collapse();\n $(adO).unbind('click');\n $(adO).bind('mouseover',function(){_adModExpand(adO);});\n };\n $(o.container).css({\n \"height\":o.collapseHeight,\n \"background\":\"transparent url(http://images.nationalgeographic.com/wpf/media-live/photologue/photos/2010/02/04/cache/40731_990x742.jpg) no-repeat top center\"\n });\n _adModExpand(o.container);\n };\n o.init();\n}\nisBlankAd = function(ad){\n // given an ad from the dom (ie: $('#kids_header div[id*=\"970x66\"]')[0])\n // or a string containing a src url of an image\n // return true if the ad is blank (1x1 image as clear pixel)\n var isBlank = true;\n var blank_url = /.*?google.*?/gi;\n\n if(typeof ad === \"string\"){\n // src of the image should match blank_url\n if(!ad.match(blank_url)) return false;\n }else{\n // verify dom element\n var $ad = $(ad);\n // ad must have two scripts and one a > image, that's 3 elements in total\n if($ad.children().length != 3) return false;\n // ad must have and image\n var $img = $ad.find('a > img');\n if($img.length <= 0) return false;\n // image should be 1x1\n if($img.attr('width') != 1 || $img.attr('height') != 1) return false;\n // the only element of the ad must be a > image\n if($img.parent()[0] != $ad.children()[2]) return false;\n // src of the image should match blank_url\n if(! $img.attr('src').match(blank_url) ) return false;\n }\n\n return isBlank;\n}\ncollapseEmptyHeaderAds = function(opts){\n\n // get specific ad units in the header by id, inspect their value for the blank ad\n // note: pushdown is never refreshable, so will always be able to determine it's contents\n // (not sure this is possible with iframe?)\n\n // short-term solution for Dart migration bug that started 4/2013\n // defined isBlankAd function to detect blank ads\n var clearAdFilename = \"common/i/presentation/clear\"; // 1x1_clear_pixel_placeholder.gif;\n\n var pushdownAd = ($('#navigation_tophat_container div[id*=\"970x66\"]') || [undefined])[0];\n if (typeof pushdownAd === \"undefined\")\n {\n \tpushdownAd = ($('#kids_header div[id*=\"970x66\"]') || [undefined])[0];\n }\n var leaderboardAd = ($('#navigation_tophat_container div[id*=\"728x90\"]') || [undefined])[0];\n if (typeof leaderboardAd === \"undefined\")\n {\n \tleaderboardAd = ($('#kids_header div[id*=\"728x90\"]') || [undefined])[0];\n }\n var secondaryAd = ($('#navigation_tophat_container div[id*=\"257x90\"]') || [undefined])[0];\n var kidsSecondaryAd = ((document.getElementById(\"advertisingModule235x90\") && document.getElementById(\"advertisingModule235x90\").length > 1)?document.getElementById(\"advertisingModule235x90\")[0]:((document.getElementById(\"advertisingModule235x90\"))?document.getElementById(\"advertisingModule235x90\"):null));\n\n var foundEmptyAd = 0;\n if (pushdownAd) {\n var html = pushdownAd.innerHTML;\n if (isBlankAd(pushdownAd) ||(html.indexOf(clearAdFilename) != -1)) {\n foundEmptyAd = 1;\n } else /* found real pushdown ad, instantiate an 'ngsAdvertisingOPA' object */ {\n opa_ad = new ngsAdvertisingOPA();\n }\n }\n if (kidsSecondaryAd && $(kidsSecondaryAd).find('iframe').length > 0 && $($(kidsSecondaryAd).find('iframe').get(0).contentWindow.document).find('img').length > 0) {\n var ad_img_src = $($(kidsSecondaryAd).find('iframe').get(0).contentWindow.document).find('img').attr('src');\n if (isBlankAd(ad_img_src)||(ad_img_src.indexOf(clearAdFilename) != -1)) {\n $(kidsSecondaryAd).remove();\n kidsSecondaryAd = null;\n }\n }\n\n // set the kidsSecondaryAd to 'secondaryAd' for the efficiency of the logic below\n secondaryAd = ((!secondaryAd && kidsSecondaryAd) ? kidsSecondaryAd : secondaryAd);\n\n // if pushdown is blank, show leaderboard and secondary/sponsor ad -- remove pushdown\n // otherwise show pushdown -- remove leaderboard and/or sponsor ad (e.g., remove both leaderboard and sponsor ad when present)\n inactiveAdModuleDivs = ((foundEmptyAd)?[pushdownAd.parentNode]:((pushdownAd && leaderboardAd)?[leaderboardAd.parentNode,((pushdownAd && secondaryAd)?secondaryAd.parentNode:null)]:[((pushdownAd && secondaryAd)?secondaryAd.parentNode:null)]));\n for(var inI=0;inI<inactiveAdModuleDivs.length;inI++) {\n if(inactiveAdModuleDivs[inI]!=null) {\n inactiveAdModuleDivs[inI].parentNode.removeChild(inactiveAdModuleDivs[inI]);\n }\n }\n activeAdModuleDivs = ((foundEmptyAd || !pushdownAd)?[((leaderboardAd)?leaderboardAd.parentNode:null),((secondaryAd)?secondaryAd.parentNode:null)]:[((pushdownAd)?pushdownAd.parentNode:null)]);\n for(var inI=0;inI<activeAdModuleDivs.length;inI++) {\n if(activeAdModuleDivs[inI]!=null) {\n var aM = activeAdModuleDivs[inI];\n // expand the ad parent container element before showing the ad\n $(activeAdModuleDivs).each(function() { $(this).removeClass('hidden'); });\n }\n } /* if no ads are found, fallback and remove the 'hidden' status on existing ads (when found) */\n if(!pushdownAd && !leaderboardAd && !secondaryAd) {\n $('div.leaderboard').removeClass('hidden');\n $('div.secondary_ad').removeClass('hidden');\n }\n else {\n if(foundEmptyAd==0 && pushdownAd) {\n // spoof a pushdown when the 'spoof_opa' query string/GET param is present - NOTE: will remove a real pushdown ad if one exists\n if(window.location && window.location.search && /\\bspoof_opa\\b/.test(window.location.search)) {\n opa_001 = new ngsAdvertisingOPA();\n opa_001.spoof();\n }\n }\n }\n\n // for kids, need to remove div kids_tophat_row1 when it's a pushdown ad and center the ad\n if (!foundEmptyAd){\n var kids_tophat_row1 = ($('#kids_tophat_row1') || [undefined])[0];\n if (kids_tophat_row1){\n kids_tophat_row1.parentNode.removeChild(kids_tophat_row1);\n $('#kids_header .advertisement').addClass('kids_pushdown');\n }\n }\n}\n\n\nvar rssFeeds = [];\naddRSSFeed = function(rssObj){\n rssFeeds.push(rssObj);\n}\n\nloadRssReaders = function(){\n if(typeof($.jGFeed)==\"undefined\"){\n $('div.rssReader').remove();\n return;\n }\n var totFeeds = rssFeeds.length;\n for(var i=0;i<totFeeds;i++){\n var itemCount = rssFeeds[i].count;\n var resultsDiv = rssFeeds[i].div;\n var rssURL = rssFeeds[i].feed;\n\n $.jGFeed(rssURL,\n function(feeds){\n if(!feeds){\n $('#'+resultsDiv).append(\"<p>ERROR LOADING RSS FEED</p>\");\n return false;\n }\n $('#rss_loading').remove();\n var html = '<ul class=\"bullets\">';\n for(var j=0; j<itemCount; j++){\n var item = feeds.entries[j];\n html += '<li><a href=\"'+item.link+'\">'+item.title+'</a>'+'</li>';\n }\n html += '</ul>';\n $('#'+resultsDiv).append(html);\n }, itemCount);\n }\n}\n\nvar factsBoxes = [];\naddFactsBox = function(factObj){\n factsBoxes.push(factObj);\n}\n\nloadFactsBoxes = function(){\n var totBoxes = factsBoxes.length;\n\n for(var i=0;i<totBoxes;i++){\n factsBoxes[i].get_data();\n }\n}\n\n//wrapper function to make NGM Flash interactives refresh ads and register page views\nfunction ngmPageView(){\n ngsPageView();\n}\n\ncheckKidsSponsor = function(){\n return false;\n var blankAdFilename = \"817-grey.gif\";\n var clearAdFilename = \"1x1_clear_pixel_placeholder.gif\";\n\n if($(\"#advertisingModule210x50\").find(\"iframe\").get(0) != undefined){\n\n var sponsor_img_src = $($(\"#advertisingModule210x50\").find(\"iframe\").get(0).contentWindow.document).find(\"img\").attr('src');\n\n if ((sponsor_img_src != undefined&&( sponsor_img_src.indexOf(blankAdFilename) != -1)||(sponsor_img_src.indexOf(clearAdFilename) != -1) ) ) {\n $(\"#sponsorAd\").addClass('hidden');\n } else {\n $(\"#sponsorAd\").removeClass('hidden');\n }\n } else {\n $(\"#sponsorAd\").removeClass('hidden');\n }\n}\n\n/* header search box behavior */\n$(document).mouseup(function (e) {\n var $container = $(\"#global_search .field\");\n if ($container.has(e.target).length === 0) {\n $container.find(\"#header_search_input\").removeClass(\"search_focus\");\n $container.find(\"#search_type\").hide();\n }\n});\n\n$(\"#global_search .field\").live(\"focusin\", function(){\n var $this = $(this);\n $(\"#header_search_input\").addClass(\"search_focus\");\n $this.find(\"#search_type\").show();\n $this.find(\"#search_type\").css({\"visibility\": \"visible\"});\n});\n\n$(\"#search_type li\").live(\"mousedown\", function(){\n var $this = $(this);\n $this.parent().find(\"li\").removeClass(\"selected\");\n $this.addClass(\"selected\");\n $(\"#global_search\").attr(\"action\", $this.attr(\"data-url\"));\n $(\"#global_search\").submit(); //trigger submit on click.\n});\n\n//Search toggle\n$('.search_option span.video_search_link').live('click', function() {\n $(\"#global_search\").attr(\"action\", $(\"#global_search #search_type\").find(\"li:eq(1)\").attr(\"data-url\"));\n $(\"#global_search #header_search_input\").val($(\".searched_form input[type='text']\").val());\n $(\"#global_search\").submit();\n});\n" }, { "alpha_fraction": 0.5552977323532104, "alphanum_fraction": 0.5583913326263428, "avg_line_length": 21.6842098236084, "blob_id": "d51117658d1fa157ef32d473f44c2a08790d64f8", "content_id": "a321c95abece93ffec2d29795f08d0738a388a76", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1293, "license_type": "permissive", "max_line_length": 126, "num_lines": 57, "path": "/servers/demo-scaleout/html/boston.tmp/bcom_textsize_supersizeMe.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "function fontsizeup() {\n active = getActiveStyleSheet();\n switch (active) {\n case 'A-' : \n setActiveStyleSheet('A');\n break;\n case 'A' : \n setActiveStyleSheet('A+');\n break;\n case 'A+' : \n setActiveStyleSheet('A++');\n break;\n case 'A++' :\n break;\n default :\n setActiveStyleSheet('A+');\n break;\n }\n}\n\nfunction fontsizedown() {\n active = getActiveStyleSheet();\n switch (active) {\n case 'A++' : \n setActiveStyleSheet('A+');\n break;\n case 'A+' : \n setActiveStyleSheet('A');\n break;\n case 'A' : \n setActiveStyleSheet('A-');\n break;\n case 'A-' : \n break;\n default :\n setActiveStyleSheet('A-');\n break;\n }\n}\n\nfunction setActiveStyleSheet(title) {\n var i, a, main;\n for(i=0; (a = document.getElementsByTagName(\"link\")[i]); i++) {\n if(a.getAttribute(\"rel\").indexOf(\"style\") != -1 && a.getAttribute(\"title\")) {\n a.disabled = true;\n if(a.getAttribute(\"title\") == title) a.disabled = false;\n }\n }\n}\n\nfunction getActiveStyleSheet() {\n var i, a;\n for(i=0; (a = document.getElementsByTagName(\"link\")[i]); i++) {\n if(a.getAttribute(\"rel\").indexOf(\"style\") != -1 && a.getAttribute(\"title\") && !a.disabled) return a.getAttribute(\"title\");\n }\n return null;\n}\n" }, { "alpha_fraction": 0.5987097024917603, "alphanum_fraction": 0.6116129159927368, "avg_line_length": 23.21875, "blob_id": "0017601d1cf7201b4ad61bbd104cf78e354303d2", "content_id": "cd93444a6879bb0f5e38deaf474c8319d7ba40ff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 775, "license_type": "permissive", "max_line_length": 77, "num_lines": 32, "path": "/servers/demo-scaleout/html/gen_file_response.php", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "<?php\n$chunksize = 128;\nif (isset($_GET['chunksize'])){\n $chunksize = (int)$_GET['chunksize'];\n}\n$sleeptime = 10;\nif (isset($_GET['sleeptime'])){\n $sleeptime = (int)$_GET['sleeptime'];\n}\n$filename = \"/usr/share/nginx/www/script.py\";\nif (isset($_GET['filename'])) {\n $filename = $_GET['filename'];\n}\n\n$file_contents = file_get_contents($filename);\n$file_len = strlen($file_contents);\n$chunkcount = $file_len / $chunksize;\n$last_chunk_sz = $file_len % $chunksize;\n$chunk_i = 0;\n\twhile ($chunk_i < $chunkcount)\n\t{\n $to_send = substr($file_contents, $chunk_i * $chunksize, $chunksize);\n\t\techo $to_send;\n\t\tflush();\n\t\t$chunk_i++;\n\t\tsleep($sleeptime/1000);\n\t}\n \n$to_send = substr($file_contents, $chunk_i * $chunksize, $last_chunk_sz);\necho $to_send;\nflush();\n?>\n" }, { "alpha_fraction": 0.6346922516822815, "alphanum_fraction": 0.6586730480194092, "avg_line_length": 20.568965911865234, "blob_id": "cfbeb8d8e79a259820fb4134e1790d24f8baeab5", "content_id": "8f7d6b1a42f26359611f8b2fd10b6dab3b354680", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1251, "license_type": "permissive", "max_line_length": 121, "num_lines": 58, "path": "/client/demo-waf/startup.py", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport subprocess\nfrom multiprocessing import Process\nimport os\nimport time\n\n\n\n#----- USE ENV VARS TO FIND VS IPs\n#----- os.environ\n\n\n\n\n#----- Add VS FQDN entries\n#cmd = 'echo \"169.254.10.3 waf.demovip.avi.local\" >> /etc/hosts'\n#result = subprocess.check_output(cmd, shell=True)\n#time.sleep(1)\n\n\n#----- Add traffic shaping\ncmd = '/bin/bash /opt/avi/client/netem'\nresult = subprocess.check_output(cmd, shell=True)\ntime.sleep(1)\n\n\n#----- Add additional interface IPs\ncmd = '/etc/init.d/networking stop; /etc/init.d/networking start'\nresult = subprocess.check_output(cmd, shell=True)\ntime.sleep(1)\n\n\n\n\n\n\nscript_list = [\n '/usr/bin/python /opt/avi/client/vs_demo/brokenlink_vs.py 169.254.10.1 >> /opt/avi/client/vs_demo/brokenlink_vs.log',\n '/usr/bin/python /opt/avi/client/vs_demo/ssl_traffic.py 169.254.10.1 >> /opt/avi/client/vs_demo/ssl_traffic.log',\n '/usr/bin/python /opt/avi/client/waf/waf_traffic.py >> /opt/avi/client/waf/waf_traffic.log'\n ]\n\n\ndef run_script(script):\n result = subprocess.check_output(script, shell=True)\n\n\n\n\nwhile True:\n proc = []\n for s in script_list:\n p = Process(target = run_script, args = (s,))\n p.start()\n proc.append(p)\n for p in proc:\n p.join()\n" }, { "alpha_fraction": 0.6411290168762207, "alphanum_fraction": 0.6572580933570862, "avg_line_length": 15.466666221618652, "blob_id": "0657a571fd12f295da409a0b7688e1d6a7d061f0", "content_id": "1bcdda040beabb95546bd0b93ef392d1dacf1c8c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 248, "license_type": "permissive", "max_line_length": 38, "num_lines": 15, "path": "/servers/demo-scaleout/html/script.py", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "import fileinput\nimport os\nimport subprocess\n\n\nfor line in fileinput.input(\"v1.txt\"):\n\tsp = line.split('?')\n\tln = line.rsplit()\n\tprint ln[0]\n\tmv_file = 'mv %s %s' %(ln[0], sp[0])\n\tprint mv_file\n\tsubprocess.call(mv_file, shell=True)\n\n\nprint 'done'\n\n" }, { "alpha_fraction": 0.5418946146965027, "alphanum_fraction": 0.5617621541023254, "avg_line_length": 28.43220329284668, "blob_id": "084a465cff6a4da392c187b6bef292273afa3a0b", "content_id": "eb84cd75d438028d45fb6c7f6cee91c4eefdb705", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3473, "license_type": "permissive", "max_line_length": 123, "num_lines": 118, "path": "/servers/demo-scaleout/html/nyc-4/urilist.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "/*\n$Id: urilist.js 103281 2012-07-11 16:14:19Z konige $\n(c) 2008 The New York Times Company\n*/\n\nvar TimesPeople = TimesPeople || {};\n\nTimesPeople.URIList = {\n\n allowedHosts: {\n 'www.nytimes.com': 1,\n 'nytimes.com': 1,\n 'community.nytimes.com': 1,\n 'elections.nytimes.com': 1,\n 'events.nytimes.com': 1,\n 'movies.nytimes.com': 1,\n 'movies2.nytimes.com': 1,\n 'my.nytimes.com': 1,\n 'politics.nytimes.com': 1,\n 'tech2.nytimes.com': 1,\n 'tech.nytimes.com': 1,\n 'travel.nytimes.com': 1,\n 'travel2.nytimes.com': 1,\n 'topics.nytimes.com': 1,\n 'theater.nytimes.com': 1,\n 'jobmarket.nytimes.com': 1,\n 'projects.nytimes.com': 1,\n 'prototype.nytimes.com': 1,\n 'query.nytimes.com': 1,\n 'health.nytimes.com': 1,\n 'timesmachine.nytimes.com': 1,\n 'timespeople.nytimes.com': 1,\n 'www.sea1.nytimes.com': 1,\n 'tv.nytimes.com': 1,\n 'nyt.com': 1,\n 'www.nyt.com': 1,\n 'oscars.nytimes.com': 1,\n 'documents.nytimes.com': 1,\n 'ncaabracket.nytimes.com': 1,\n 'submit.nytimes.com': 1,\n 'global.nytimes.com': 1,\n 'video.nytimes.com': 1,\n 'video.on.nytimes.com': 1,\n 'dealbook.nytimes.com': 1\n },\n\n allowedHostsPatterns: [\n /.*\\.blogs\\.nytimes\\.com/\n ],\n\n deniedURIs:[\n /.*?glogin.*/, /.*?\\/auth\\/login.*/, /.*?gst\\/signout.*/, /.*?pagewanted=print.*/, /.*?pagemode=print.*/,\n /.*?\\/style\\/t\\/.*/, /.*?archive\\/pdf.*/, /.*?markets.on.nytimes.com.*/,\n /.*?\\/learning.nytimes.com.*/, /.*?\\/membercenter.*/, /.*?\\/mem\\/.*/, /.*?\\/gst\\/forgot.*/, /.*?\\/gst\\/emailus.*/,\n /.*?\\/gst\\/unsub.*/, /.*?\\/gst\\/regi.*/, /.*?\\/regi.*/, /.*?\\/ref\\/crosswords\\/setpuzzle.*/,\n /.*?\\/gst\\/mostblogged.*/, /.*?\\/gst\\/mostsearched.*/, /.*?\\/gst\\/mostemailed.*/, /.*?\\/gst\\/mostpopular.*/,\n /.*?\\/marketing\\/.*/, /.*?jobmarket.nytimes.com.*/, /.*?\\/packages\\/html\\/style\\/.*?/,\n /.*?\\/gst\\/litesub_insert.*/, /.*?\\/ref\\/classifieds\\/.*?/, /.*?\\/gst\\/shopping_cart.*/,\n /.*?select.nytimes.com.*/\n ],\n\n deniedMetaTags:[\n {\"PST\": \"Audio Slideshow\"},\n {\"TimesPeople\": \"disallow\"}\n ],\n\n deniedPlatforms: [\n /Android|dream|AppleWebKit\\/41|Opera/\n ],\n\n allowsCurrentPlatform: function() {\n for (var i = 0, pattern; pattern = this.deniedPlatforms[i]; i++) {\n if (pattern.test(navigator.userAgent)) {return false;}\n };\n return true;\n },\n\n allowsCurrentHost: function() {\n if (NYTD.env == 'staging' || NYTD.env == 'development') {\n return true;\n }\n else {\n if (this.allowedHosts[window.location.host]) {\n return true;\n }\n else {\n for (var i = 0, pattern; pattern = this.allowedHostsPatterns[i]; i++) {\n if (pattern.test(window.location.host)) return true;\n else return false;\n }\n }\n }\n },\n\n allowsCurrentType: function() {\n for (var i = 0, pair; pair = this.deniedMetaTags[i]; i++) {\n for(var key in pair) {\n var matches = document.getElementsByName(key);\n for (var j = 0, match; match = matches[j]; j++) {\n if(match.content == pair[key]) {return false;}\n }\n }\n }\n return true;\n },\n\n allowsCurrentURI: function() {\n for (var i = 0, pattern; pattern = this.deniedURIs[i]; i++) {\n if (pattern.test(window.location.href)) {return false;}\n };\n return true;\n },\n\n allowsCurrentPage: function() {\n return this.allowsCurrentPlatform() && this.allowsCurrentHost() && this.allowsCurrentURI() && this.allowsCurrentType();\n }\n\n};\n" }, { "alpha_fraction": 0.5748031735420227, "alphanum_fraction": 0.6929134130477905, "avg_line_length": 24.600000381469727, "blob_id": "d5b2651f481abebf08aaa1bf5e14dd2fb3aac10e", "content_id": "12a2162656054958148654845d6702a85ed87674", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 127, "license_type": "permissive", "max_line_length": 60, "num_lines": 5, "path": "/servers/demo-scaleout/html/start_node.sh", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "#!/bin/bash\ncd /usr/share/nginx/www\n\n#PORT=7777 IP=10.10.116.12 supervisor -w delay.js delay.js &\nPORT=$2 IP=$1 node delay.js &" }, { "alpha_fraction": 0.4825657904148102, "alphanum_fraction": 0.5980263352394104, "avg_line_length": 48.032257080078125, "blob_id": "305d91e16c136abfb8594641bc50a7b830548d4a", "content_id": "9c3336bd5989302008cdde4b3caa621424b7157c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3040, "license_type": "permissive", "max_line_length": 207, "num_lines": 62, "path": "/client/demo-waf/vs_demo/ssl_traffic.py", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport time\nimport subprocess\nimport sys\nimport traceback\nfrom datetime import datetime\n\n\n\nip_list = [\"161.98.255.1\", \"37.60.63.2\", \"206.223.191.1\", \"23.26.110.2\", \"27.113.239.2\", \"42.97.255.1\", \"132.247.255.2\", \"14.192.95.1\", \"37.16.63.1\", \"49.213.31.2\", \"41.67.128.1\", \"27.97.1.2\"]\nvs = sys.argv[1]\n\n\niphone = '\"Mozilla/5.0 (iPhone; CPU iPhone OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B206 Safari/7534.48.3\"'\nchrome = '\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36\"'\nfirefox = '\"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0\"'\nie = '\"Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko\"'\nipad = '\"Mozilla/5.0(iPad; U; CPU OS 4_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8F191 Safari/6533.18.5\"'\n\n#iphone = \"\\\"Mozilla\\/5.0 (iPhone CPU iPhone OS 5_1_1 like Mac OS X) AppleWebKit\\/534.46 (KHTML, like Gecko) Version/5.1 Mobile\\/9B206 Safari\\/7534.48.3\\\"\"\n#chrome = \"\\\"Mozilla\\/5.0 (Macintosh Intel Mac OS X 10_9_2) AppleWebKit\\/537.36 (KHTML, like Gecko) Chrome\\/34.0.1847.131 Safari\\/537.36\\\"\"\n#firefox = \"\\\"Mozilla\\/5.0 (Windows NT 6.1 WOW64 rv:29.0) Gecko\\/20100101 Firefox\\/29.0\\\"\"\n#ie = \"\\\"Mozilla\\/5.0 (Windows NT 6.3 WOW64 Trident\\/7.0 Touch rv:11.0) like Gecko\\\"\"\n#ipad = \"\\\"Mozilla/5.0(iPad U CPU OS 4_3 like Mac OS X en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8F191 Safari/6533.18.5\\\"\"\n\n\nurl1 = \"http://\"+vs+\"/imgs/logo.png\"\nurl2 = \"https://\"+vs+\"/\"\nurl3 = \"http://\"+vs+\"/imgs/conversion.js\"\nurl4 = \"https://\"+vs+\"/imgs/header.png\"\nurl5 = \"https://\"+vs+\"/assets/avi.webm\"\nurl6 = \"https://\"+vs+\"/cnn.html\"\nurl7 = \"https://\"+vs+\"/natgeo.html\"\n\n\n\nwhile True:\n print '-----> STARTING NEW LOOP'\n for ip in ip_list:\n try:\n print \"<<<<< Client IP: \"+ip+\" \\n\\n\"\n curl = \"curl --interface \"+ip+\" -s -L --ciphers \\'AES128-GCM-SHA256\\' -k -A \"+chrome+\" \"+url1+\" -o tmp\"\n print curl+ \"\\n\\n\"\n result = subprocess.check_output(curl, shell=True)\n time.sleep(2)\n curl = \"curl --interface \"+ip+\" -s -L --ciphers \\'ECDHE-ECDSA-AES256-SHA\\' -k -A \"+chrome+\" \"+url5+\" -o tmp\"\n print curl+ \"\\n\\n\"\n result = subprocess.check_output(curl, shell=True)\n time.sleep(2)\n curl = \"curl --interface \"+ip+\" -s -L --tlsv1.1 -k -A \"+chrome+\" \"+url3+\" -o tmp\"\n print curl+ \"\\n\\n\"\n result = subprocess.check_output(curl, shell=True)\n time.sleep(2)\n curl = \"curl --interface \"+ip+\" -s -L --tlsv1.0 -k -A \"+chrome+\" \"+url4+\" -o tmp\"\n print curl+ \"\\n\\n\"\n result = subprocess.check_output(curl, shell=True)\n time.sleep(2)\n except:\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+exception_text)\n print 'ERROR - moving on to next IP'\n" }, { "alpha_fraction": 0.41383013129234314, "alphanum_fraction": 0.42367592453956604, "avg_line_length": 46.1120491027832, "blob_id": "14ab9e1c1ae1c8158c17a077e9ac68de0617e555", "content_id": "9dbecfbc0f5501eeba30227327307ceaf8c947a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 39103, "license_type": "permissive", "max_line_length": 203, "num_lines": 830, "path": "/servers/demo-scaleout/html/natgeo.old/analytics-cb1382965721.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "window.analytics = window.analytics || {ga: {}};\nwindow.analytics.ga = window.analytics.ga || {};\n\nif( !Object.prototype.hasOwnProperty.call( String.prototype, 'endsWith'))\n String.prototype.endsWith = function(str){\n var lastIndex = this.lastIndexOf(str);\n return (lastIndex != -1) && (lastIndex + str.length == this.length);\n };\n \n(function(window, document, $, undefined) {\n \n //getSiteName reduces a either the documents url or a given url to the top most site name.\n //i.e. photography.nataionalgeographic.com would return nationalgeographic.com,\n // mysubdomain.mywebsite.co.uk would return mywebsite.co.uk.\n var getSiteName = function (url) {\n var hostName = url || window.location.hostname,\n hostNamePosFromEnd;\n //Don't want any http:// or similar stuff.\n hostName = hostName.replace(/^\\w+?:\\d*?\\/\\//, '');\n\n //Drop any path info from url.\n hostName = hostName.split('/')[0];\n hostName = hostName.split('.');\n hostNamePosFromEnd = (hostName.length >= 2) ? ((hostName[hostName.length - 2].length === 2) ? 3 : 2) : 1;\n while (hostName.length > hostNamePosFromEnd) {\n hostName.shift();\n }\n return hostName.join('.');\n };\n var defaultSiteName = getSiteName();\n \n allReady = function (window, document, $, a) {\n 'use strict';\n \n var debug = !!window.location.search.match('debug'),\n log = function (msg) {\n if (debug) {\n if (window.console && window.console.log) {\n window.console.log(msg);\n }\n }\n },\n track = function (item) {\n window._gaq.push(item);\n log(item);\n \n },\n root = document.documentElement,\n \n //Utilities\n isHTTPS = !!document.location.protocol.match('https:'),\n isHTTP = !!document.location.protocol.match('http:'),\n serialize = function (obj) {\n var str = [],\n p;\n for (p in obj) {\n if (obj.hasOwnProperty(p)) {\n str.push(encodeURIComponent(p) + \"=\" + encodeURIComponent(obj[p]));\n }\n }\n return str.join(\"&\");\n },\n addEvent = function (type, el, func) {\n var oldOn,\n onContainer;\n if (el.addEventListener) {\n el.addEventListener(type, func, false);\n } else if (el.attachEvent) {\n el.attachEvent('on' + type, func);\n } else {\n if (typeof el['on' + type] === 'function') {\n oldOn = el['on' + type];\n onContainer = function (oldOn, newOn) {\n if (typeof oldOn === 'function') {\n oldOn();\n }\n newOn();\n };\n el['on' + type] = onContainer;\n } else {\n el['on' + type] = func;\n }\n }\n },\n addScript = function (src, cb, async) {\n var s = document.createElement('script');\n if (typeof cb === 'function') {\n addEvent('load', s, cb);\n }\n s.src = src;\n s.async = (async === undefined) ? true : async;\n root.insertBefore(s, root.childNodes[0]);\n return s;\n },\n thinmint = {\n get: function (sKey) {\n if (!sKey || !this.has(sKey)) { return null; }\n return window.unescape(document.cookie.replace(new RegExp(\"(?:^|.*;\\\\s*)\" + window.escape(sKey).replace(/[\\-\\.\\+\\*]/g, \"\\\\$&\") + \"\\\\s*\\\\=\\\\s*((?:[^;](?!;))*[^;]?).*\"), \"$1\"));\n },\n set: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {\n if (!sKey || /^(?:expires|max\\-age|path|domain|secure)$/i.test(sKey)) { return; }\n var sExpires = \"\";\n if (vEnd) {\n switch (vEnd.constructor) {\n case Number:\n sExpires = vEnd === Infinity ? \"; expires=Tue, 19 Jan 2038 03:14:07 GMT\" : \"; max-age=\" + vEnd;\n break;\n case String:\n sExpires = \"; expires=\" + vEnd;\n break;\n case Date:\n sExpires = \"; expires=\" + vEnd.toGMTString();\n break;\n }\n }\n document.cookie = window.escape(sKey) + \"=\" + window.escape(sValue) + sExpires + (sDomain ? \"; domain=\" + sDomain : \"\") + (sPath ? \"; path=\" + sPath : \"\") + (bSecure ? \"; secure\" : \"\");\n },\n remove: function (sKey, sPath) {\n if (!sKey || !this.has(sKey)) { return; }\n document.cookie = window.escape(sKey) + \"=; expires=Thu, 01 Jan 1970 00:00:00 GMT\" + (sPath ? \"; path=\" + sPath : \"\");\n },\n has: function (sKey) {\n return (new RegExp(\"(?:^|;\\\\s*)\" + window.escape(sKey).replace(/[\\-\\.\\+\\*]/g, \"\\\\$&\") + \"\\\\s*\\\\=\")).test(document.cookie);\n },\n keys: /* optional method: you can safely remove it! */ function () {\n var aKeys = document.cookie.replace(/((?:^|\\s*;)[^\\=]+)(?=;|$)|^\\s*|\\s*(?:\\=[^;]*)?(?:\\1|$)/g, \"\").split(/\\s*(?:\\=[^;]*)?;\\s*/);\n for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = window.unescape(aKeys[nIdx]); }\n return aKeys;\n }\n },\n i,\n iLen,\n csScript = (function () {\n window._comscore = window._comscore || [];\n window._comscore.push({ c1: \"2\", c2: \"3005368\" });\n return addScript((isHTTPS ? 'https://s' : 'http://') + 'b.scorecardresearch.com/beacon.js?');\n })(),\n \n //Google Analytics\n gaScript = document.createElement('script'),\n //gpt = document.createElement('script'),\n \n //Omniture\n omnitureScript = (function () {\n var src = (window.staticURL || (isHTTPS ? \"https://www-s.nationalgeographic.com/wpf/\" : \"http://images.nationalgeographic.com/wpf/\")) + 'sites/common/j/omniture_code.js';\n return addScript(src);\n })(),\n\n //Gigya Google Analytics integration\n gigyaIntScript = addScript((isHTTPS ? 'https://cdns' : 'http://cdn') + '.gigya.com/js/gigyaGAIntegration.js'),\n \n //Survey Monkey\n surveyMonkey = (function () {\n if (isHTTP && window.location.hostname === \"environment.nationalgeographic.com\") {\n var isGEC = !!(window.location.pathname.match('/environment/energy/great-energy-challenge/')),\n smGECid = 'zsmmDV05_2fJzMmJDaTkjvfg_3d_3d',\n smid = 'j3Pcrw2nwpcrRWelX96W7w_3d_3d',\n basePath = 'http://www.surveymonkey.com/jsPop.aspx',\n path = basePath + '?sm=' + ((isGEC) ? smGECid : smid);\n \n return addScript(path);\n }\n })(),\n \n qcScript = (function () {\n var qs;\n //only loads for http\n if (isHTTP) {\n qs = addScript('http://edge.quantserve.com/quant.js');\n addEvent('load', qs, function () {\n if(typeof window.quantserve === 'function') {\n window._qacct=\"p-c8v-iKfiW8tsY\";\n window.quantserve();\n }\n });\n return qs;\n }\n })();\n \n //Google Analytics\n window._gaq = window._gaq || [];\n //The ga._gaEarlyQ in the analytics object allows for items to be pushed the the _gaq before the _trackPageView call\n a.ga._gaEarlyQ = a.ga._gaEarlyQ || [];\n track(['_setAccount', a.ga.accountID || 'UA-28236326-1']);\n track(['_setDomainName', defaultSiteName]);\n track(['_setAllowLinker', true]);\n track(['_addIgnoredRef', 'nationalgeographic']);\n \n (function(){\n var vidTitleElem = document.getElementById('natgeov-vtitle'),\n vidTitle = (vidTitleElem) ? (vidTitleElem.textContent || vidTitleElem.innerText) : undefined;\n \n if (vidTitle) {\n vidTitle = vidTitle.trim();\n track(['_setCustomVar', 4, 'videoTitle', vidTitle]);\n }\n }());\n (function (_gaq) {\n var sess = thinmint.get('memSess'),\n parts;\n \n if (sess) {\n parts = sess.split('|');\n track(['_setCustomVar', 3, 'isLoged', 'true', 3]);\n track(['_setCustomVar', 8, 'userToken', parts[0], 3]);\n track(['_setCustomVar', 9, 'memberLevel', parts[1], 3]);\n } else {\n track(['_setCustomVar', 3, 'isLoged', 'false', 3]);\n }\n })(window._gaq);\n \n for (i = a.ga._gaEarlyQ.length - 1; i >= 0; i--) {\n track(a.ga._gaEarlyQ[i]);\n }\n\n //The ga.trackPageViewItem in the analytics object allows custom attributes to be passed to the _trackPageView method.\n track(a.ga.trackPageViewItem || ['_trackPageview']);\n gaScript = addScript((isHTTPS ? \"https://ssl\" : \"http://www\") + '.google-analytics.com/ga.js');\n \n // Login/out events\n $(window).on('login',function(e) {\n track(['_trackEvent', 'Membership', 'General', 'Sign In']);\n });\n \n $(window).on('logout',function(e) {\n track(['_trackEvent', 'Membership', 'General', 'Log Out']);\n });\n \n // Downloads\n $(function () {\n $('#container').on('click', 'a', function (e) {\n var $this = $(this),\n //Shortcircut flag for determining if a link is a download, but can't count on it.\n isDownload = $this.hasClass('download'),\n downloadType = '';\n if ($this.hasClass('pdf') || (($this.attr('href') !== undefined) && $this.attr('href').match('.pdf'))) {\n log('downloading pdf');\n isDownload = true;\n downloadType = 'pdf';\n } else if ($this.hasClass('wallpaper')) {\n log('downloading wallpaper');\n isDownload = true;\n downloadType = 'wallpaper';\n } else if (isDownload){\n log('downloading file');\n downloadType = 'file';\n }\n if (isDownload) {\n track(['_trackEvent', 'engage', 'download: ' + downloadType, $(this).attr('title') || document.title]);\n }\n });\n }());\n \n //Event Tracking\n (function () {\n var videoDuration; //Used for Video Tracking progress tracking\n //Outbound links\n $('body').on('click', 'a[href^=\"http\"]:not([href*=\"' + defaultSiteName + '\"])', function (e) {\n var natGeoDomains = [\n 'nationalgeographicexpeditions.com',\n 'scienceblogs.com',\n 'buysub.com',\n 'ngtravelerseminars.com',\n 'greatenergychallengeblog.com',\n '360energydiet.com',\n 'nationalgeographic.org',\n 'nationalgeographic.com',\n 'ngstudentexpeditions.com',\n 'natgeotakeaction.org',\n 'customersvc.com',\n 'killinglincolnconspiracy.com',\n 'explorethe80s.com',\n 'natgeobraingames.com',\n 'nationalgeographic.it',\n 'survivetheblackout.com',\n 'kennedyandoswald.com'\n ],\n targetA = this;\n //NatGeo TLDs\n if ($.inArray(getSiteName(targetA.href), natGeoDomains) >= 0) {\n track(['_link', targetA.href]);\n //Third Party TLDs\n } else {\n track(['_trackEvent', 'engagement', 'outbound-click', targetA.title || getSiteName(targetA.href)]);\n }\n });\n \n //Nav Events\n (function () {\n $('#navigation_mainB .primary_nav, #site_nav > ul').on('click', 'a', function (e) {\n var $this = $(e.target),\n $thisParentNav = $this.parentsUntil('.primary_nav', '.primary_nav > li').eq(0),\n parentNav = $thisParentNav.children('a').eq(0).text();\n \n //this is for clicks on subnav items\n if ($thisParentNav.length) {\n track(['_trackEvent', 'main-nav', parentNav, $this.text().trim()]);\n \n //clicks on primary nav items.\n } else {\n track(['_trackEvent', 'main-nav', 'home', $this.text().trim()]);\n }\n });\n }());\n \n // Floodlight Tags\n (function(awe){\n var pathname = awe.pathname,\n host = awe.host,\n FloodLightTags,\n FloodLightOptions,\n floodLightInstance;\n \n if(!pathname.endsWith('/')) {\n pathname = [pathname,'/'].join('');\n }\n \n /*\n * When this dataset is looped over, we first check for the right domain.\n *\n * If the domain doesn't match, everything falls back to\n * nationalgeographic.com\n *\n * Within the domain scope, the first match found is returned.\n */\n FloodLightOptions = {\n 'animals.nationalgeographic.com': {\n '^/animals/wild/animal-underworld/$':'natio040',\n '^/animals/big-cats/$':'natio634',\n '^/animals/big-cats/cause-an-uproar/episode-guide/$':'natio095',\n '^/animals/wild/built-for-the-kill/$':'natio606',\n '^/animals/wild/shows-deadly-60/$':'natio203',\n '^/animals/wild/dog-whisperer/$':'natio111',\n '^/animals/$':'natio708',\n '^/animals/wild/shows-incredible-dr-pol/$':'natio457',\n '^/animals/wild/events-penguin-palooza/$':'natio557',\n '^/animals/schedule/wild/$':'gibpn088',\n '^/animals/wild/events-shark-attack-experiment-live/$':'natio677',\n '^/animals/wild/shows-swamp-men/$':'natio667'\n },\n 'channel.nationalgeographic.com':{\n '^/channel/abandoned/$':'natio516',\n '^/channel/alaska-state-troopers/$':'natio907',\n '^/channel/american-colony-meet-the-hutterites/$' : 'natio574',\n '^/channel/american-gypsies/$':'natio319',\n '^/channel/american-weed/$' : 'natio510',\n '^/channel/americas-lost-treasures/': 'natio318',\n '^/channel/amish-out-of-order/$':'natio632',\n '^/channel/border-wars/$':'natio852',\n '^/channel/brain-games/$':'natio268',\n '^/channel/chasing-ufos/$':'natio226',\n '^/channel/doomsday-preppers/$':'natio169',\n '^/channel/drugs-inc/$':'natio597',\n '^/channel/explorer/$' : 'natio706',\n '^/channel/family-guns/$' : 'natio997',\n '^/channel/hard-time/$' : 'natio699',\n '^/channel/knights-of-mayhem/$':'natio681',\n '^/channel/the-last-days-of-osama-bin-laden/$':'natio143',\n '^/channel/locked-up-abroad/$':'natio465',\n '^/channel/meet-the-hutterites/$':'natio574',\n '^/channel/rocket-city-rednecks/$':'natio533',\n '^/channel/schedule/ngc/$':'natio428',\n '^/channel/taboo/$':'natio172',\n '^/channel/the-link/$' : 'natio531',\n '^/channel/the-truth-behind/$' : 'natio572',\n '^/channel/titanic-100-years/$' : 'qocse441',\n '^/channel/titanic/final-word-with-james-cameron$':'natio575',\n '^/channel/ultimate-factories/$' : 'natio607',\n '^/channel/untamed-americas/$':'natio395',\n '^/channel/wicked-tuna/$':'natio144',\n '^/channel/wild-justice/$':'natio208',\n '^/channel/witness-disaster/$' : 'natio202',\n '^/channel/$':'natio857',\n // Wild\n '^/wild/africas-deadliest/$' : 'natio768',\n '^/wild/animal-intervention/$':'natio780',\n '^/wild/dangerous-encounters/$' : 'natio064',\n '^/wild/outback-wrangler/$' : 'natio293',\n '^/wild/stranger-than-nature/$' : 'natio048',\n // Default\n '^/$':'natio517'\n },\n 'nationalgeographic.com':{\n '^/$':'natio411',\n '^/channel/$':'natio857',\n '^/animals/$':'natio708',\n '^/wild/tv-schedule$':'gibpn088',\n '^/animals/schedule/wild/$':'gibpn088',\n '^/animals/big-cats/cause-an-uproar/episode-guide/$':'natio095',\n '^/animals/big-cats/$':'natio634',\n '^/(channel|wild)/schedule/(daily|weekly)/$':'natio428'\n },\n 'ngm.nationalgeographic.com':{\n '/':'natio933'\n }\n };\n \n FloodLightTags = function(opts) {\n var instanceOpts = function(category) {\n return {\n '%(category)s':category,\n '%(bust)s':Math.random()*10000000000000\n };\n },\n optsSwitcher=function(opts) {\n if (Object.prototype.hasOwnProperty.call(opts, host)) {\n return opts[host];\n }\n return opts['nationalgeographic.com'];\n },\n optsPicker,\n self,\n src,\n f;\n\n this.opts = optsSwitcher(opts);\n optsPicker = function(opts) {\n var key;\n \n for(key in opts) {\n // Exclude unwanted properties.\n if( opts.hasOwnProperty(key)) {\n if( new RegExp(key).test(pathname)) {\n return instanceOpts(opts[key]);\n }\n }\n }\n return instanceOpts(opts['^/$']);\n };\n this.opts = optsPicker(this.opts);\n src = '//fls.doubleclick.net/activityi;src=3661093;type=indiv055;cat=%(category)s;ord=%(bust)s?';\n $.each( this.opts, function(index, item) {\n src=src.split(index).join(item);\n });\n\n f = $(\"<iframe/>\");\n f.attr('src',src);\n f.attr('width',1);\n f.attr('height',1);\n f.attr('frameborder',0);\n f.css('display','none');\n\n self = this;\n $('body').append(f);\n return this;\n };\n \n floodLightInstance = new FloodLightTags( FloodLightOptions);\n })(window.location);\n \n //Module Events\n \n //Social Connect Engagement\n (function () {\n $('#connect_with_us, .connect_ng').on('click', 'a', function(e) {\n var service = getSiteName($(this).attr('href')).split('.')[0];\n track(['_trackEvent', 'social', 'outbound-click', service]);\n });\n }());\n \n //Newsletter Engagemet\n (function () {\n var trackNewsletterEngagement = function (id) {\n var section = document.location.pathname.split('/')[1]; //cus pathname starts with \"/\"\n track(['_trackEvent', 'engage', 'newsletter', section + ':newsletter_' + id]);\n };\n //Flyout\n $('#newsletter_flyout_form').on('click', '[type=\"submit\"]', function () {\n var $this = $(this),\n $form = $this.parents('form').eq(0),\n newsletterID = $form.find('[name=\"newsletter\"]').eq(0).attr('value');\n \n trackNewsletterEngagement(newsletterID);\n });\n //newsletter close\n $('body').on('mousedown', 'div.dod_close, .no_flyout', function () {\n var $this = $(this),\n closeType = $this.hasClass('no_flyout') ? 'no_flyout' : 'close';\n \n trackNewsletterEngagement(closeType);\n });\n \n //Right Rail Module\n $('.newsletter_signup').on('click', '[value=\"submit\"]', function () {\n var $this = $(this),\n $form = $this.parents('form').eq(0),\n newsletterID = $form.find('[name=\"newsletter\"]').eq(0).attr('value');\n \n trackNewsletterEngagement(newsletterID);\n });\n \n //This handles a custom \"newsletterSignup\" event which is fired on a successfull ajax resonse from the newsletter submit action.\n $('form[id^=\"newsletters_signup\"], form#newsletter_flyout_form').on('newsletterSignup', function(e) {\n track(['_setAccount', 'UA-28236326-1'],\n ['_setDomainName', 'nationalgeographic.com'],\n ['_setAllowLinker', true],\n ['_setCustomVar', 2, 'isSubscriber-Email', 'true', 1]);\n track(['_trackPageview', e.url]);\n });\n }());\n \n //Email Registration Test Events\n (function () {\n $('#eregtest').on('Displayed', function (e) {\n // Determine section names\n var section = document.location.pathname.split('/')[1],\n site = window.location.hostname.split('.')[0];\n if (section === '' || section === ' ') {\n if (site === 'www') {\n section = 'Home';\n } else if (site === 'news') {\n section = 'News';\n } else if (site === 'animals') {\n section = 'Animals';\n } else if (site === 'photography') {\n section = 'Photography';\n } else {\n section = site;\n }\n } else if (section === 'news') {\n section = 'News';\n } else if (section === 'animals') {\n section = 'Animals';\n } else if (section === 'photography') {\n if (document.location.pathname.split('/')[3] === 'photo-of-the-day') {\n section = \"Photography-POD\";\n } else if (window.location.hostname === 'ngm.nationalgeographic.com') {\n if (document.location.pathname.split('/')[1] === 'photography') {\n section = \"NGM Photos\";\n }\n } else {\n section = \"Photography\";\n }\n } else {\n section = section;\n }\n \n // Push the custom variable\n track(['_setCustomVar', 7, 'Reg-wall-section', section + '-1st-hit', 2]);\n \n // Record the modal display event\n track(['_trackPageview', 'Reg-wall-view ']);\n });\n \n $('#eregtest').on('Privacy_Link', function () {\n track(['_trackEvent', 'Reg-wall-section', 'click', 'privacy-policy']);\n });\n \n $('#eregtest').on('TOS_Link', function () {\n track(['_trackEvent', 'Reg-wall-section', 'click', 'terms-service']);\n });\n \n $('#eregtest').on('Explanation_Link', function () {\n track(['_trackEvent', 'Reg-wall-section', 'click', 'whats-this']);\n });\n \n $('#eregtest').on('Email_Reg_Button', function () {\n track(['_trackEvent', 'Reg-wall-section', 'click', 'join-now']);\n });\n \n $('#eregtest').on('FB_Reg_Button', function () {\n track(['_trackEvent', 'Reg-wall-section', 'Social Login', 'facebook']);\n });\n }());\n \n //Packaged Homepage Module GA Events\n (function () {\n var $home = $('body.www.homepage'),\n $DLModule = $home.find('#content_top'),\n $DL = $DLModule.find('.dl'),\n $moreLink = $DL.find(\"ul > li div > p.action > a\"),\n $sideMods = $DLModule.find('.secondary .promo_collection'),\n $pod = $sideMods.eq(0),\n $featuredVideo = $sideMods.eq(1),\n $homeContent = $home.find('#content_mainA'),\n $homeRR = $home.find('#content_mainB');\n \n $moreLink.attr(\"data-index\", 1);\n\n //This should only target the <a> around the DL image.\n $DL.on('click', 'a', function (e) {\n var $this = $(this),\n $thisLI = $this.parentsUntil('.dl > ul').eq(0),\n isDLNav = ($thisLI.length) ? $thisLI.parent().hasClass('dl_navigation') : false,\n index = $thisLI.index() + 1;\n \n //Should only be dealing with links inside lists.\n if ($thisLI.attr(\"tagName\").toLowerCase() === \"li\") {\n //Dl Nav\n if (isDLNav) {\n $moreLink.attr(\"data-index\", $this.text());\n track(['_trackEvent', 'DL', 'DLNav', 'HPDL' + $this.text() + '_HPMod']);\n }\n //DL Image\n else {\n track(['_trackEvent', 'DL', 'DLImage', 'DLMain Image' + index + '_HPMod']);\n }\n //Direct parent of More link is a <p>.\n } \n else if ($this.parent('.action')[0]) {\n track(['_trackEvent', 'DL', 'DLMore', 'HPDL' + $moreLink.attr(\"data-index\") + '_More_HPMod']);\n }\n });\n $pod.on('click', 'a', function () {\n track(['_trackEvent', 'Module', 'DLSide1', 'POD_HPMod']);\n });\n $featuredVideo.on('click', 'a', function () {\n track(['_trackEvent', 'Module', 'DLSlide2', 'FeaturedContent RL_HPMod ']);\n });\n $homeContent.on('click', 'a', function () {\n var $this = $(this),\n $thisModule = $this.parents('.promo_collection').eq(0),\n moduleClassList = ($thisModule.length) ? $thisModule.attr('class').split(' ') : [];\n \n if ($.inArray('news_stories', moduleClassList) >= 0) {\n track(['_trackEvent', 'Module', 'LeftUDL', 'DailyNews_HPMod']);\n } else if ($.inArray('vcalendar', moduleClassList) >= 0) {\n track(['_trackEvent', 'Module', 'RightUDL', 'TV_HPMod']);\n }\n });\n $homeRR.on('click', 'a', function () {\n var $this = $(this),\n $thisModule = $this.parents('.promo_collection').eq(0),\n moduleClassList = ($thisModule.length) ? $thisModule.attr('class').split(' ') : [];\n\n if ($.inArray('links_list', moduleClassList) && $.inArray('small', moduleClassList)) {\n if ($thisModule.find('h3.title').text('Travel With Us')) {\n track(['_trackEvent', 'Module', 'RightRLTra', 'TravelWithUs_HPMod']);\n } else if ($thisModule.find('h3.title').text('Newsletters')) {\n track(['_trackEvent', 'Module', 'RightRLNewsltr', 'Newsletter_HPMod']);\n }\n }\n });\n }());\n \n //Packaged News Article Module GA Events\n (function () {\n var $news = $('body.news.article').eq(0),\n $modules = $news.find('.most-popular-news, .great-energy-challenge-blog, .news-video, .news-blogs');\n \n $modules.on('click', 'a', function (e) {\n var $this = $(this),\n $thisModule = $this.parents('.most-popular-news, .great-energy-challenge-blog, .news-video, .news-blogs').eq(0);\n \n if ($thisModule.hasClass('most-popular-news')) {\n track(['_trackEvent', 'Module', 'RightRLNewsDL', 'MostPopNews_NewsMod']);\n } else if ($thisModule.hasClass('great-energy-challenge-blog')) {\n track(['_trackEvent', 'Module', 'RightRLNews1', 'GEC_NewsMod']);\n } else if ($thisModule.hasClass('news-video')) {\n track(['_trackEvent', 'Module', 'LeftRLNews2', 'NewsVideos_NewsMod']);\n } else if ($thisModule.hasClass('news-blogs')) {\n track(['_trackEvent', 'Module', 'RightRLNews2', 'NewsBlogs_NewsMod']);\n }\n });\n }());\n \n //Video Modules\n (function () {\n var $modules = $('#content_mainB').find('[class*=\"video\"]');\n $('#content_mainB .videos').on('click', 'a', function () {\n var $this = $(this),\n $thisModule = $this.parentsUntil('.tabs-content').find('[class*=\"video\"]').eq(0),\n moduleName;\n \n if ($thisModule.hasClass('featured-video')) {\n moduleName = 'FeaturedVideo';\n } else if ($thisModule.hasClass('latest-video')) {\n moduleName = 'LatestVideo';\n }\n track(['_trackEvent', 'Module', 'RightRLVideo', moduleName]);\n });\n }());\n \n //video tracking\n (function () {\n /*\n Needs to be delegated since original #ngplayer node get replaced with\n <object/> for flash video.\n */\n $('body').on('Ready Start Play Pause Progress Complete', '#ngplayer', function (e) {\n var percentageViewed,\n timeInSec;\n if (e.type === 'Ready') {\n videoDuration = e.value;\n track(['_trackEvent', 'video', e.type, $('#natgeov-vtitle').text().trim()]);\n } else if (e.type === 'Progress') {\n percentageViewed = (e.value)/100;\n timeInSec = Math.floor(videoDuration * percentageViewed);\n track(['_trackEvent', 'video', e.type, 'Video complete ' + e.value + '%']);\n } else {\n track(['_trackEvent', 'video', e.type, $('#natgeov-vtitle').text().trim()]);\n }\n });\n }());\n //Scroll Tracking\n (function (doc, win) {\n var de = doc.documentElement,\n scrollY = function () {\n return win.self.pageYOffset || (de && de.scrollTop) || doc.body.scrollTop;\n },\n pageHeight = function () {\n return doc.body.scrollHeight;\n },\n windowHeight = function () {\n return win.self.innerHeight || (de && de.clientHeight) || doc.body.clientHeight;\n },\n trackAt = {\n topHat : 290,\n engagementA : 0.6,\n engagementB : 0.9\n },\n isTracked = {\n topHat : false,\n engagementA : false,\n engagementB : false\n };\n \n addEvent('scroll', win, function () {\n var percentScroll = (scrollY() + windowHeight())/pageHeight(),\n pxScroll = scrollY(),\n page = win.location.pathname,\n search = win.location.search,\n url = page + search;\n \n if (!isTracked.topHat && pxScroll > trackAt.topHat) {\n isTracked.topHat = true;\n track(['_trackEvent', 'engagement', 'scrolled past ' + trackAt.topHat, url, null, true]);\n } else if (!isTracked.engagementA && percentScroll > trackAt.engagementA) {\n isTracked.engagementA = true;\n track(['_trackEvent', 'engagement', 'scrolled ' + (trackAt.engagementA * 100) + '%', url]);\n } else if (!isTracked.engagementB && percentScroll > trackAt.engagementB) {\n isTracked.engagementB = true;\n track(['_trackEvent', 'engagement', 'scrolled ' + (trackAt.engagementB * 100) + '%', url]);\n }\n });\n }(document, window, undefined));\n \n //Bounce modification\n (function (sec) {\n var url = document.location.pathname + document.location.search,\n bounce = window.setTimeout(function () {\n track(['_trackEvent', 'engagement', 'Dwell time (more than ' + sec + ' seconds)', url]);\n }, sec * 1000);\n }(20));\n \n })();\n //End Google Analytics\n \n // Nielsen Online SiteCensus V6.0 | COPYRIGHT 2010 Nielsen Online\n (function () {\n var d = new Image(1, 1);\n d.onerror = d.onload = function () {\n d.onerror = d.onload = null;\n };\n d.src = [ document.location.protocol,\n \"//secure-us.imrworldwide.com/cgi-bin/m?ci=us-301776h&cg=0&cc=1&si=\",\n window.escape(window.location.href),\n \"&rp=\",\n window.escape(document.referrer),\n \"&ts=compact&rnd=\",\n (new Date()).getTime()].join('');\n })();\n };\n \n if ($) {\n if ($.fn.on) {\n $(document).ready(function() {\n allReady(window, document, $, analytics);\n });\n } else {\n $.fn.on = function (events, selector, data, handler) {\n var $this = this,\n $filtered,\n attach = ($.fn.delegate) ? 'delegate' : ($.fn.live) ? 'live' : 'bind';\n\n if (handler === undefined) {\n if (data === undefined) {\n handler = selector;\n selector = undefined;\n } else {\n handler = data;\n data = undefined;\n }\n }\n\n if (attach === 'delegate' && typeof selector === 'string') {\n return $this[attach](selector, events, data || {}, handler);\n } else {\n attach = (attach === 'delegate') ? 'live' : attach;\n $filtered = (selector) ? $this.find(selector) : $this;\n\n if (data) {\n return $this[attach].call($filtered, events, data, handler);\n } else {\n return $this[attach].call($filtered, events, handler);\n }\n }\n };\n $(document).ready(function() {\n allReady(window, document, $, analytics);\n });\n }\n } else {\n (function () {\n var jq = document.createElement('script'),\n jqS = document.body || document.head || document.documentElement;\n jq.async = true;\n if (jq.addEventListener) {\n jq.addEventListener('load', function () {\n allReady(window, document, jQuery.noConflict(!!$), analytics);\n });\n } else if (jq.onreadystatechange !== undefined) {\n // Added for IE8 otherwise it won't know that we're ready\n jq.onreadystatechange = function () {\n if (this.readyState === 'loaded') {\n allReady(window, document, jQuery.noConflict(!!$), analytics);\n }\n };\n }\n jq.src = '//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js';\n jqS.appendChild(jq);\n })();\n }\n \n if (typeof String.prototype.trim === 'undefined') {\n String.prototype.trim = function () {\n return this.replace(/^\\s\\s*/, '').replace(/\\s\\s*$/, '');\n };\n }\n})(window, document, window.jQuery);\n" }, { "alpha_fraction": 0.4805980920791626, "alphanum_fraction": 0.48326805233955383, "avg_line_length": 31.662790298461914, "blob_id": "b8043d954157b18723ca5cae628ce01602359aeb", "content_id": "a01758b756787d4484d6e75d973591f1123efb8d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5618, "license_type": "permissive", "max_line_length": 158, "num_lines": 172, "path": "/servers/demo-scaleout/html/boston.tmp/bcom-gigya.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "\n//////////// src: scripts/_bcom-gigya.js ////////////\n\nif (typeof bcom === \"undefined\") { bcom = {}; }\n\n/*-------------\n * BCOM Gigya module\n *\n * Used for putting the Gigya social\n * module on a page\n */\nbcom.gigya = {\n\n /*--------------\n * bcom.gigya.init()\n *\n * Expects the ID of an element\n * that will be turned into the\n * Gigya module.\n *\n * DOM element should resemble:\n * <div id=\"gigya-top\" data-networks=\"facebook,twitter\" data-canonical=\"example.com/full-article\" data-shorturl=\"example.com\" data-headline=\"Hello World\">\n */\n init: function(id) {\n var $elem, act, uiParams;\n\n $elem = $(\"#\" + id);\n this.canonicalURL = $elem.attr(\"data-canonical\");\n this.shortURL = $elem.attr(\"data-shorturl\");\n this.headline = $elem.attr(\"data-headline\");\n this.thumbnail = $elem.attr(\"data-thumbnail\");\n this.description = $elem.attr(\"data-description\");\n this.networks = this.getNetworks($elem.attr(\"data-networks\"));\n this.thumbType = $elem.attr(\"data-thumb-type\");\n this.showCounts = $elem.attr(\"data-show-counts\");\n this.iconsOnly = $elem.attr(\"data-icons\");\n\n\t\t//changing the default from right to top if attr left blank of undefined\n\t\tif(this.showCounts == undefined || this.showCounts == ''){\n\t\t\tthis.showCounts = 'top';\n\t\t}\n act = this.createUserAction();\n uiParams = this.setUIParams(act, id);\n gigya.socialize.showShareBarUI(uiParams);\n },\n\n createUserAction: function() {\n var act;\n act = new gigya.socialize.UserAction();\n act.setLinkBack(this.shortURL);\n act.setTitle(this.headline);\n act.setDescription(this.description);\n if(this.thumbType === 'image'){\n\t var image = {\n\t\t\t//we should really set a default image to use in the instance that we don't have an image set for an article\n\t type: 'image',\n\t src: this.thumbnail,\n\t href: 'http://graphics8.nytimes.com'\n\t }\n\t\t\tact.addMediaItem(image);\n\t\t}\n\t\tif(this.thumbType === 'video'){\n\t\t\tvar video = {\n src: 'http://www.youtube.com/v/fzzjgBAaWZw&hl=en&fs=1',\n previewImageURL: 'http://graphics8.nytimes.com/images/2006/01/02/science/03cute.large2.jpg',\n type: 'flash'\n }\n\t\t\tact.addMediaItem(video);\n\n\t\t}\n return act;\n },\n\n getNetworks: function(data) {\n if (data) {\n return data.split(\",\");\n }\n\n // Default list of networks to use\n // if none are provided\n return [\"facebook\",\n \"twitter\",\n \"googleplus-share\",\n \"pinterest\",\n \"linkedin\",\n \"share\"];\n },\n\n setUIParams: function(act, id) {\n var params, self;\n\n self = this;\n\n params = {\n containerID: id,\n moreEnabledProviders: \"reddit,tumblr,evernote,gmail,pinterest,bitly,delicious\",\n shareButtons: [],\n //showCounts: \"top\",-show-counts\n showCounts: this.showCounts,\n iconsOnly:\tthis.iconsOnly,\n userAction: act,\n shortURLs: \"never\"\n }\n\n var len = self.networks.length;\n for(var i = 0; i < len; i++) {\n var network = self.networks[i];\n\n switch(network) {\n case \"facebook\":\n params.shareButtons.push(\n {provider: \"Facebook\"});\n break;\n case \"twitter\":\n params.shareButtons.push(\n { provider:\"Twitter\",\n related: \"BostonDotCom,BostonGlobe\",\n via:\"BostonDotCom\",\n countURL: self.canonical\n });\n params[\"twitterUserAction\"] = { \"title\": this.headline + \" - via @bostondotcom\" }\n break;\n case \"googleplus-share\":\n params.shareButtons.push(\n { provider:\"googleplus-share\"});\n break;\n case \"pinterest\":\n params.shareButtons.push(\n { provider:\"pinterest\"});\n break;\n case \"linkedin\":\n params.shareButtons.push(\n { provider:\"linkedin\"});\n break;\n case \"share\":\n params.shareButtons.push(\n { provider:\"share\",\n tooltip:\"Share on other social networks\"\n });\n params[\"enableCount\"] = false;\n break;\n case \"email\":\n params.shareButtons.push({provider:\"email\"});\n break;\n case \"reddit\":\n params.shareButtons.push({provider:\"Reddit\"});\n break;\n case \"stumbleupon\":\n params.shareButtons.push({provider:\"Stumbleupon\"});\n break;\n case \"myspace\":\n params.shareButtons.push({provider:\"Myspace\"});\n break;\n case \"tumblr\":\n params.shareButtons.push({provider:\"Tumblr\"});\n break;\n default:\n break;\n }\n }\n\n return params;\n }\n}\n\n\n//////////// src: scripts/_bcom-gigya-run.js ////////////\n\n$(function() {\n\t$('.gigya').each(function(){\n\t\t bcom.gigya.init(this.id);\n\t});\n});" }, { "alpha_fraction": 0.6424580812454224, "alphanum_fraction": 0.6759776473045349, "avg_line_length": 43.75, "blob_id": "ec9fbef3bc89b6f1a3a5c009318f587dabbada06", "content_id": "f8469e4a83b03f128148b3ffd260f32c2fba516f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 179, "license_type": "permissive", "max_line_length": 110, "num_lines": 4, "path": "/servers/demo-scaleout/html/boston.tmp/cross-check.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "window._taboola = window._taboola || [];\nwindow._taboola.push({\n \"throttle_pub\" : { \"mangareader-mangapanda\" : 10, \"mangareader-mangareader\" : 10, \"mangareader-network\" : 10}\n});\n" }, { "alpha_fraction": 0.4718337953090668, "alphanum_fraction": 0.485817015171051, "avg_line_length": 43.69643020629883, "blob_id": "817021ea8eeac392b785a27310100ceff40de05e", "content_id": "83e02a8cde2b1fce9d956b581a1e2ae292d3cd49", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2503, "license_type": "permissive", "max_line_length": 131, "num_lines": 56, "path": "/servers/demo-scaleout/html/nyc-3/autosuggestConfig.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "/* $Id: autosuggestConfig.js 119242 2013-01-15 00:48:07Z surya.sanagavarapu $\n (c) 2012 The New York Times Company\n*/\n\nvar NYTD = NYTD || {};\nNYTD.Search = NYTD.Search || {};\n\n// Configure to show company ticker symbol, then the full name of the company, with matching text in bold in both\nNYTD.Search.Config = {\n SearchBoxes: {\n bizAutosuggest: {\n DOMselector: \".inlineSearchControl\",\n resultsNode: [1], //node in the response that holds results\n serviceLocation: \"/svc/suggest/v1/business\",\n nameOfQueryCall: \"query=\",\n minimumCharSearch: 2, //minuimum number of characters to search on (optional)\n dataType: \"json\",\n getMethod: \"get\",\n suggestedItemTemplate: function(key, val, boldedJson) {\n var data = NYTD.jQuery.parseJSON(val);\n var boldedData = NYTD.jQuery.parseJSON(boldedJson);\n var boldedResults = boldedData.results;\n var boldedCompany = boldedResults.company;\n var prettyCompany = boldedCompany.slice(0, 3) === '<b>' ? \n '<b>' + boldedCompany.charAt(3).toUpperCase() + boldedCompany.slice(4) :\n boldedCompany.charAt(0).toUpperCase() + boldedCompany.slice(1);\n return [\n '<li class=\"clearfix\">',\n '<a href=\"',data.results.url,'\">','<span>',boldedResults.ticker,'</span>',prettyCompany,'</a>',\n '</li>'].join('');\n },\n\n footerTemplate: function(query) {\n return [\n '<li class=\"marketQuoteRefer\" title=\"View All Matches\">',\n '<h6>',\n '<a href=\"http://markets.on.nytimes.com/research/symbol_lookup/overview/search.asp?textIn=',query,'\">',\n '<b>View All Matches &raquo;</b>',\n '</a>',\n '</h6>',\n '</li>'].join('');\n },\n\n submitCallback: function() {\n var $selectedItem = NYTD.jQuery(this).find(\"li.selectedItem\");\n if ($selectedItem.length) {\n var href = $selectedItem.find(\"a\").attr('href');\n if (href) {\n window.location.href = href;\n return false;\n }\n }\n }\n }\n }\n};\n" }, { "alpha_fraction": 0.7596253752708435, "alphanum_fraction": 0.8054110407829285, "avg_line_length": 18.219999313354492, "blob_id": "893898dacbb3a7bd09692168e1b895c925abaae9", "content_id": "270c98dea1fb0329b4ab5d5ca9a97a8b46e77c32", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 961, "license_type": "permissive", "max_line_length": 76, "num_lines": 50, "path": "/servers/rdp/etc/xrdp/sesman.ini", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "[Globals]\nListenAddress=127.0.0.1\nListenPort=3350\nEnableUserWindowManager=1\nUserWindowManager=startwm.sh\nDefaultWindowManager=startwm.sh\n\n[Security]\nAllowRootLogin=1\nMaxLoginRetry=4\n# When AlwaysGroupCheck = false access will be permitted\nAlwaysGroupCheck = false\n\n[Sessions]\nX11DisplayOffset=10\nMaxSessions=50\n# if 1, true, or yes, kill session after 60 seconds\nKillDisconnected=0\n# if not zero, the seconds without mouse or keyboard input before disconnect\n# not complete yet\nIdleTimeLimit=0\n# if not zero, the seconds before a disconnected session is killed\n# min 60 seconds\nDisconnectedTimeLimit=0\n\n[Logging]\nLogFile=/tmp/xrdp-sesman.log\nLogLevel=DEBUG\nEnableSyslog=1\nSyslogLevel=DEBUG\n\n[X11rdp]\nparam1=-bs\nparam2=-ac\nparam3=-nolisten\nparam4=tcp\nparam5=-uds\n\n[Xvnc]\nparam1=-bs\nparam2=-ac\nparam3=-nolisten\nparam4=tcp\nparam5=-localhost\nparam6=-dpi\nparam7=96\n\n#[Chansrv]\n# drive redirection, defaults to xrdp_client if not set\n#FuseMountName=thinclient_drives\n" }, { "alpha_fraction": 0.48216918110847473, "alphanum_fraction": 0.49189507961273193, "avg_line_length": 28.008546829223633, "blob_id": "f85bc23b1ab47e0471be9bc3f583e02ee85b984d", "content_id": "49f74d8b7a24094032215997eecaf235323c852f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3393, "license_type": "permissive", "max_line_length": 166, "num_lines": 117, "path": "/servers/demo-scaleout/html/create_page.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "\"use strict\";\nvar fs = require('fs'),\n wrench = require('wrench'),\n htmlFileDir = __dirname + '/';\n\nvar folders = ['abc-1', 'abc-2', 'abc-3',\n 'nyc-1', 'nyc-2', 'nyc-3', 'nyc-4', 'nyc-5'\n];\nfolders.forEach(function(item) {\n saveHtmlFile(item);\n});\n\nfunction saveHtmlFile(input) {\n var fileName = htmlFileDir + input + '.html';\n var fileDict = getResourceFiles(input);\n var top = '<!DOCTYPE html><hmtl>\\n<head><meta charset=\"utf-8\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"><title>' + input + '</title></head>\\n<body>\\n';\n var middle = createMiddle(input, fileDict);\n var bottom = '</body>\\n</html>';\n var text = top + middle + bottom;\n fs.writeFile(fileName, text, function(err) {\n if (err) {\n console.log(err);\n return;\n } else {\n console.log('Wrote: ' + fileName);\n }\n });\n}\n\nfunction createMiddle(input, fileDict) {\n var middleText = '';\n Object.keys(fileDict).forEach(function(key) {\n fileDict[key].forEach(function(file) {\n var src = input + '/' + file;\n var extension = key.toLowerCase();\n switch (extension) {\n case '.jpg':\n case '.png':\n case '.gif':\n middleText += '<img src=\"' + src + '\"/>';\n break;\n case '.css':\n middleText += '<link rel=\"stylesheet\" href=\"' + src + '\">';\n break;\n case '.js':\n middleText += '<script src=\"' + src + '\"></script>';\n break;\n case '.txt':\n middleText += '<p>' + src + '</p>';\n break;\n default:\n console.log(extension);\n throw 'Unexpected file type';\n }\n middleText += '\\n';\n\n });\n });\n return middleText;\n}\n\nfunction getResourceFiles(input) {\n var files = wrench.readdirSyncRecursive(__dirname + '/' + input);\n\n var fileDict = {\n '.txt': [makeParagraph(50, 200)]\n },\n //, 'js'\n fileTypes = ['jpg', 'gif', 'png', 'css']\n .map(function(item) {\n return '\\.' + item + '$';\n }),\n fileTypesRegEx = new RegExp(fileTypes.join('|'), 'i');\n for (var i = files.length - 1; i >= 0; i--) {\n var file = files[i],\n match = file.match(fileTypesRegEx);\n if (match) {\n if (!fileDict[match[0]]) {\n fileDict[match[0]] = [];\n }\n fileDict[match[0]].push(file);\n }\n };\n\n Object.keys(fileDict).forEach(function(key) {\n fileDict[key].sort();\n });\n\n return fileDict;\n}\n\nfunction randomLength(min, max) {\n var possible = [];\n for (var i = min; i <= max; i++) {\n possible.push(i);\n }\n return possible[Math.floor(Math.random() * possible.length)];\n}\n\nfunction makeParagraph(min, max) {\n var text = \"\";\n for (var i = min; i <= max; i++) {\n text += makeRandomString(randomLength(1, 20)) + \" \";\n }\n return text;\n\n}\n\nfunction makeRandomString(length) {\n var text = \"\";\n var possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n for (var i = 0; i < length; i++)\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n\n return text;\n}" }, { "alpha_fraction": 0.27941176295280457, "alphanum_fraction": 0.6029411554336548, "avg_line_length": 20.66666603088379, "blob_id": "34fd8bd9ec545d70d8853a6a6ff8b5bf9f542e2a", "content_id": "9f747d687ba8955a70bb8a740d6abe22c5de6d2e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 68, "license_type": "permissive", "max_line_length": 51, "num_lines": 3, "path": "/servers/demo-scaleout/html/nyc-1/wtid.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "<!-- \r\ngTempWtId=\"158f2ef6-d551-413d-b2e8-236979c5cb11\"; \r\n// -->\r\n" }, { "alpha_fraction": 0.7346938848495483, "alphanum_fraction": 0.7414966225624084, "avg_line_length": 48, "blob_id": "2ce79c9df37e32b1438d9895e36e5991a4f65024", "content_id": "ec612aed9863206911536bc764b60fc6d9305387", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 147, "license_type": "permissive", "max_line_length": 91, "num_lines": 3, "path": "/servers/demo-scaleout/html/nyc-5/boot.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "if (window.TimesPeople && TimesPeople.URIList && TimesPeople.URIList.allowsCurrentPage()) {\n NYTD.require('/js2/build/timespeople/build.js');\n}\n" }, { "alpha_fraction": 0.6296296119689941, "alphanum_fraction": 0.6296296119689941, "avg_line_length": 54, "blob_id": "104c0af8ac307410729cd25c7c35504647d0cccc", "content_id": "f9dd535e97edc4f94afa304203df1e35f6c932e2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 54, "license_type": "permissive", "max_line_length": 54, "num_lines": 1, "path": "/servers/demo-scaleout/html/natgeo/list.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "s_sv_globals.onListLoaded('','','','natgeoglobal',[]);" }, { "alpha_fraction": 0.4913986623287201, "alphanum_fraction": 0.5023186206817627, "avg_line_length": 29.660551071166992, "blob_id": "1e711586127aa46e42426647b2fcb5c508baefbd", "content_id": "8af8d4f7be3fdef714ad8242c937d23b676bfadd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 6685, "license_type": "permissive", "max_line_length": 138, "num_lines": 218, "path": "/servers/demo-scaleout/html/httpcc.php", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "<?php\ndefine( 'LAST_MODIFIED_STRING', 'Sat, 09 Sep 2000 22:00:00 GMT' );\n\n$arg_et = 10;\n$et = 'PT10S';\nif( isset( $_GET['et'] ) and $_GET['et'] !== '' )\n{\n $arg_et = $_GET['et'];\n $et = 'PT' . $arg_et . 'S';\n}\n\n$lmts = LAST_MODIFIED_STRING;\nif( isset( $_GET['mt'] ) and $_GET['mt'] !== '' )\n{\n $arg_mt = $_GET['mt'];\n $mt = 'PT' . $arg_mt . 'S';\n $lmt_date = new DateTime(LAST_MODIFIED_STRING);\n\t$lmt_date->add(new DateInterval($mt));\n\t$lmts = toUTCDate($lmt_date);\n}\n\ndate_default_timezone_set(\"UTC\");\n// expires_date : 10s after page generation\n$expires_date = new DateTime();\n$expires_date->add(new DateInterval($et));\n\n$headers = array(\n 'Date' => date( 'D, d M Y H:i:s', time() ),\n);\n\n$auth = 0;\nif( isset( $_SERVER['HTTP_AUTHORIZATION'] ) and $_SERVER['HTTP_AUTHORIZATION'] !== '')\n{\n $auth = 1;\n $headers['X-Auth'] = md5($_SERVER['HTTP_AUTHORIZATION']);\n}\n\nif( isset( $_GET['h'] ) and $_GET['h'] !== '' )\n{\n switch( $_GET['h'] )\n {\n case \"private\" :\n $headers['Expires'] = toUTCDate($expires_date);\n $headers['Cache-Control'] = \"s-maxage=60, private, max-age=60\";\n break;\n\n case \"nostore\" :\n $headers['Expires'] = toUTCDate($expires_date);\n $headers['Cache-Control'] = \"s-maxage=60, no-store, max-age=60\";\n break;\n\n case \"nocache\" :\n $headers['Expires'] = toUTCDate($expires_date);\n $headers['Cache-Control'] = \"s-maxage=60, no-cache, max-age=60\";\n break;\n\n case \"expires\" :\n $headers['Expires'] = toUTCDate($expires_date);\n break;\n\n case \"cache-control\":\n $headers['Cache-Control'] = \"public, proxy-revalidate, max-age=\" . $arg_et/2 . \", s-maxage=\" . $arg_et;\n break;\n\n case \"cache-control-override\":\n $headers['Expires'] = toUTCDate($expires_date);\n $headers['Cache-Control'] = \"public, proxy-revalidate, max-age=\" . $arg_et/4 . \", s-maxage=\" . $arg_et/2;\n break;\n\n case \"lmt\":\n $headers['Last-Modified'] = $lmts;\n $headers['Etag'] = md5( $lmts );\n\n if( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) and\n $_SERVER['HTTP_IF_MODIFIED_SINCE'] == $lmts ) {\n header( \"HTTP/1.1 304 Not Modified\" );\n exit( );\n }\n break;\n\n case \"vary\":\n $headers['Expires'] = toUTCDate($expires_date);\n $headers['Vary'] = 'User-Agent';\n break;\n\n case \"varycookie\":\n $headers['Expires'] = toUTCDate($expires_date);\n $headers['Vary'] = 'Cookie';\n break;\n\n case \"varystar\":\n $headers['Expires'] = toUTCDate($expires_date);\n $headers['Vary'] = '*';\n break;\n\n case \"cookie\":\n $utcdate = toUTCDate($expires_date);\n $headers['Expires'] = $utcdate;\n $headers['Set-Cookie'] = 'md5expires=' . md5($utcdate);\n break;\n\n case \"nonexp\":\n break;\n\n case \"nodate\":\n unset($headers['Date']);\n $headers['Expires'] = toUTCDate($expires_date);\n break;\n\n case \"agexp\":\n $headers['Age'] = $arg_et;\n $headers['Expires'] = toUTCDate($expires_date);\n break;\n\n case \"multivary\":\n $headers['Expires'] = toUTCDate($expires_date);\n $headers['Vary'] = 'User-Agent,Host,Accept-Encoding';\n break;\n\n case \"missingvary\":\n $headers['Expires'] = toUTCDate($expires_date);\n $headers['Vary'] = 'User-AgentX,Host,Accept-Encoding';\n break;\n\n case \"mlinevary\":\n $headers['Expires'] = toUTCDate($expires_date);\n $headers['Vary'] = 'User-Agent,Host';\n header(\"vary: accept-language, accept-encoding\");\n flush();\n break;\n\n case \"hwarn\":\n $headers['Last-Modified'] = $lmts;\n $headers['Cache-Control'] = \"public\";\n\t $headers['Age'] = '86398';\n break;\n\n case \"imodz\":\n $lmts = $headers['Date'];\n $lmts = toUTCDate(new DateTime($lmts));\n // fallthrough\n\n case \"imod\":\n $headers['Last-Modified'] = $lmts;\n $headers['Etag'] = md5( $lmts );\n $headers['Cache-Control'] = \"public\";\n $headers['Expires'] = toUTCDate($expires_date);\n break;\n }\n} elseif( isset($_POST['k']) and $_POST['k'] !== '' and\n isset($_POST['v']) and $_POST['v'] !== '') {\n $k=$_POST['k'];\n $v=$_POST['v'];\n $setc = \"$k: $v\";\n\n header(\"$setc\", false);\n} else {\n\t$headers['Last-Modified'] = $lmts;\n\tif ($auth==0) {\n\t $headers['Age'] = '86398';\n }\n if( isset( $_SERVER['HTTP_CACHE_CONTROL'] ) ) {\n $headers['Cache-Control'] = $_SERVER['HTTP_CACHE_CONTROL'];\n }\n}\n\nsendHeaders( $headers );\n\nfunction sendHeaders( array $headerList )\n{\n foreach( $headerList as $name => $value )\n {\n header( \"${name}: ${value}\", false );\n }\n}\n\nfunction toUTCDate( DateTime $date )\n{\n $date->setTimezone( new DateTimeZone( 'UTC' ) );\n return $date->format( 'D, d M Y H:i:s \\G\\M\\T' );\n}\n?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head></head>\n <body>\n <h1>Headers received</h1>\n <?php\n print \"<pre>\";\n print_r($_SERVER);\n print \"</pre>\";\n ?>\n <hr/>\n <h1>Headers sent</h1>\n <?php\n print \"<pre>\";\n foreach( $headers as $name => $value ) {\n print \"<strong>${name}</strong>: ${value}<br/>\";\n }\n\n if( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {\n print \"<strong>If-Modified-Since</strong> has been sent in the\";\n print \"request, value : \" . $_SERVER['HTTP_IF_MODIFIED_SINCE'];\n }\n print \"</pre>\";\n ?>\n <hr/>\n <h1>Links for testing</h1>\n <ul>\n <li><a href=\"<?=$_SERVER['PHP_SELF']?>?h=expires\">Test Expires response header</a></li>\n <li><a href=\"<?=$_SERVER['PHP_SELF']?>?h=cache-control\">Test Cache-Control response header</a></li>\n <li><a href=\"<?=$_SERVER['PHP_SELF']?>?h=cache-control-override\">Test Cache-Control response header overrides Expires</a></li>\n <li><a href=\"<?=$_SERVER['PHP_SELF']?>?h=last-modified\">Test Last-Modified/If-modified-since response header</a></li>\n <li><a href=\"<?=$_SERVER['PHP_SELF']?>?h=vary\">Test Vary response header</a></li>\n <ul>\n </body>\n</html>\n\n" }, { "alpha_fraction": 0.6052631735801697, "alphanum_fraction": 0.6859267950057983, "avg_line_length": 59.24137878417969, "blob_id": "4cfa56a9ee2f09a84a914cfa47e2e1179a4e5b12", "content_id": "7a998e7c9f2e74bba07fb8661b9d88ab0fa278e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1748, "license_type": "permissive", "max_line_length": 297, "num_lines": 29, "path": "/servers/demo-scaleout/html/abc-1/aperture-cookie.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "\n\n/** \n* @filepath: aperture-cookie\n* @created: Tue, 26 Nov 13 12:59:19 -0800\n* @serveraddr: 10.141.172.146\n* @remoteaddr: 10.96.118.249\n* @bu: abccom\n* @cdnroot: http://cdn.media.abc.com/m\n*/\n\n\n/** \n* @filepath: /abcdm/aperture.cookie.js\n* @created: Tue, 26 Nov 13 12:59:19 -0800\n* @serveraddr: 10.141.172.146\n* @remoteaddr: 10.96.118.249\n* @bu: abccom\n* @cdnroot: http://cdn.media.abc.com/m\n*/\n\nvar cookie,cookies,cookieName,omnObject;function readCookie(name){var c=document.cookie.split(\"; \"),C;cookies={};for(var i=c.length-1;i>=0;i--){C=c[i].split(\"=\");cookies[C[0]]=C[1];}\nif(cookies[name]){return JSON.parse(decodeURIComponent(cookies[name]));}else{return null;}}\nfunction typeLookup(type,list){if(list&&typeof(list)===\"object\"){for(var i=0;i<list.length;i++){if(list[i].type===type){return list[i];}}\nreturn null;}else{return null;}}\nfunction rc4Encrypt(key,pt){s=new Array();for(var i=0;i<256;i++){s[i]=i;};var j=0;var x;for(i=0;i<256;i++){j=(j+s[i]+key.charCodeAt(i%key.length))%256;x=s[i];s[i]=s[j];s[j]=x;}\ni=0;j=0;var ct=\"\";for(var y=0;y<pt.length;y++){i=(i+1)%256;j=(j+s[i])%256;x=s[i];s[i]=s[j];s[j]=x;ct+=String.fromCharCode(pt.charCodeAt(y)^s[(s[i]+s[j])%256]);}return ct;}\nfunction hexEncode(data){var b16D=\"0123456789abcdef\";var b16M=new Array();for(var i=0;i<256;i++){b16M[i]=b16D.charAt(i>>4)+b16D.charAt(i&15);}\nvar result=new Array();for(var i=0;i<data.length;i++){result[i]=b16M[data.charCodeAt(i)];}\nreturn result.join(\"\");}\ncookieName=\"aperture_\"+hexEncode(rc4Encrypt(\"abcdm\",unescape(encodeURIComponent(window.location.href))));cookie=readCookie(cookieName);if(cookie){omnObject=typeLookup(\"omniture\",cookie);if(omnObject&&omnObject.prop9&&omnObject.eVar31){s_omni.prop9=omnObject.prop9;s_omni.eVar31=omnObject.eVar31;}}" }, { "alpha_fraction": 0.5443567633628845, "alphanum_fraction": 0.5523913502693176, "avg_line_length": 31.211332321166992, "blob_id": "8008c6d0d3cee4fc32680b561c3ca6ba2320f334", "content_id": "e0eba2030920409380b5a1272d7e72ad364e5066", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 21034, "license_type": "permissive", "max_line_length": 632, "num_lines": 653, "path": "/servers/demo-scaleout/html/nyc-5/trackingTags_v1.1.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "/*\n* $Id: trackingTags_v1.1.js 134621 2013-11-08 18:05:46Z leonardo.meirelles $\n*/\n\n// CONFIGURE HOST BASED ON ENVIRONMENT\nvar NYTD = NYTD || {};\nNYTD.Analytics = NYTD.Analytics || {};\nNYTD.Analytics.JSFileLoaded = NYTD.Analytics.JSFileLoaded || {};\n\n\nif ( !NYTD.Analytics.JSFileLoaded['trackingTags_v1.1.js'] ) {\n\n/* BEGIN ANALYTICS TRACKING */\n\n NYTD.Analytics.JSFileLoaded['trackingTags_v1.1.js'] = 1;\n\nNYTD.Hosts = NYTD.Hosts || (function(){\n var host, scripts = document.getElementsByTagName(\"script\");\n\n for (var i = 0, script; script = scripts[i]; i++) {\n host = script.src &&\n/^(.+\\.nytimes.com)\\/js\\/app\\/analytics\\/trackingTags_v1\\.1\\.js/.test(script.src) ? RegExp.$1 :'';\n if (host) { break };\n };\n\n return {\n imageHost: host,\n jsHost: host,\n cssHost: host\n }\n})();\n\n\n// START WEBTRENDS JS TAG\nvar gtrackevents=false;\nvar gdcsid=\"dcsym57yw10000s1s8g0boozt_9t1x\";\nvar gfpcdom=\".nytimes.com\";\nvar gdomain=\"wt.o.nytimes.com\";\nvar js_host = NYTD.Hosts.jsHost + \"/js/app/analytics/\";\n\nvar includeJsFile = function (incFilename, async) {\n\n var incFileJS = document.createElement(\"script\");\n incFileJS.setAttribute(\"type\", \"text/javascript\");\n incFileJS.setAttribute(\"src\", incFilename);\n if (async === true) {\n incFileJS.async = true;\n }\n document.getElementsByTagName(\"head\").item(0).appendChild(incFileJS);\n\n}\n\n// Include WebTrends wtid.js\nvar wt_initObj = { enabled:true, fpc:\"WT_FPC\", domain:gdomain, dcsid:gdcsid };\nif (wt_initObj.enabled&&(document.cookie.indexOf(wt_initObj.fpc+\"=\")==-1)&&(document.cookie.indexOf(\"WTLOPTOUT=\")==-1)){\nvar wtid_js_host=\"http\"+(window.location.protocol.indexOf('https:')==0?'s':'')+\"://\"+wt_initObj.domain+\"/\"+wt_initObj.dcsid+\"/\";\nincludeJsFile(wtid_js_host+'wtid.js');\n}\n\n//includeJsFile(js_host+'controller_v1.1.js');\nvar _missingController = true; // do not remove - bx-853\n// END WEBTRENDS JS TAG\n\n// AudienceScience block\n// Set data for AudienceScience\nvar _missingAudienceScience = true; // do not remove - bx-853\n/*\n(function () {\n var getMetaTag = function(tagName) {\n var metaTags = document.getElementsByTagName(\"meta\");\n for (var i in metaTags) { \n if (metaTags[i].name == tagName) {\n return metaTags[i].content;\n }\n }\n return \"\";\n }\n\n var addCategory = function(category, valueToAppend) {\n if (valueToAppend != \"\") {\n return category + \" > \" + valueToAppend;\n } else {\n return category;\n }\n }\n\n window.DM_prepClient = function(csid, client) {\n if (\"H07707\" == csid) {\n var contentGroup = getMetaTag(\"WT.cg_n\");\n if (contentGroup != \"Homepage\") {\n var catValue = \"NYTimesglobal\";\n catValue = addCategory(catValue, contentGroup);\n catValue = addCategory(catValue, getMetaTag(\"WT.cg_s\"));\n client.DM_cat(catValue); \n }\n } // if H07707 \n }\n\n // AudienceScience script tag \n includeJsFile('http://js.revsci.net/gateway/gw.js?csid=H07707&auto=t');\n}());\n*/\n// End AudienceScience block\n\n// Duped in common.js\n(function(){\n if (NYTD.require) {\n return;\n }\n \n var windowLoaded = false;\n var document_scripts;\n \n if (window.addEventListener) {\n window.addEventListener (\"load\", function(){ windowLoaded = true }, false);\n } else if (window.attachEvent) {\n window.attachEvent (\"onload\", function(){ windowLoaded = true });\n }\n \n function scriptLoaded(src) {\n document_scripts = document_scripts || {};\n \n if (document_scripts[src]) { return true; }\n else {\n var script_tags= document.getElementsByTagName(\"script\");\n for (var i = 0, script; script = script_tags[i]; i++) {\n if(script.src) { document_scripts[script.src] = 1; }\n };\n if (document_scripts[src]) { return true; }\n else { return false; }\n }\n \n }\n\n NYTD.require = function(file, callback) {\n \n if (windowLoaded) { throw('Cannot require file, document is already loaded'); } \n\n // If matches root relative url (single slash, not protocol-agnostic double slash)\n var url = /^\\/[^\\/]/.test(file) ? NYTD.Hosts.jsHost + file : file;\n var force = arguments[arguments.length - 1] === true;\n var needsCallbackScriptTag;\n \n if (force || !scriptLoaded(url)) { \n document.write('<script src=\"' + url + '\" type=\"text/javascript\" charset=\"utf-8\" onerror=\"throw(\\'NYTD.require: An error occured: \\' + this.src)\"><\\/script>');\n document_scripts[url] = 1;\n needsCallbackScriptTag = true;\n }\n\n if (typeof callback == 'function') {\n\n if (document.addEventListener && !navigator.userAgent.match(/MSIE/)) {\n if (needsCallbackScriptTag) { \n document.write('<script type=\"text/javascript\" charset=\"utf-8\">(' + callback.toString() + ')();<\\/script>');\n }\n else {\n window.setTimeout(function(){\n callback()\n }, 0)\n }\n }\n else {\n NYTD.require.callbacks = NYTD.require.callbacks || [];\n NYTD.require.callbacks.push(callback);\n NYTD.require.callbacks.count = (++NYTD.require.callbacks.count) || 0;\n document.write(\"<script id=__onAfterRequire\" + NYTD.require.callbacks.count + \" src=//:><\\/script>\");\n document.getElementById(\"__onAfterRequire\" + NYTD.require.callbacks.count).onreadystatechange = function() {\n if (this.readyState == \"complete\") {\n this.onreadystatechange = null;\n (NYTD.require.callbacks.pop())();\n this.parentNode.removeChild(this);\n }\n };\n }\n\n }\n\n };\n})();\n\n// comscore tagging\n(function () {\n var scgMetaValue, comscoreKeyword;\n var comscoreMappingKey = [];\n var pageUrl = window.location.href;\n var cgMetaTags = document.getElementsByName('CG');\n var scgMetaTags = document.getElementsByName('SCG');\n var comscoreConfig = [ \n 'c1=2', \n 'c2=3005403'\n ];\n var comscoreKeywordMappingObj = {\n \"business\" : \"business\",\n \"business - global\" : \"global\",\n \"business - international\" : \"global\",\n \"Business Day - Dealbook\" : \"dealbook\",\n \"business - economy\" : \"economy\",\n \"business - energy-environment\" : \"energy_environment\",\n \"business - media\" : \"media\",\n \"business - smallbusiness\" : \"smallbusiness\",\n \"your-money\" : \"your_money\",\n \"Business Day - Economy\" : \"economix\",\n \"Business - Media and Advertising\" : \"mediadecoder\",\n \"Business Day - Small Business\" : \"boss\",\n \"Business Day - Your Money\" : \"bucks\",\n \"Business - Markets\" : \"markets\",\n \"Autos - wheels\" : \"wheels\",\n \"Science - Environment\" : \"green\",\n \"technology\" : \"technology\",\n \"technology - personaltech\" : \"personaltech\",\n \"Technology - bits\" : \"bits\",\n \"Technology - Personal Tech\" : \"gadgetwise\",\n \"Technology - pogue\" : \"pogue\",\n \"General - open\" : \"open\",\n \"style\" : \"style\",\n \"fashion\" : \"fashion\",\n \"dining\" : \"dining\",\n \"garden\" : \"garden\",\n \"fashion - weddings\" : \"weddings\",\n \"t-magazine\" : \"t_magazine\",\n \"T:Style - tmagazine\" : \"t_style\",\n \"Style - Dining\" : \"dinersjournal\",\n \"Style - Fashion\" : \"runway\",\n \"Style - parenting\" : \"parenting\",\n \"arts\" : \"arts\",\n \"arts - design\" : \"design\",\n \"books\" : \"books\",\n \"arts - dance\" : \"dance\",\n \"movies\" : \"movies\",\n \"arts - music\" : \"music\",\n \"arts - television\" : \"television\",\n \"theater\" : \"theater\",\n \"arts - video-games\" : \"video_games\",\n \"Arts - Event Search\" : \"event_search\",\n \"Arts - artsbeat\" : \"artsbeat\",\n \"Movies - carpetbagger\" : \"carpetbagger\",\n \"health\" : \"health\",\n \"health - research\" : \"research\",\n \"health - nutrition\" : \"nutrition\",\n \"health - policy\" : \"policy\",\n \"health - views\" : \"views\",\n \"Health - Health Guide\" : \"health_guide\",\n \"Health - well\" : \"well\",\n \"Health - newoldage\" : \"newoldage\",\n \"Health - consults\" : \"consults\",\n \"science\" : \"science\",\n \"science - earth\" : \"earth\",\n \"science - space\" : \"space\",\n \"Science - Environment\" : \"green\",\n \"Science - scientistatwork\" : \"scientistatwork\",\n \"Opinion - dotearth\" : \"dotearth\"\n };\n\n if (cgMetaTags.length > 0) {\n comscoreMappingKey.push(cgMetaTags[0].content);\n }\n if (scgMetaTags.length > 0) {\n scgMetaValue = scgMetaTags[0].content;\n if (scgMetaValue !== \"\") {\n comscoreMappingKey.push(scgMetaValue);\n }\n }\n comscoreKeyword = comscoreKeywordMappingObj[comscoreMappingKey.join(' - ')];\n\n if (pageUrl.indexOf(\"markets.on.nytimes.com\") !== -1) { // check if its a markets page\n if (pageUrl.indexOf(\"analysis_tools\") !== -1) {\n comscoreKeyword = \"analysis_tools\";\n }\n else if (pageUrl.indexOf(\"screener\") !== -1) {\n comscoreKeyword = \"screener\";\n }\n else if (pageUrl.indexOf(\"portfolio\") !== -1) {\n comscoreKeyword = \"portfolio\";\n }\n }\n\n if (comscoreKeyword) {\n comscoreConfig.push('comscorekw=' + comscoreKeyword);\n }\n\n var callback = function() {\n var udmURL = 'http'+(document.location.href.charAt(4)=='s'?'s://sb':'://b')+'.scorecardresearch.com/b?';\n udmURL += comscoreConfig.join('&');\n\n // Vendor code\n function udm_(a){var b=\"comScore=\",c=document,d=c.cookie,e=\"\",f=\"indexOf\",g=\"substring\",h=\"length\",i=2048,j,k=\"&ns_\",l=\"&\",m,n,o,p,q=window,r=q.encodeURIComponent||escape;if(d[f](b)+1)for(o=0,n=d.split(\";\"),p=n[h];o<p;o++)m=n[o][f](b),m+1&&(e=l+unescape(n[o][g](m+b[h])));a+=k+\"_t=\"+ +(new Date)+k+\"c=\"+(c.characterSet||c.defaultCharset||\"\")+\"&c8=\"+r(c.title)+e+\"&c7=\"+r(c.URL)+\"&c9=\"+r(c.referrer),a[h]>i&&a[f](l)>0&&(j=a[g](0,i-8).lastIndexOf(l),a=(a[g](0,j)+k+\"cut=\"+r(a[g](j+1)))[g](0,i)),c.images?(m=new Image,q.ns_p||(ns_p=m),m.src=a):c.write(\"<\",\"p\",\"><\",'img src=\"',a,'\" height=\"1\" width=\"1\" alt=\"*\"',\"><\",\"/p\",\">\")}\n\n udm_(udmURL);\n };\n\n var s = document.createElement(\"script\"),\n el = document.getElementsByTagName(\"script\")[0];\n s.async = true;\n s.src = (document.location.protocol == \"https:\" ? \"https://sb\": \"http://b\") + \".scorecardresearch.com/c2/3005403/cs.js\";\n if (s.addEventListener) { // normal browsers\n s.addEventListener('load', function() {\n callback();\n }, false);\n } \n else {\n s.onreadystatechange = function() { // old IEs\n if (s.readyState in {loaded: 1, complete: 1}) {\n s.onreadystatechange = null;\n callback();\n }\n };\n }\n el.parentNode.insertBefore(s, el);\n})(); // end comscore tagging\n\n// Nielsen tagging\n(function () {\n var d = new Image(1, 1);\n d.onerror = d.onload = function () {\n d.onerror = d.onload = null;\n };\n d.src = [\"//secure-us.imrworldwide.com/cgi-bin/m?ci=us-nytimes&cg=0&cc=1&si=\",\n escape(window.location.href), \"&rp=\", escape(document.referrer),\n \"&ts=compact&rnd=\", (new Date()).getTime()].join('');\n})();\n\n// Charbeat beacon\nfunction isGlobalEdition() {\n var edition = unescape(document.cookie).match('NYT-Edition=([^;]+)');\n return (edition && edition[1] && edition[1].indexOf(\"edition|GLOBAL\") !== -1);\n}\n\n// forms chartbeat domain based on the environment and edition\nfunction getChartbeatDomain() {\n var domain = '';\n if (isGlobalEdition()) {\n domain = \"international.nytimes.com\";\n if (NYTD.env === \"staging\") {\n domain = \"international.stg.nytimes.com\";\n }\n } else {\n domain = \"nytimes.com\";\n if (NYTD.env === \"staging\") {\n domain = \"stg.nytimes.com\";\n }\n }\n return domain;\n}\n\nvar _sf_async_config = {\n uid: 16698,\n domain: getChartbeatDomain(),\n pingServer: \"pnytimes.chartbeat.net\",\n path:window.location.pathname,\n title: window.TimesPeople && TimesPeople.Page && TimesPeople.Page.getTitle() || document.title.replace('- NYTimes.com', '')\n};\n\ntry {\n _sf_async_config.sections = [document.getElementsByName('CG')[0].content, document.getElementsByName('SCG')[0].content].join(\",\");\n} catch(e){}\n\ntry {\n _sf_async_config.authors = (document.getElementsByName('byl')[0] || document.getElementsByName('CLMST')[0]).content.replace('By ', '').toLowerCase().replace(/\\b[a-z]/g, function(){return arguments[0].toUpperCase();});\n} catch(e){}\n\n (function() {\n function loadChartbeat() {\n window._sf_endpt = (new Date()).getTime();\n includeJsFile(((\"https:\" == document.location.protocol) ? \"https://a248.e.akamai.net/chartbeat.download.akamai.com/102508/\" : \"http://static.chartbeat.com/\") + \"js/chartbeat.js\");\n }\n \n if (window.addEventListener) {\n window.addEventListener('load', loadChartbeat, false);\n } else if (window.attachEvent) {\n window.attachEvent('onload', loadChartbeat);\n } \n\n })();\n\n// UPTracker\nvar NYTD = NYTD || {};\nif (! NYTD.Hosts) NYTD.Hosts = {};\nif (! NYTD.Hosts.jsHost) NYTD.Hosts.jsHost = \"http://js.nyt.com\";\nNYTD.UPTracker = (function () {\n \n // default configuration\n var config = {\n baseUrl: '//up.nytimes.com/?',\n defaultArguments: 'd=0//&c=1'\n };\n\n var url;\n \n function init (params) {\n\n if (params.baseUrl) {\n config.baseUrl = params.baseUrl;\n }\n if (params.eventType) {\n config.eventType = params.eventType;\n }\n if (params.data) {\n config.data = params.data;\n }\n if (params.userID) {\n config.userID = params.userID;\n }\n \n config.url = params.url || window.location.href;\n };\n \n function createUrl() {\n \n // begin with baseUrl\n url = config.baseUrl + config.defaultArguments;\n \n // append eventType\n if (config.eventType) {\n url += '&e=' + config.eventType;\n }\n\n // add user id if we have one\n if (config.userID) {\n url += '&ui=' + config.userID;\n }\n \n // url encode and append url\n url += '&u=' + encodeURIComponent(config.url);\n \n // url encode and append referrer\n url += '&r=' + encodeURIComponent(document.referrer);\n\n // if we have meta data, encode and append it\n if (config.data) {\n try {\n JSON.stringify({world:'peace'});\n appendAndSend(); \n } catch (e) { // if no JSON, inlcude json2-min\n var script = document.createElement('script');\n script.type = \"text/javascript\";\n script.src = \"//www.nytimes.com/js/app/lib/json/json2-min.js\";\n script.onload = function () { \n appendAndSend(); \n };\n script.onreadystatechange = function () {\n if (this.readyState == 'loaded' || this.readyState == 'complete') {\n appendAndSend(); \n }\n };\n \n document.getElementsByTagName(\"head\")[0].appendChild(script);\n }\n } else {\n send();\n }\n }; \n\n function appendAndSend() {\n var jsonData = JSON.stringify(config.data);\n if (jsonData) {\n url += '&p=' + encodeURIComponent(jsonData);\n }\n send ();\n }\n \n function send() {\n if (url) {\n var img = document.createElement('img');\n img.setAttribute('border', 0);\n img.setAttribute('height', 0);\n img.setAttribute('width', 0);\n img.setAttribute('src', url);\n document.body.appendChild(img);\n } else {\n return false;\n }\n };\n\n return {\n track: function (params) {\n var params = params || {};\n init(params);\n createUrl();\n },\n check: function (){\n var imageTags = document.getElementsByTagName('img');\n var UPTcalled = false;\n var pattern = /up\\.nytimes\\.com\\//;\n for (var i=0; i < imageTags.length; i++){\n if ( pattern.test(imageTags[i].src)){\n UPTcalled = true;\n break;\n }\n }\n if (!UPTcalled) {\n NYTD.UPTracker.track(); // set generic UPT call if not available on page load\n }\n }\n };\n})();\n\nif (window.addEventListener) {\n window.addEventListener('load', NYTD.UPTracker.check, false);\n\n} else if (window.attachEvent) {\n window.attachEvent('onload', NYTD.UPTracker.check);\n}\n\n\n/*jslint browser: true, devel: true, maxerr: 50, indent: 3 */\n/*global NYTD, includeJsFile */\n(function (root, factory) {\n \"use strict\";\n var\n env = null,\n success = false,\n NYTD = root.NYTD,\n getHost,\n i,\n requirejs_valid,\n required_libs = [\"foundation/hosts\"],\n requirejs_track_lib_name = \"foundation/lib/tracking\";\n\n // Define the function that handles the environment discovery.\n getHost = function () {\n var\n host = null,\n STATIC_HTTP = {\n \"prd\": \"//graphics8.nytimes.com\",\n \"stg\": \"//static.stg.nytimes.com\",\n \"dev\": \"//static.dev.nytimes.com\"\n },\n STATIC_HTTPS_PROD = \"//static.nytimes.com\";\n\n // By default, host points to Production.\n if (location.protocol === \"https:\") {\n host = STATIC_HTTPS_PROD;\n } else {\n host = STATIC_HTTP[\"prd\"];\n }\n\n // Get the environment from NYTD.env\n if (typeof NYTD === \"object\") {\n if (typeof NYTD.env === \"string\") {\n env = NYTD.env;\n } else if (typeof NYTD.Host === \"object\" && typeof NYTD.Host.getEnv === \"function\") {\n env = NYTD.Host.getEnv();\n }\n }\n // Check the environment.\n if (env !== null) {\n switch (env) {\n case \"staging\":\n case \"stg\":\n host = STATIC_HTTP[\"stg\"];\n break;\n case \"development\":\n case \"dev\":\n host = STATIC_HTTP[\"dev\"];\n break;\n }\n } else {\n // Environment is not available, use the URL location.\n if (/\\.stg\\.nytimes\\.com$/.test(location[\"hostname\"]) === true) {\n host = STATIC_HTTP[\"stg\"];\n } else if (/\\.dev\\.nytimes\\.com$/.test(location[\"hostname\"]) === true) {\n host = STATIC_HTTP[\"dev\"];\n }\n }\n\n // Return the hostname.\n return host;\n };\n\n // Retrieve hosts from require js library.\n requirejs_valid = true;\n if (typeof require === \"function\" && typeof require.defined === \"function\") {\n if (typeof define === \"function\" && typeof define.amd === \"object\" && typeof requirejs === \"function\") {\n // Need to check if foundation/hosts is defined.\n for (i = 0; i < required_libs.length; i += 1) {\n requirejs_valid = requirejs_valid && (requirejs.defined(required_libs[i]) === true);\n }\n if (requirejs_valid === true) {\n // For development purposes, undefined the requirejs_track_lib_name.\n requirejs.undef(requirejs_track_lib_name);\n define(\n requirejs_track_lib_name,\n required_libs,\n function (hosts) {\n var\n host = null;\n\n if (typeof hosts === \"object\" && typeof hosts.js === \"string\") {\n host = hosts.js;\n } else {\n host = getHost();\n }\n return host;\n }\n );\n\n // Call the function to set up the lib.\n require(\n [requirejs_track_lib_name],\n function (host) {\n // Load from required hosts.\n factory(host);\n }\n );\n } else {\n factory(getHost());\n }\n\n // Confirmation that factory was called.\n success = true;\n }\n }\n\n // // If define and requirejs functions doesn't exists.\n if (success === false) {\n factory(getHost());\n }\n}(\n this,\n function (host) {\n \"use strict\";\n var\n src,\n script, loadList;\n\n // Host.jshost is not reliable.\n if (/\\/\\/www\\.(stg\\.|dev\\.)?nytimes\\.com$/.test(host) === true) {\n host = host.replace(/\\/\\/www\\.(stg\\.|dev\\.)?nytimes\\.com$/, \"//static.$1nytimes.com\");\n }\n\n // Load the script.\n loadList = [\n {src : host + \"/bi/js/analytics/EventTracker.js\", async: false},\n {src : host + \"/bi/js/tagx/tagx.js\", async: true}\n ];\n\n for(var s = 0; s < loadList.length; s++) {\n src = loadList[s].src;\n if (typeof includeJsFile === \"function\") {\n includeJsFile(src, loadList[s].async); \n } else {\n // Include manually.\n script = document.createElement(\"script\");\n script.src = src;\n document.body.appendChild(script);\n }\n }\n }\n));\n\n/* END ANALYTICS TRACKING */\n/* NOTE: ALL NEW CODE NEEDS TO BE ADDED ABOVE THIS LINE */\n}\n" }, { "alpha_fraction": 0.5914086103439331, "alphanum_fraction": 0.6813187003135681, "avg_line_length": 57.882354736328125, "blob_id": "12b020f8423c138eef9392dbcaf75b14cb41d56e", "content_id": "5fe6ce3bc9e2403b394d7dd2c2862a393e4941c0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1001, "license_type": "permissive", "max_line_length": 335, "num_lines": 17, "path": "/client/scaleout/scaleout/traffic-ecc.py", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport subprocess\nimport traceback\nfrom datetime import datetime\n\n\nwhile True:\n print '-----> STARTING NEW LOOP'\n try:\n #cmd = 'while true; do ab -n 100000 -c 5 -f TLS1.0 -Z ECDHE-ECDSA-AES256-SHA https://scaleout.demovip.avi.local/100k.dat & ab -n 100000 -c 5 -f TLS1.1 -Z ECDHE-ECDSA-AES256-SHA https://scaleout.demovip.avi.local/100k.dat & ab -n 100000 -c 5 -f TLS1.2 -Z ECDHE-ECDSA-AES256-SHA https://scaleout.demovip.avi.local/100k.dat; done'\n cmd = 'ab -n 100000 -c 5 -f TLS1.0 -Z ECDHE-ECDSA-AES256-SHA https://scaleout.demovip.avi.local/100k.dat & ab -n 100000 -c 5 -f TLS1.1 -Z ECDHE-ECDSA-AES256-SHA https://scaleout.demovip.avi.local/100k.dat & ab -n 100000 -c 5 -f TLS1.2 -Z ECDHE-ECDSA-AES256-SHA https://scaleout.demovip.avi.local/100k.dat'\n result = subprocess.check_output(cmd, shell=True)\n except:\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+exception_text)\n print 'ERROR - restarting'\n" }, { "alpha_fraction": 0.4360189437866211, "alphanum_fraction": 0.4528220593929291, "avg_line_length": 22.683673858642578, "blob_id": "9e3162c155dbd5ddf5038a6cc551982d54ffc069", "content_id": "c18dc64602f13b30e774d9e8ddfe89dd5091f02d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2321, "license_type": "permissive", "max_line_length": 72, "num_lines": 98, "path": "/servers/demo-scaleout/html/gen_response.php", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "<?php\n\t$chunkcount = 10;\n\tif (isset($_GET['chunkcount'])){\n \t$chunkcount = (int)$_GET['chunkcount'];\n\t}\n $chunksize = 4096;\n\tif (isset($_GET['chunksize'])){\n\t\t$chunksize = (int)$_GET['chunksize'];\n\t}\n $sleeptime = 10;\n\tif (isset($_GET['sleeptime'])){\n\t\t$sleeptime = (int)$_GET['sleeptime'];\n\t}\n $type = 'str';\n\tif (isset($_GET['type'])){\n\t\t$type = $_GET['type'];\n\t}\n $hide = '';\n\tif (isset($_GET['hide'])){\n\t\t$hide = $_GET['hide'];\n\t}\n\n function generateBinaryData($length = 4096) {\n $string = '';\n foreach (range( 0x00, 0x1F ) as $i) {\n $string .= chr($i);\n }\n return $string; \n }\n\tfunction generateRandomData($length = 4096) {\n \t$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n \t$randomString = '';\n \tfor ($i = 0; $i < $length; $i++) {\n \t$randomString .= $characters[rand(0, strlen($characters) - 1)];\n \t}\n \treturn $randomString;\n\t}\n\tfunction generateRandomSparseData($length = 4096) {\n \t$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n \t$randomString = '';\n $indx = rand(0, 5*strlen($characters) - 1);\n \tfor ($i = 0; $i < $length; $i++) {\n if ($indx < strlen($characters)) {\n $randomString .= $characters[$indx];\n }\n else {\n $randomString .= ' ';\n }\n \t}\n \treturn $randomString;\n\t}\n\n $string = '';\n if ($type == 'sparse') {\n $string = generateRandomSparseData($chunksize);\n }\n elseif ($type == 'bin') {\n \t$string = generateBinaryData($chunksize);\n }\n else {\n $string = generateRandomData($chunksize);\n }\n\n if ($type == 'html') {\n if (strpos($hide, 'H') === false) {\n echo '<html>'; \n }\n if (strpos($hide, 'D') === false) {\n echo '<head>';\n }\n echo $string;\n if (strpos($hide, 'd') === false) {\n echo '</head>'; \n }\n if (strpos($hide, 'B') === false) {\n echo '<body>';\n }\n echo flush(); \n }\n\t$loop = 0;\n\twhile ($loop < $chunkcount)\n\t{\n\t\techo $string;\n\t\tflush();\n\t\t$loop ++;\n\t\tsleep($sleeptime/1000);\n\t}\n\n if ($type == 'html') {\n if (strpos($hide, 'b') === false) {\n echo '</body>'; \n } \n if (strpos($hide, 'h') === false) {\n echo '</html>';\n }\n echo flush();\n }\n?>\n" }, { "alpha_fraction": 0.5987546443939209, "alphanum_fraction": 0.6132004857063293, "avg_line_length": 46.514793395996094, "blob_id": "79c8d18fadd389536dcfd05bdbc10bcc4ba0fb72", "content_id": "28714c09df3def48588ff1202137deff0e9e1c59", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 24090, "license_type": "permissive", "max_line_length": 321, "num_lines": 507, "path": "/servers/demo-scaleout/html/nyc-1/recommendationsModule.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "/**\n * \n * $Id: recommendationsModule.js 135430 2013-11-19 15:19:13Z shawn.gao $\n * \n */\n var NYTD = NYTD || {};\n NYTD.mostPopWidget = (function() {\n \n // Config\n\n var mostPoplimit = 10;\n NYTD.MostPop = {};\n \n // Service URLs\n var mostEmailedUrl = '/svc/most-popular/getdata.json?type=mostemailed';\n var mostViewedUrl = '/svc/most-popular/getdata.json?type=mostviewed';\n var recommendedUrl = '/svc/recommendations/v3/personalized.json?access_key=71DA1628-4BDA-436F-9E36-13ED89326228';\n \n // Default User Pic URL\n var default_user_pic_url = NYTD.Hosts.imageHost + \"/images/apps/timespeople/none.png\";\n \n // Get page content type\n NYTD.MostPop.CG = $$('meta[name=CG]')[0].content;\n NYTD.MostPop.PST = $$('meta[name=PST]')[0].content;\n if (NYTD.MostPop.CG == \"Homepage\") {\n NYTD.MostPop.contentType = 'Homepage';\n mostEmailedUrl += '&hp=1';\n mostViewedUrl += '&hp=1';\n recommendedUrl += '&hp=1';\n } else if (NYTD.MostPop.CG == 'opinion') {\n NYTD.MostPop.contentType = 'Opinion';\n } else if (NYTD.MostPop.CG == 'Member Center' && NYTD.MostPop.PST == 'Error Page') {\n NYTD.MostPop.contentType = 'Error Page';\n }\n \n // Loading Logger\n\n NYTD.MostPop.EventLog = {\n \"mostPopContentRecommendations\" : \"unloaded\",\n \"mostPopContentMostEmailed\" : \"unloaded\",\n \"mostPopContentMostViewed\" : \"unloaded\"\n };\n\n \tfunction activateRecommended() {\n \t $('mostPopTabRecommendations').setStyle({\"display\":\"block\"}).addClassName('selected');\n \t $('mostPopTabMostEmailed').setStyle({\"display\":\"block\"}).removeClassName('selected');\n \t $('mostPopContentMostEmailed').setStyle({\"display\":\"none\"}).removeClassName('tabContentActive');\n \t $('mostPopContentRecommendations').setStyle({\"display\":\"block\"}).addClassName('tabContentActive');\n\n \t $('mostPopTabMostViewed').setStyle({\"display\":\"none\"}).removeClassName('selected');\n \t $('mostPopContentMostViewed').setStyle({\"display\":\"none\"}).removeClassName('tabContentActive');\n\n \t $$('.showRecommended').each(function(el){\n \t el.setStyle({\"display\":\"none\"});\n \t });\n\n if (NYTD.MostPop.EventLog['mostPopContentRecommendations'] != \"loaded\") loadData(recommendedUrl, 'mostPopContentRecommendations');\n setCookie('nyt-recommend', '1', {domain : 'nytimes.com', path : '/', expires : 30});\n \t}\n\n \tfunction deactivateRecommended(auto) {\n \t $('mostPopTabMostViewed').setStyle({\"display\":\"block\"});\n \t $('mostPopTabMostEmailed').setStyle({\"display\":\"block\"}).addClassName('selected');\n \t $('mostPopContentMostEmailed').setStyle({\"display\":\"block\"}).addClassName('tabContentActive');\n\n \t $('mostPopTabRecommendations').setStyle({\"display\":\"none\"}).removeClassName('selected');\n \t $('mostPopContentRecommendations').setStyle({\"display\":\"none\"}).removeClassName('tabContentActive');\n\n \t $$('.showRecommended').each(function(el){\n \t el.setStyle({\"display\":\"block\"});\n \t });\n\n if (NYTD.MostPop.EventLog['mostPopContentMostEmailed'] != \"loaded\") loadData(mostEmailedUrl, 'mostPopContentMostEmailed');\n if (auto !== true) {\n setCookie('nyt-recommend', '0', {domain : 'nytimes.com', path : '/', expires : 30});\n }\n \t}\n\n // Ajax Calls\n\n \tfunction loadData(url, id) {\n \tnew Ajax.Request(url, {\n method: 'get',\n onComplete: function(transport) {\n\n try { var response = transport.responseText.evalJSON(); } \n catch(e) {\n errorMessage($(id));\n }\n\n switch(id)\n {\n case \"mostPopContentRecommendations\":\n NYTD.MostPop.loggedIn = (response.uid > 0);\n var json = response.suggestions; \n NYTD.MostPop.num_articles = response.num_articles || \"0\";\n NYTD.MostPop.user_displayname = response.user_displayname || \"\";\n NYTD.MostPop.user_pic_url = response.user_pic_url || default_user_pic_url;\n var tracking = (NYTD.MostPop.contentType == \"Homepage\") ? '?src=rechp' : '?src=recg';\n break;\n case \"mostPopContentMostEmailed\":\n var json = response.articles;\n var tracking = '?src=me&ref=general';\n break;\n case \"mostPopContentMostViewed\":\n var json = response.articles;\n var tracking = '?src=mv&ref=general';\n break;\n default:\n var json = response.articles;\n var tracking = '?src=mv&ref=general';\n }\n if (json && json.length > 0) {\n populateMostPop(json, $(id), tracking, id);\n if (id == \"mostPopContentRecommendations\") setupRecommended();\n NYTD.MostPop.EventLog[id] = \"loaded\";\n } else { \n if (id == \"mostPopContentRecommendations\" && !NYTD.MostPop.autoRecOff) { \n deactivateRecommended(true);\n NYTD.MostPop.autoRecOff = true; \n } else {\n errorMessage($(id));\n } \n }\n \t\t\t\t $$('#'+id+' .loader').invoke('remove');\n },\n onFailure: function(transport) {\n errorMessage($(id));\n }\n }); \n }\n\n \tfunction setupRecommended() {\n \t if($('recommendedFooter')) $('recommendedFooter').setStyle({\"display\":\"block\"});\n \t if (NYTD.MostPop.loggedIn) {\n \t $('mostPopContentRecommendations').insert({ top : '<div id=\"recommendedHeader\" class=\"opposingFloatControl wrap\" style=\"display: none;\">\\\n \t\t\t\t<div class=\"element1\"><span id=\"articlesPastMonth\">'+ NYTD.MostPop.num_articles +'</span> articles viewed recently</div>\\\n \t\t\t\t<div class=\"element2\"><p><img class=\"runaroundRight user_pic\" src=\"'+ NYTD.MostPop.user_pic_url +'\" /><strong>'+ NYTD.MostPop.user_displayname.truncate(25) +'</strong><br /><a href=\"http://www.nytimes.com/recommendations\">All Recommendations</a></p></div></div>'});\n\n \t if($('recommendedHeader')) $('recommendedHeader').setStyle({\"display\":\"block\"});\n \t $$('#recommendedFooter .loggedIn').invoke('setStyle', {\"display\":\"block\"});\n \t $$('#recommendedFooter .loggedOut').invoke('setStyle', {\"display\":\"none\"});\n \t } else {\n \t if($('recommendedHeader')) $('recommendedHeader').remove();\n \t $$('#recommendedFooter .loggedIn').invoke('setStyle', {\"display\":\"none\"});\n \t $$('#recommendedFooter .loggedOut').invoke('setStyle', {\"display\":\"block\"});\n \t }\n \t}\n\n \t// Create Error Message\n\n \tfunction errorMessage(target) {\n \t\tif(target == $(\"mostPopContentRecommendations\")){\n \t\t errorHTML = '<div class=\"errorMessage\"><p><b>We don&rsquo;t have any personalized recommendations for you at this time. Please try again later.</b></p></div>';\n \t\t target.childElements().each(function(el){\n el.setStyle({\"display\":\"none\"});\n });\n if($('recommendedFooter')) $('recommendedFooter').setStyle({\"display\":\"block\"});\n if(NYTD.MostPop.loggedIn) {\n \t $$('#recommendedFooter .general').invoke('setStyle', {\"display\":\"block\"});\n \t } else {\n \t $$('#recommendedFooter .loggedOut').invoke('setStyle', {\"display\":\"block\"});\n \t }\n \t } else {\n \t errorHTML = '<div class=\"errorMessage\"><p><b>This article list is not currently available. Please try again later.</b></p></div>';\n \t }\n target.select('.loader').invoke('remove');\n target.select('.errorMessage').invoke('remove');\n \t\ttarget.insert({ top : errorHTML});\n \t}\n \n // Inject HTML\n function populateMostPop(item, target, tracking, id) { \n // Build HTML\n var mostPopHTML = '<table class=\"leftAlignedMostPop\"><tbody>';\n var img = \"\";\n var kicker;\n for (var i=0, len = item.length; i < len; i++) {\n var title = item[i].title;\n if (i >= mostPoplimit) {\n break;\n }\n if (id == \"mostPopContentRecommendations\") {\n if (item[i].item_type == \"Video\") {\n title = \"Video: \"+item[i].title;\n }\n }\n if (NYTD.MostPop.contentType !== \"Homepage\") {\n if (item[i].thumbnail != null) { \n var img = '<td class=\"mostPopularImg\"><a title=\"Click to go to this article\" href=\"'+item[i].url + tracking +'\"><img src=\"'+item[i].thumbnail.url+'\"></a></td>'; \n } \n else { \n var img = \"<td></td>\"; \n }\n }\n if (item[i].kicker != null) {\n if (item[i].kicker === \"Op-Ed Columnist\") {\n kicker = item[i].byline.substr(3);\n }\n else {\n kicker = item[i].kicker;\n } \n } \n else { \n kicker = \"\"; \n }\n mostPopHTML += '<tr>'+ \n img +'<td class=\"listNumber\">'+ \n (i+1) +'.</td><td class=\"mostPopularTitle\"><h6 class=\"kicker\">'+ kicker + '</h6><h4><a title=\"Click to go to this article\" href=\"'+\n item[i].url + tracking +'\">'+\n title+'</a></h4></td></tr>\\n';\n }\n mostPopHTML += '</tbody></table>';\n //Clean Up existing stuff\n var existingTable = target.select('table.leftAlignedMostPop');\n var isTable = existingTable.length;\n if (!isTable) {} \n else { \n existingTable[0].remove();\n }\n var errors = target.select('.errorMessage');\n var isError = errors.length;\n if (!isError) {} \n else { \n errors[0].remove();\n }\n // Print \n target.insert({ top : mostPopHTML});\n }\n \n // New CSS styles\n \tvar cssStyle = '#mostPopWidget.doubleRule { background:url(\"'+ NYTD.Hosts.imageHost +'/images/global/borders/aColumnHorizontalBorder.gif\") repeat-x scroll 0 16px transparent !important; border-width:0 !important; clear:both; height:auto !important; margin-bottom:0 !important; } \\\n #mostPopWidget .kicker{ margin:0; font-size:10px !important; font-family: arial, helvetica, sans-serif; font-weight:normal; text-transform:uppercase;}\\\n #mostPopWidget h4{ font-weight: bold }\\\n #mostPopWidget ol{display:none;}\\\n #mostPopWidget #tabsContainer{position:static; bottom:0; left:0 !important}\\\n #mostPopWidget .tabs{padding:0 0 0 6px !important;text-transform:uppercase; margin-bottom: -1px; }\\\n #mostPopWidget .tabs li{ width:150px;border-top-width:0 !important;border-right-width:0 !important;border-bottom-width:0 !important;border-left-width:0 !important;background:none;text-align:center;height:24px !important;line-height:2.25em;margin:0 -2px 0 0 !important;padding-top:13px !important ;font-weight:bold;}\\\n #mostPopWidget .tabs li.selected{ background:url(\"'+ NYTD.Hosts.imageHost +'/images/recommendations/plainTab160Tall.gif\") no-repeat scroll center bottom !important;border-right:0 none !important;margin:0 0 0 0 !important;height:23px !important;}\\\n #mostPopWidget .tabContent{ padding:4px 0 0 0;border:0;border-top:1px solid #cacaca;}\\\n #mostPopWidget .tabContent .loader {text-align: center; padding:40px 0; }\\\n #mostPopWidget .tabContent .loader img { width:18px; height: 18px; }\\\n #mostPopWidget .tabContent table{border-collapse:collapse; width:100%; }\\\n #mostPopWidget .tabContent table td{text-align:left !important; font-size:13px !important; height:35px; vertical-align:top; padding:6px 0 4px 0; border-bottom:1px solid #E2E2E2;}\\\n #mostPopWidget .tabContent table tr.last td{border-bottom:0px;}\\\n #mostPopWidget .tabContent table td.listNumber{padding:6px 10px 4px 3px;font-size:1.3em; text-align:right !important}\\\n #mostPopWidget .tabContent table td.mostPopularImg{width:30px; padding: 4px 6px 4px 0; }\\\n #mostPopWidget .tabContent table td.mostPopularTitle{padding-top:7px;}\\\n #mostPopWidget .tabContent table.leftAlignedMostPop td.mostPopularImg{ padding-right:6px; }\\\n #mostPopWidget .tabContent table.rightAlignedMostPop td.mostPopularImg{ padding-right:0px; padding-left:6px; }\\\n #mostPopWidget .tabContent td.mostPopularImg img{ width:48px;}\\\n #mostPopWidget .tabContent h4{ font-weight:normal; text-align:left !important; text-transform:none !important; font-size:13px !important;line-height:1.15em !important;margin-bottom:3px !important;font-family:georgia,\"times new roman\",times,serif !important;}\\\n \t\t#mostPopWidget .mostFooter { font-family: arial, helvetica, sans-serif; margin:8px 0 0 0;}\\\n \t\t#mostPopWidget .mostFooter p {font-size: 11px;} \\\n \t\t#articlesPastMonth { font-size: 34px; margin-right: 9px; float:left; line-height:30px}\\\n \t\t#recommendedHeader {border-bottom: 1px solid #E2E2E2; font-size: 1.2em; font-family: arial, helvetica, sans-serif; padding:7px 2px 7px 10px}\\\n \t\t#recommendedHeader .element1{ width: 160px }\\\n \t\t#recommendedHeader .element2{ width: 160px }\\\n \t\t#recommendedHeader .element2 img{ height:25px; }\\\n \t\t#recommendedHeader .element2 p{ font-size: 12px; text-align: right }\\\n \t\t#recommendedHeader .element2 a{ white-space: nowrap; }\\\n \t\t#recommendedFooter {font-family: arial, helvetica, sans-serif;}\\\n \t\t#recommendedFooter .element1 {margin:13px 0 0 0}\\\n \t\t#recommendedFooter p { font-size: 1.1em}\\\n \t\t#recommendedFooter .loggedIn span,\\\n \t\t#recommendedFooterActions .element2 span{ font-size:10px; color:#999; } \\\n \t\t#recommendedFooter .loggedIn span a,\\\n \t\t#recommendedFooterActions .element2 span a{color:#666; text-decoration:underline } \\\n \t\t#recommendedFooterActions .horizontalMenu li {padding:0 6px 0 0}\\\n \t\t#recommendedFooterActions .element1 {margin: -1px 0 0 0}\\\n \t\t#recommendedFooterActions { margin: 12px 0 0 0; }\\\n \t\t#recommendedAdContainer { text-align:center}\\\n \t\t#recommendedAdContainer iframe { border:0; }\\\n \t\t#recommendedAdContainer #recommendedAd { margin-top: 5px; }\\\n \t\t#recommendedAdContainer span {font-size:7px; text-transform: uppercase; color:#999;}\\\n \t\t.hideRecommended:hover,\\\n \t\t.showRecommended:hover,\\\n \t\t#fbLoginButton:hover {cursor: pointer}\\\n \t\t#mostPopWidget .tabContent .errorMessage { padding:30px 20px; color: #999; font-family: arial, helvetica, sans-serif; border-bottom: 1px solid #E2E2E2; }\\\n \t\t#mostPopWidget .tabContent .errorMessage p{ font-size:11px; } \\\n \t\t\\\n \t\t';\n \n // Homepage style\n \n if (NYTD.MostPop.contentType == \"Homepage\") {\n cssStyle += \" \\\n #home #mostPopWidget .tabContent table td{ border-bottom: 0 !important; height: auto; padding-bottom: 2px;} \\\n #home #mostPopWidget .tabContent table td.mostPopularTitle h4 { font-weight: bold !important; font-size: 12px !important; }\\\n #home #mostPopWidget .tabContent table { margin: 4px 0 6px; }\\\n #home #recommendedFooter { border-top: 1px solid #E2E2E2 !important; }\\\n #home #mostPopWidget .mostFooter { margin:0; padding-top: 8px; border-top: 1px solid #E2E2E2 !important; }\\\n #home #recommendedHeader { margin-bottom: 2px }\\\n #home #mostPopWidget .tabContent .errorMessage { border-bottom: none; } \\\n \";\n }\n \n \n \tif (NYTD.MostPop.contentType == \"Opinion\") {\n cssStyle += '#mostPopWidget .tabs li.selected {\\\n background: #F4F4F4 !important;\\\n border-top:1px solid #ccc !important;\\\n border-left:1px solid #ccc !important;\\\n border-right:1px solid #ccc !important;\\\n height:23px !important;\\\n margin:0 !important;\\\n }\\\n #mostPopWidget .tabs li {\\\n background: none !important;\\\n border:0 none !important;\\\n height:23px !important;\\\n margin:0 !important;\\\n }'; \n }\n \n if (NYTD.MostPop.contentType == \"Error Page\") {\n cssStyle += '#mostPopWidget #tabsContainer {\\\n display: none;\\\n padding-top: 0;\\\n }\\\n #mostPopWidget.doubleRule {\\\n background: none !important;\\\n padding-top: 0;\\\n }\\\n #mostPopWidget .tabContent {\\\n border: 0 !important;\\\n padding-top: 0;\\\n }\\\n #mostPopWidget .tabContent h4 {\\\n font-family: arial,helvetica,sans-serif !important;\\\n font-size: 14px !important;\\\n }\\\n #mostPopWidget .tabContent table td.mostPopularTitle {\\\n padding-top: 6px;\\\n }\\\n #mostPopWidget .tabContent table td {\\\n border-bottom: 0;\\\n font-size: 14px !important;\\\n }\\\n #mostPopWidget .tabContent table td.listNumber {\\\n font-weight: bold;\\\n width: 20px;\\\n }\\\n #mostPopWidget .showRecommended {\\\n display: none !important;\\\n }\\\n #mostPopWidget .tabContent table.leftAlignedMostPop td.mostPopularImg {\\\n padding: 6px 6px 6px 0;\\\n }\\\n '; \n }\n \n \t// Load CSS \n \tfunction appendStyleTag(styleStr) {\n var newNode = document.createElement('style');\n newNode.setAttribute(\"type\", \"text/css\");\n if (newNode.styleSheet) {\n // IE\n newNode.styleSheet.cssText = styleStr;\n } else {\n newNode.appendChild(document.createTextNode(styleStr));\n }\n $$('head')[0].appendChild(newNode);\n \t\t}\n appendStyleTag(cssStyle);\n\n \tvar mostPopShell = '<!-- MOST POPULAR MODULE STARTS -->\\\n \t\t <div id=\"tabsContainer\">\\\n \t\t <ul class=\"tabs\">\\\n \t\t <li id=\"mostPopTabMostEmailed\" class=\"tab\" style=\"display: none;\"><a href=\"http://www.nytimes.com/gst/mostpopular.html\">MOST EMAILED</a></li>\\\n \t\t <li id=\"mostPopTabMostViewed\" class=\"tab\" style=\"display: none;\"><a href=\"http://www.nytimes.com/gst/mostpopular.html\">MOST VIEWED</a></li>\\\n \t\t\t\t\t\t\t\t<li id=\"mostPopTabRecommendations\" class=\"tab\" style=\"display: none;\"><a href=\"http://www.nytimes.com/recommendations\">RECOMMENDED FOR YOU</a></li>\\\n \t\t </ul>\\\n \t\t </div>\\\n \t\t\t\t\t\t\\\n \t\t\t\t\t\t<div id=\"mostPopContentMostEmailed\" class=\"tabContent\" style=\"display: none;\">\\\n \t\t\t\t\t\t <div class=\"loader\"><img src=\"'+ NYTD.Hosts.imageHost +'/images/loaders/loading-grey-lines-circle-18.gif\" /></div>\\\n \t\t\t\t\t\t\t<div class=\"mostFooter opposingFloatControl wrap\"><p class=\"element1\"><a href=\"http://www.nytimes.com/gst/mostpopular.html\">Go to Complete List &raquo;</a></p>\\\n \t\t\t\t\t\t\t<p class=\"element2\"><a class=\"showRecommended\">Show My Recommendations</a></p></div>\\\n \t\t\t\t\t\t</div>\\\n \t\t\t\t\t\t\\\n \t\t\t\t\t\t<div id=\"mostPopContentMostViewed\" class=\"tabContent\" style=\"display: none;\">\\\n \t\t\t\t\t\t <div class=\"loader\"><img src=\"'+ NYTD.Hosts.imageHost +'/images/loaders/loading-grey-lines-circle-18.gif\" /></div>\\\n \t\t\t\t\t\t\t<div class=\"mostFooter opposingFloatControl wrap\"><p class=\"element1\"><a href=\"http://www.nytimes.com/gst/mostpopular.html\">Go to Complete List &raquo;</a></p>\\\n \t\t\t\t\t\t\t<p class=\"element2\"><a class=\"showRecommended\">Show My Recommendations</a></p></div>\\\n \t\t\t\t\t\t</div>\\\n \t\t\t\t\t\t\\\n \t\t\t\t\t\t<div id=\"mostPopContentRecommendations\" class=\"tabContent\" style=\"display: none;\">\\\n \t\t\t\t\t\t <div class=\"loader\"><img src=\"'+ NYTD.Hosts.imageHost +'/images/loaders/loading-grey-lines-circle-18.gif\" /></div>\\\n \t\t\t\t\t\t\t\\\n \t\t\t\t\t\t\t<div id=\"recommendedFooter\">\\\n \t\t\t\t\t\t\t <div class=\"opposingFloatControl wrap\"> \\\n \t\t\t\t\t\t\t <p class=\"element1 loggedOut\" style=\"display: none;\">Log in to discover more articles<br />\\\n \t\t\t\t\t\t\t\tbased on what you&lsquo;ve read.</p>\\\n \t\t\t\t\t\t\t\t\\\n \t\t\t\t\t\t\t\t <p class=\"element1 loggedIn\" style=\"display: none;\"><a href=\"http://www.nytimes.com/recommendations\">Go to Your Recommendations &raquo;</a><br />\\\n \t\t\t\t\t\t\t\t<span><a href=\"http://www.nytimes.com/content/help/extras/recommendations/recommendations.html\">What&rsquo;s This?</a> | <a class=\"hideRecommended\">Don&rsquo;t Show</a></span></p>\\\n \t\t\t\t\t\t\t\t\\\n \t\t\t\t\t\t\t\t<p class=\"element1 general\" style=\"display: none;\"><a href=\"http://www.nytimes.com/content/help/extras/recommendations/recommendations.html\">What&rsquo;s This?</a> | <a class=\"hideRecommended\">Don&rsquo;t Show</a></p>\\\n \t\t\t\t\t\t\t\t<div id=\"recommendedAdContainer\" class=\"element2\">\\\n \t\t\t\t\t\t\t\t\t<div id=\"recommendedAd\">\\\n \t\t\t\t\t\t\t\t\t <iframe scrolling=\"no\" frameborder=\"0\" src=\"http://www.nytimes.com/packages/html/recommendations/ad.html\" width=\"168\" height=\"40\"></iframe>\\\n </div>\\\n \t\t\t\t\t\t\t\t</div>\\\n \t\t\t\t\t\t\t</div>\\\n \t\t\t\t\t\t\t\t\\\n \t\t\t\t\t\t\t\t<div id=\"recommendedFooterActions\" class=\"opposingFloatControl wrap loggedOut\" style=\"display: none;\">\\\n \t\t\t\t\t\t\t\t<div class=\"element1\">\\\n \t\t\t\t\t\t\t\t <ul class=\"flush horizontalMenu\">\\\n \t\t\t\t\t\t\t\t <li><a href=\"/login\"><img src=\"'+ NYTD.Hosts.imageHost +'/images/recommendations/recommendedLogin.png\" /></a></li>\\\n \t\t\t\t\t\t\t\t <li><a href=\"/regi\"><img src=\"'+ NYTD.Hosts.imageHost +'/images/recommendations/recommendedRegister.png\" /></a>\\\n \t\t\t\t\t\t\t\t <li><a id=\"fbLoginButton\"><img src=\"'+ NYTD.Hosts.imageHost +'/images/recommendations/recommendedFacebook.png\" /></a></li>\\\n \t\t\t\t\t\t\t\t</ul>\\\n \t\t\t\t\t\t\t\t</div>\\\n \t\t\t\t\t\t\t\t<div class=\"element2\">\\\n \t\t\t\t\t\t\t\t <span><a href=\"http://www.nytimes.com/content/help/extras/recommendations/recommendations.html\">What&rsquo;s This?</a> | <a class=\"hideRecommended\">Don&rsquo;t Show</a></span>\\\n \t\t\t\t\t\t\t\t</div>\\\n \t\t\t\t\t\t\t</div>\\\n \t\t\t\t\t\t\t</div>\\\n \t\t\t\t\t\t\t\\\n \t\t\t\t\t\t</div>\\\n \t\t\t\t\t\t\\\n \t\t<!-- MOST POPULAR MODULE ENDS -->';\n \t\t\n \t // Init \n\n \tvar init = (function() {\n\n //Build initial HTML\n \t $('mostPopWidget').insert(mostPopShell);\n \n // Click Handlers\n\n \t$('mostPopTabMostEmailed').observe('click', respondToClickMostEmailed);\n function respondToClickMostEmailed(event) {\n var url = mostEmailedUrl;\n if (NYTD.MostPop.EventLog['mostPopContentMostEmailed'] != \"loaded\") loadData(url, \"mostPopContentMostEmailed\");\n }\n\n $('mostPopTabMostViewed').observe('click', respondToClickMostViewed);\n function respondToClickMostViewed(event) {\n var url = mostViewedUrl;\n if (NYTD.MostPop.EventLog['mostPopContentMostViewed'] != \"loaded\") loadData(url, \"mostPopContentMostViewed\");\n } \n\n $('mostPopTabRecommendations').observe('click', respondToClickRecommendations);\n function respondToClickRecommendations(event) {\n var url = recommendedUrl;\n if (NYTD.MostPop.EventLog['mostPopContentRecommendations'] != \"loaded\") loadData(url, \"mostPopContentRecommendations\");\n }\n\n // Hide Rec Handler\n $$('.hideRecommended').each(function(el){ \n el.observe('click', deactivateRecommended);\n });\n\n // Show Rec Handler\n $$('.showRecommended').each(function(el){ \n el.observe('click', activateRecommended);\n });\n\n // fbLogin Handler\n $('fbLoginButton').observe('click', function(){\n NYTD.Facebook.User.login(function(){\n // Reset cache\n NYTD.MostPop.EventLog.mostPopContentRecommendations = \"unloaded\";\n var url = recommendedUrl;\n window.setTimeout(function(){\n loadData(url, \"mostPopContentRecommendations\");\n }, 1000);\n });\n });\n \n // Check Reco Cookie\n \t NYTD.MostPop.recCookie = getCookie('nyt-recommend');\n \t if (NYTD.MostPop.contentType != 'Error Page' && (NYTD.MostPop.recCookie == null || NYTD.MostPop.recCookie == 1)) {\n \t // No Cookie or cookie set to true, Show Recommended\n \t activateRecommended();\n \t } else {\n \t // Cookie set to false or Error Page, show most viewed and most emailed.\n \t NYTD.MostPop.autoRecOff = true;\n \t deactivateRecommended(true);\n \t }\n new Accordian(\"mostPopWidget\");\n \t})();\t\n \n \t\n \t// Utils\n \t\n \tfunction setCookie(name, value, options) {\n \t var newcookie = [escape(name) + \"=\" + escape(value)];\n \t if (options) {\n \t if (options.expires) {\n \t\t\t\t\t\tvar date = new Date();\n \t\t\t\t\t\tdate.setTime(date.getTime()+(options.expires*24*60*60*1000));\n \t\t\t\t\t\tnewcookie.push(\"expires=\" + date.toGMTString());\n \t\t\t\t\t}\n \t if (options.path) newcookie.push(\"path=\" + options.path);\n \t if (options.domain) newcookie.push(\"domain=\" + options.domain);\n \t if (options.secure) newcookie.push(\"secure\");\n \t }\n \t document.cookie = newcookie.join('; ');\n \t }\n \tfunction getCookie(name) {\n return new RegExp(name + '=([^;]+)').test(unescape(document.cookie)) ? RegExp.$1 : null;\n }\n })();\n" }, { "alpha_fraction": 0.6092384457588196, "alphanum_fraction": 0.6204743981361389, "avg_line_length": 29.80769157409668, "blob_id": "79cc184bbfd85f267646bc71cae2a0e59f228533", "content_id": "d2ff72c7beb4885515295988b896c1ef0f28d9f7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 801, "license_type": "permissive", "max_line_length": 85, "num_lines": 26, "path": "/servers/demo-scaleout/html/tmp/cnn/geo.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "//\noptimizelyGeo = {\n 'city': \"MILPITAS\",\n 'continent': \"NA\",\n 'country': \"US\",\n 'region': \"CA\",\n 'ip': \"70.35.58.82\"\n};\nif (typeof window['optimizely'] !== \"undefined\" &&\n window['optimizely'] !== null) {\n try {\n var visitorObj = window['optimizely']['data']['visitor'];\n visitorObj['location']['city'] = optimizelyGeo['city'];\n visitorObj['location']['continent'] = optimizelyGeo['continent'];\n visitorObj['location']['country'] = optimizelyGeo['country'];\n visitorObj['location']['region'] = optimizelyGeo['region'];\n visitorObj['ip'] = optimizelyGeo['ip'];\n }\n catch(error) {}\n if (typeof window['optimizely']['activateGeoDelayedExperiments'] !== \"undefined\") {\n window['optimizely']['activateGeoDelayedExperiments']();\n }\n else {\n optimizelyGeo = {};\n }\n}\n" }, { "alpha_fraction": 0.8052889108657837, "alphanum_fraction": 0.8059476017951965, "avg_line_length": 1536.250732421875, "blob_id": "c7de8c4a76d21fe291103aa69fbd6ea6a1125b54", "content_id": "26683edb3e946ffcdbb4abb023ae6e8702c992d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 490383, "license_type": "permissive", "max_line_length": 10464, "num_lines": 319, "path": "/servers/demo-scaleout/html/random_512kb.html", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html>\n<head>\n<title></title>\n<meta charset=\"utf-8\">\n<style type=\"text/css\">body{margin:10px}table,th,td,li,dl{font-family:\"lucida grande\",arial;font-size:8pt}dt{font-weight:bold}table{background-color:#efefef;border:2px solid #ddd;width:100%}th{background-color:#efefef}td{background-color:#fff}</style>\n</head>\n<body><table cellpadding=\"1\" cellspacing=\"1\">\n<tr>\n<th>test1</th>\n<th>test2</th>\n<th>test3</th>\n<th>test4</th>\n</tr>\n<tr>\n<td>Amelia P. Walls</td>\n<td>7691 Sit Road</td>\n<td>Ella H. Mosley</td>\n<td>P.O. Box 592, 7839 Sit Av.</td>\n<td>Sibelius, Finale, Lycos, Borland, Google, Altavista, Chami, Cakewalk, Macromedia, Adobe, Yahoo, Apple Systems, Lavasoft, Microsoft</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Yahoo, Microsoft, Chami, Macromedia, Sibelius, Apple Systems, Adobe, Altavista, Lavasoft, Lycos, Google, Cakewalk, Borland, Finale</td>\n<td>eget mt serg stger setst setst gfbc dfgbdfgn etus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit</td>\n<p>\ngu7Irke58rEbwLdbJcxHlElhAYY99Z5NrDpNkd2OgCCvQbAY6rcxuGUlE1fwESfjhubOY99H6AK96BXLynybRPz1VJdaT0WhAmuGqAdMrpgOmy8So8kkcZS2mFMBQvuIU6mDatrRfN3FwFhaw1H6uUWNHWBOWNyDPi6gvvnkGUPJt1p6fkyu7hMCo0CXFclIseF1c1WP6izPFq2MnFJn5KRNX2Aai7nURf64FpeBh6W1mSHorfNcqQoeEBO1QjUM1YssYnClFCeWPbwmwEkUmUJnFS4GXJd1VxOfQ9wU8NJ3ctjZmItJqWpvhQrEfDMnfU6Cv7mjBbYpvxmiVtgPsCask8D5KpMY6qFPPfamnzZjdDT7OLW2YfcRuj0i4ZQjnwgrH7iWE0c2ZzBpGv1wK59o0vt7TAfThvBiixSzkftsGlFxL5GaAVPb1OPhuXGr6JB4yjyfOta2s4mLMCsvJJ3PFYdep3R3f9rd59WsOjnYVaVHxdKlPzv3ZbID8NHtr2991pwkplellWDJFn4Nr1hVjtOtLkrZBlE8Yk96tV2K3lpqjgIyyencqoy1hS0M30rvDZL3tb5U75eekx4GuV2yBkiOj7OiSpExAs7QnTiXgzts1Ugw6gbvdMDyASNxXipMb5V9YcsJ9jBhqzdR5Fc5QbOd3pBKo5X7bQ0TQShRmnchiSU3OFznj1XnP3U3LLJ8TUpuSsZrLYUGsMZ31jdiTxVwgwIuH2YyOXuxebVVWnw7Scztb2aNn2vpbgFnF1I22leL3XtgZu1r3mQJaGQ8gBP1UBu7E1lN8EFib4OPOVnw87SHRdLmityFDmHvHdQZcdZF4JwucyYqqtLvWHLZ3cgSodiVDXsHdKk5wYBKJMKXVREvLM0QbdZ5VqUmWrm7OuHpSR2kZwd1OggcOvQGL3n1hUaiUcT2AAi7IqsWVoVK1sEiBtTB4Iqb6l7WtaxCctJrYT0pY59fkOobQVhGjr8yJhpvaEmWtcYOCMVCGTWLI2UKXXdZZOk34bqEt5SHYhas2bDf3QTHV0y6fLZjcs73pI4gbGyp5l9hsV3NRgnwQXQmlMXA46HnC6KDUqYvlOZ8SVUsr35AuaAWbdRisPRTZd1TvdmaFmXFpPA2azfys0aRCBMZBSlGftmzeKb0VAsdWGRCkGkgKk5dApmlweErxWFajllwdIr4ERVlG6CPGSXE2Z4IydLdA1P54BHE2qQKNg7TAlvC1H5q7IOLKg5WHB5kiSzX7cU4iNQXkzCd40PEnaClnDSCpKRhioYXrGRoAuM2EYgv7N0pSzXELbfRgGrXFFNyGPijjmjSmMb4md9GIMgcVr9Ug3q74wBHN5hhTDuhFLrHYLvsw82bd4vs3djsPMenDIIjZweHv4imyAPNOa9y92sVUiYenEQw56BucqCZADTPbE1Uq6EzBe1HRm23SadgXa4Am5Mrenwlm3e6YaI7q0hBtCiiw8kIw9ZTgJuCjvn86PRl53Nz3GHnFFiIJbIM0sPIKnJGI1dzu2wSgleZPDXlZKJJoFSKw4y0DQCtHHayhb9nEvAWBnvlUeGKTPYIhsGBqyE2uk8ioilN3Nxpd4pmBcgTIrXnvtMsJkYOWqkQPhAnTjhlCyAnqbnJYMzU0vUJzoNI142MPm85IuO66m21FIUVhnWdkQnARcBn4wE3f370Az3TA36v4hNWtAngt21wRx7YS3wfybndkw6kq4sMx9gozX6fdQpj7YwRAUvQMM5QifvmxCNIvWsgTJoARZ83yLSFXDnLwoKvIfpzWp9fRzqi1XDN2HMAr6hgFGufLbPzTkFG9zFGHNCx6dvmo3H48u0Ar9Um5723vqCSSz1ShGdTxBry3IpTUGZ69e5ezUQHYAITsLC8d1oXft0Z7AHRt4XAJTR2AfBBjrndKsisFHVLCqsLiQOluNbZzSzGhveAxdcinkGQxrpxVkihB0PeI6LssSrgaAb6n52Kex0dKtHimh60qVPMuPxkkHbV\ngu7Irke58rEbwLdbJcxHlElhAYY99Z5NrDpNkd2OgCCvQbAY6rcxuGUlE1fwESfjhubOY99H6AK96BXLynybRPz1VJdaT0WhAmuGqAdMrpgOmy8So8kkcZS2mFMBQvuIU6mDatrRfN3FwFhaw1H6uUWNHWBOWNyDPi6gvvnkGUPJt1p6fkyu7hMCo0CXFclIseF1c1WP6izPFq2MnFJn5KRNX2Aai7nURf64FpeBh6W1mSHorfNcqQoeEBO1QjUM1YssYnClFCeWPbwmwEkUmUJnFS4GXJd1VxOfQ9wU8NJ3ctjZmItJqWpvhQrEfDMnfU6Cv7mjBbYpvxmiVtgPsCask8D5KpMY6qFPPfamnzZjdDT7OLW2YfcRuj0i4ZQjnwgrH7iWE0c2ZzBpGv1wK59o0vt7TAfThvBiixSzkftsGlFxL5GaAVPb1OPhuXGr6JB4yjyfOta2s4mLMCsvJJ3PFYdep3R3f9rd59WsOjnYVaVHxdKlPzv3ZbID8NHtr2991pwkplellWDJFn4Nr1hVjtOtLkrZBlE8Yk96tV2K3lpqjgIyyencqoy1hS0M30rvDZL3tb5U75eekx4GuV2yBkiOj7OiSpExAs7QnTiXgzts1Ugw6gbvdMDyASNxXipMb5V9YcsJ9jBhqzdR5Fc5QbOd3pBKo5X7bQ0TQShRmnchiSU3OFznj1XnP3U3LLJ8TUpuSsZrLYUGsMZ31jdiTxVwgwIuH2YyOXuxebVVWnw7Scztb2aNn2vpbgFnF1I22leL3XtgZu1r3mQJaGQ8gBP1UBu7E1lN8EFib4OPOVnw87SHRdLmityFDmHvHdQZcdZF4JwucyYqqtLvWHLZ3cgSodiVDXsHdKk5wYBKJMKXVREvLM0QbdZ5VqUmWrm7OuHpSR2kZwd1OggcOvQGL3n1hUaiUcT2AAi7IqsWVoVK1sEiBtTB4Iqb6l7WtaxCctJrYT0pY59fkOobQVhGjr8yJhpvaEmWtcYOCMVCGTWLI2UKXXdZZOk34bqEt5SHYhas2bDf3QTHV0y6fLZjcs73pI4gbGyp5l9hsV3NRgnwQXQmlMXA46HnC6KDUqYvlOZ8SVUsr35AuaAWbdRisPRTZd1TvdmaFmXFpPA2azfys0aRCBMZBSlGftmzeKb0VAsdWGRCkGkgKk5dApmlweErxWFajllwdIr4ERVlG6CPGSXE2Z4IydLdA1P54BHE2qQKNg7TAlvC1H5q7IOLKg5WHB5kiSzX7cU4iNQXkzCd40PEnaClnDSCpKRhioYXrGRoAuM2EYgv7N0pSzXELbfRgGrXFFNyGPijjmjSmMb4md9GIMgcVr9Ug3q74wBHN5hhTDuhFLrHYLvsw82bd4vs3djsPMenDIIjZweHv4imyAPNOa9y92sVUiYenEQw56BucqCZADTPbE1Uq6EzBe1HRm23SadgXa4Am5Mrenwlm3e6YaI7q0hBtCiiw8kIw9ZTgJuCjvn86PRl53Nz3GHnFFiIJbIM0sPIKnJGI1dzu2wSgleZPDXlZKJJoFSKw4y0DQCtHHayhb9nEvAWBnvlUeGKTPYIhsGBqyE2uk8ioilN3Nxpd4pmBcgTIrXnvtMsJkYOWqkQPhAnTjhlCyAnqbnJYMzU0vUJzoNI142MPm85IuO66m21FIUVhnWdkQnARcBn4wE3f370Az3TA36v4hNWtAngt21wRx7YS3wfybndkw6kq4sMx9gozX6fdQpj7YwRAUvQMM5QifvmxCNIvWsgTJoARZ83yLSFXDnLwoKvIfpzWp9fRzqi1XDN2HMAr6hgFGufLbPzTkFG9zFGHNCx6dvmo3H48u0Ar9Um5723vqCSSz1ShGdTxBry3IpTUGZ69e5ezUQHYAITsLC8d1oXft0Z7AHRt4XAJTR2AfBBjrndKsisFHVLCqsLiQOluNbZzSzGhveAxdcinkGQxrpxVkihB0PeI6LssSrgaAb6n52Kex0dKtHimh60qVPMuPxkkHbV\ngu7Irke58rEbwLdbJcxHlElhAYY99Z5NrDpNkd2OgCCvQbAY6rcxuGUlE1fwESfjhubOY99H6AK96BXLynybRPz1VJdaT0WhAmuGqAdMrpgOmy8So8kkcZS2mFMBQvuIU6mDatrRfN3FwFhaw1H6uUWNHWBOWNyDPi6gvvnkGUPJt1p6fkyu7hMCo0CXFclIseF1c1WP6izPFq2MnFJn5KRNX2Aai7nURf64FpeBh6W1mSHorfNcqQoeEBO1QjUM1YssYnClFCeWPbwmwEkUmUJnFS4GXJd1VxOfQ9wU8NJ3ctjZmItJqWpvhQrEfDMnfU6Cv7mjBbYpvxmiVtgPsCask8D5KpMY6qFPPfamnzZjdDT7OLW2YfcRuj0i4ZQjnwgrH7iWE0c2ZzBpGv1wK59o0vt7TAfThvBiixSzkftsGlFxL5GaAVPb1OPhuXGr6JB4yjyfOta2s4mLMCsvJJ3PFYdep3R3f9rd59WsOjnYVaVHxdKlPzv3ZbID8NHtr2991pwkplellWDJFn4Nr1hVjtOtLkrZBlE8Yk96tV2K3lpqjgIyyencqoy1hS0M30rvDZL3tb5U75eekx4GuV2yBkiOj7OiSpExAs7QnTiXgzts1Ugw6gbvdMDyASNxXipMb5V9YcsJ9jBhqzdR5Fc5QbOd3pBKo5X7bQ0TQShRmnchiSU3OFznj1XnP3U3LLJ8TUpuSsZrLYUGsMZ31jdiTxVwgwIuH2YyOXuxebVVWnw7Scztb2aNn2vpbgFnF1I22leL3XtgZu1r3mQJaGQ8gBP1UBu7E1lN8EFib4OPOVnw87SHRdLmityFDmHvHdQZcdZF4JwucyYqqtLvWHLZ3cgSodiVDXsHdKk5wYBKJMKXVREvLM0QbdZ5VqUmWrm7OuHpSR2kZwd1OggcOvQGL3n1hUaiUcT2AAi7IqsWVoVK1sEiBtTB4Iqb6l7WtaxCctJrYT0pY59fkOobQVhGjr8yJhpvaEmWtcYOCMVCGTWLI2UKXXdZZOk34bqEt5SHYhas2bDf3QTHV0y6fLZjcs73pI4gbGyp5l9hsV3NRgnwQXQmlMXA46HnC6KDUqYvlOZ8SVUsr35AuaAWbdRisPRTZd1TvdmaFmXFpPA2azfys0aRCBMZBSlGftmzeKb0VAsdWGRCkGkgKk5dApmlweErxWFajllwdIr4ERVlG6CPGSXE2Z4IydLdA1P54BHE2qQKNg7TAlvC1H5q7IOLKg5WHB5kiSzX7cU4iNQXkzCd40PEnaClnDSCpKRhioYXrGRoAuM2EYgv7N0pSzXELbfRgGrXFFNyGPijjmjSmMb4md9GIMgcVr9Ug3q74wBHN5hhTDuhFLrHYLvsw82bd4vs3djsPMenDIIjZweHv4imyAPNOa9y92sVUiYenEQw56BucqCZADTPbE1Uq6EzBe1HRm23SadgXa4Am5Mrenwlm3e6YaI7q0hBtCiiw8kIw9ZTgJuCjvn86PRl53Nz3GHnFFiIJbIM0sPIKnJGI1dzu2wSgleZPDXlZKJJoFSKw4y0DQCtHHayhb9nEvAWBnvlUeGKTPYIhsGBqyE2uk8ioilN3Nxpd4pmBcgTIrXnvtMsJkYOWqkQPhAnTjhlCyAnqbnJYMzU0vUJzoNI142MPm85IuO66m21FIUVhnWdkQnARcBn4wE3f370Az3TA36v4hNWtAngt21wRx7YS3wfybndkw6kq4sMx9gozX6fdQpj7YwRAUvQMM5QifvmxCNIvWsgTJoARZ83yLSFXDnLwoKvIfpzWp9fRzqi1XDN2HMAr6hgFGufLbPzTkFG9zFGHNCx6dvmo3H48u0Ar9Um5723vqCSSz1ShGdTxBry3IpTUGZ69e5ezUQHYAITsLC8d1oXft0Z7AHRt4XAJTR2AfBBjrndKsisFHVLCqsLiQOluNbZzSzGhveAxdcinkGQxrpxVkihB0PeI6LssSrgaAb6n52Kex0dKtHimh60qVPMuPxkkHbV\ngu7Irke58rEbwLdbJcxHlElhAYY99Z5NrDpNkd2OgCCvQbAY6rcxuGUlE1fwESfjhubOY99H6AK96BXLynybRPz1VJdaT0WhAmuGqAdMrpgOmy8So8kkcZS2mFMBQvuIU6mDatrRfN3FwFhaw1H6uUWNHWBOWNyDPi6gvvnkGUPJt1p6fkyu7hMCo0CXFclIseF1c1WP6izPFq2MnFJn5KRNX2Aai7nURf64FpeBh6W1mSHorfNcqQoeEBO1QjUM1YssYnClFCeWPbwmwEkUmUJnFS4GXJd1VxOfQ9wU8NJ3ctjZmItJqWpvhQrEfDMnfU6Cv7mjBbYpvxmiVtgPsCask8D5KpMY6qFPPfamnzZjdDT7OLW2YfcRuj0i4ZQjnwgrH7iWE0c2ZzBpGv1wK59o0vt7TAfThvBiixSzkftsGlFxL5GaAVPb1OPhuXGr6JB4yjyfOta2s4mLMCsvJJ3PFYdep3R3f9rd59WsOjnYVaVHxdKlPzv3ZbID8NHtr2991pwkplellWDJFn4Nr1hVjtOtLkrZBlE8Yk96tV2K3lpqjgIyyencqoy1hS0M30rvDZL3tb5U75eekx4GuV2yBkiOj7OiSpExAs7QnTiXgzts1Ugw6gbvdMDyASNxXipMb5V9YcsJ9jBhqzdR5Fc5QbOd3pBKo5X7bQ0TQShRmnchiSU3OFznj1XnP3U3LLJ8TUpuSsZrLYUGsMZ31jdiTxVwgwIuH2YyOXuxebVVWnw7Scztb2aNn2vpbgFnF1I22leL3XtgZu1r3mQJaGQ8gBP1UBu7E1lN8EFib4OPOVnw87SHRdLmityFDmHvHdQZcdZF4JwucyYqqtLvWHLZ3cgSodiVDXsHdKk5wYBKJMKXVREvLM0QbdZ5VqUmWrm7OuHpSR2kZwd1OggcOvQGL3n1hUaiUcT2AAi7IqsWVoVK1sEiBtTB4Iqb6l7WtaxCctJrYT0pY59fkOobQVhGjr8yJhpvaEmWtcYOCMVCGTWLI2UKXXdZZOk34bqEt5SHYhas2bDf3QTHV0y6fLZjcs73pI4gbGyp5l9hsV3NRgnwQXQmlMXA46HnC6KDUqYvlOZ8SVUsr35AuaAWbdRisPRTZd1TvdmaFmXFpPA2azfys0aRCBMZBSlGftmzeKb0VAsdWGRCkGkgKk5dApmlweErxWFajllwdIr4ERVlG6CPGSXE2Z4IydLdA1P54BHE2qQKNg7TAlvC1H5q7IOLKg5WHB5kiSzX7cU4iNQXkzCd40PEnaClnDSCpKRhioYXrGRoAuM2EYgv7N0pSzXELbfRgGrXFFNyGPijjmjSmMb4md9GIMgcVr9Ug3q74wBHN5hhTDuhFLrHYLvsw82bd4vs3djsPMenDIIjZweHv4imyAPNOa9y92sVUiYenEQw56BucqCZADTPbE1Uq6EzBe1HRm23SadgXa4Am5Mrenwlm3e6YaI7q0hBtCiiw8kIw9ZTgJuCjvn86PRl53Nz3GHnFFiIJbIM0sPIKnJGI1dzu2wSgleZPDXlZKJJoFSKw4y0DQCtHHayhb9nEvAWBnvlUeGKTPYIhsGBqyE2uk8ioilN3Nxpd4pmBcgTIrXnvtMsJkYOWqkQPhAnTjhlCyAnqbnJYMzU0vUJzoNI142MPm85IuO66m21FIUVhnWdkQnARcBn4wE3f370Az3TA36v4hNWtAngt21wRx7YS3wfybndkw6kq4sMx9gozX6fdQpj7YwRAUvQMM5QifvmxCNIvWsgTJoARZ83yLSFXDnLwoKvIfpzWp9fRzqi1XDN2HMAr6hgFGufLbPzTkFG9zFGHNCx6dvmo3H48u0Ar9Um5723vqCSSz1ShGdTxBry3IpTUGZ69e5ezUQHYAITsLC8d1oXft0Z7AHRt4XAJTR2AfBBjrndKsisFHVLCqsLiQOluNbZzSzGhveAxdcinkGQxrpxVkihB0PeI6LssSrgaAb6n52Kex0dKtHimh60qVPMuPxkkHbV\ngu7Irke58rEbwLdbJcxHlElhAYY99Z5NrDpNkd2OgCCvQbAY6rcxuGUlE1fwESfjhubOY99H6AK96BXLynybRPz1VJdaT0WhAmuGqAdMrpgOmy8So8kkcZS2mFMBQvuIU6mDatrRfN3FwFhaw1H6uUWNHWBOWNyDPi6gvvnkGUPJt1p6fkyu7hMCo0CXFclIseF1c1WP6izPFq2MnFJn5KRNX2Aai7nURf64FpeBh6W1mSHorfNcqQoeEBO1QjUM1YssYnClFCeWPbwmwEkUmUJnFS4GXJd1VxOfQ9wU8NJ3ctjZmItJqWpvhQrEfDMnfU6Cv7mjBbYpvxmiVtgPsCask8D5KpMY6qFPPfamnzZjdDT7OLW2YfcRuj0i4ZQjnwgrH7iWE0c2ZzBpGv1wK59o0vt7TAfThvBiixSzkftsGlFxL5GaAVPb1OPhuXGr6JB4yjyfOta2s4mLMCsvJJ3PFYdep3R3f9rd59WsOjnYVaVHxdKlPzv3ZbID8NHtr2991pwkplellWDJFn4Nr1hVjtOtLkrZBlE8Yk96tV2K3lpqjgIyyencqoy1hS0M30rvDZL3tb5U75eekx4GuV2yBkiOj7OiSpExAs7QnTiXgzts1Ugw6gbvdMDyASNxXipMb5V9YcsJ9jBhqzdR5Fc5QbOd3pBKo5X7bQ0TQShRmnchiSU3OFznj1XnP3U3LLJ8TUpuSsZrLYUGsMZ31jdiTxVwgwIuH2YyOXuxebVVWnw7Scztb2aNn2vpbgFnF1I22leL3XtgZu1r3mQJaGQ8gBP1UBu7E1lN8EFib4OPOVnw87SHRdLmityFDmHvHdQZcdZF4JwucyYqqtLvWHLZ3cgSodiVDXsHdKk5wYBKJMKXVREvLM0QbdZ5VqUmWrm7OuHpSR2kZwd1OggcOvQGL3n1hUaiUcT2AAi7IqsWVoVK1sEiBtTB4Iqb6l7WtaxCctJrYT0pY59fkOobQVhGjr8yJhpvaEmWtcYOCMVCGTWLI2UKXXdZZOk34bqEt5SHYhas2bDf3QTHV0y6fLZjcs73pI4gbGyp5l9hsV3NRgnwQXQmlMXA46HnC6KDUqYvlOZ8SVUsr35AuaAWbdRisPRTZd1TvdmaFmXFpPA2azfys0aRCBMZBSlGftmzeKb0VAsdWGRCkGkgKk5dApmlweErxWFajllwdIr4ERVlG6CPGSXE2Z4IydLdA1P54BHE2qQKNg7TAlvC1H5q7IOLKg5WHB5kiSzX7cU4iNQXkzCd40PEnaClnDSCpKRhioYXrGRoAuM2EYgv7N0pSzXELbfRgGrXFFNyGPijjmjSmMb4md9GIMgcVr9Ug3q74wBHN5hhTDuhFLrHYLvsw82bd4vs3djsPMenDIIjZweHv4imyAPNOa9y92sVUiYenEQw56BucqCZADTPbE1Uq6EzBe1HRm23SadgXa4Am5Mrenwlm3e6YaI7q0hBtCiiw8kIw9ZTgJuCjvn86PRl53Nz3GHnFFiIJbIM0sPIKnJGI1dzu2wSgleZPDXlZKJJoFSKw4y0DQCtHHayhb9nEvAWBnvlUeGKTPYIhsGBqyE2uk8ioilN3Nxpd4pmBcgTIrXnvtMsJkYOWqkQPhAnTjhlCyAnqbnJYMzU0vUJzoNI142MPm85IuO66m21FIUVhnWdkQnARcBn4wE3f370Az3TA36v4hNWtAngt21wRx7YS3wfybndkw6kq4sMx9gozX6fdQpj7YwRAUvQMM5QifvmxCNIvWsgTJoARZ83yLSFXDnLwoKvIfpzWp9fRzqi1XDN2HMAr6hgFGufLbPzTkFG9zFGHNCx6dvmo3H48u0Ar9Um5723vqCSSz1ShGdTxBry3IpTUGZ69e5ezUQHYAITsLC8d1oXft0Z7AHRt4XAJTR2AfBBjrndKsisFHVLCqsLiQOluNbZzSzGhveAxdcinkGQxrpxVkihB0PeI6LssSrgaAb6n52Kex0dKtHimh60qVPMuPxkkHbV\ngu7Irke58rEbwLdbJcxHlElhAYY99Z5NrDpNkd2OgCCvQbAY6rcxuGUlE1fwESfjhubOY99H6AK96BXLynybRPz1VJdaT0WhAmuGqAdMrpgOmy8So8kkcZS2mFMBQvuIU6mDatrRfN3FwFhaw1H6uUWNHWBOWNyDPi6gvvnkGUPJt1p6fkyu7hMCo0CXFclIseF1c1WP6izPFq2MnFJn5KRNX2Aai7nURf64FpeBh6W1mSHorfNcqQoeEBO1QjUM1YssYnClFCeWPbwmwEkUmUJnFS4GXJd1VxOfQ9wU8NJ3ctjZmItJqWpvhQrEfDMnfU6Cv7mjBbYpvxmiVtgPsCask8D5KpMY6qFPPfamnzZjdDT7OLW2YfcRuj0i4ZQjnwgrH7iWE0c2ZzBpGv1wK59o0vt7TAfThvBiixSzkftsGlFxL5GaAVPb1OPhuXGr6JB4yjyfOta2s4mLMCsvJJ3PFYdep3R3f9rd59WsOjnYVaVHxdKlPzv3ZbID8NHtr2991pwkplellWDJFn4Nr1hVjtOtLkrZBlE8Yk96tV2K3lpqjgIyyencqoy1hS0M30rvDZL3tb5U75eekx4GuV2yBkiOj7OiSpExAs7QnTiXgzts1Ugw6gbvdMDyASNxXipMb5V9YcsJ9jBhqzdR5Fc5QbOd3pBKo5X7bQ0TQShRmnchiSU3OFznj1XnP3U3LLJ8TUpuSsZrLYUGsMZ31jdiTxVwgwIuH2YyOXuxebVVWnw7Scztb2aNn2vpbgFnF1I22leL3XtgZu1r3mQJaGQ8gBP1UBu7E1lN8EFib4OPOVnw87SHRdLmityFDmHvHdQZcdZF4JwucyYqqtLvWHLZ3cgSodiVDXsHdKk5wYBKJMKXVREvLM0QbdZ5VqUmWrm7OuHpSR2kZwd1OggcOvQGL3n1hUaiUcT2AAi7IqsWVoVK1sEiBtTB4Iqb6l7WtaxCctJrYT0pY59fkOobQVhGjr8yJhpvaEmWtcYOCMVCGTWLI2UKXXdZZOk34bqEt5SHYhas2bDf3QTHV0y6fLZjcs73pI4gbGyp5l9hsV3NRgnwQXQmlMXA46HnC6KDUqYvlOZ8SVUsr35AuaAWbdRisPRTZd1TvdmaFmXFpPA2azfys0aRCBMZBSlGftmzeKb0VAsdWGRCkGkgKk5dApmlweErxWFajllwdIr4ERVlG6CPGSXE2Z4IydLdA1P54BHE2qQKNg7TAlvC1H5q7IOLKg5WHB5kiSzX7cU4iNQXkzCd40PEnaClnDSCpKRhioYXrGRoAuM2EYgv7N0pSzXELbfRgGrXFFNyGPijjmjSmMb4md9GIMgcVr9Ug3q74wBHN5hhTDuhFLrHYLvsw82bd4vs3djsPMenDIIjZweHv4imyAPNOa9y92sVUiYenEQw56BucqCZADTPbE1Uq6EzBe1HRm23SadgXa4Am5Mrenwlm3e6YaI7q0hBtCiiw8kIw9ZTgJuCjvn86PRl53Nz3GHnFFiIJbIM0sPIKnJGI1dzu2wSgleZPDXlZKJJoFSKw4y0DQCtHHayhb9nEvAWBnvlUeGKTPYIhsGBqyE2uk8ioilN3Nxpd4pmBcgTIrXnvtMsJkYOWqkQPhAnTjhlCyAnqbnJYMzU0vUJzoNI142MPm85IuO66m21FIUVhnWdkQnARcBn4wE3f370Az3TA36v4hNWtAngt21wRx7YS3wfybndkw6kq4sMx9gozX6fdQpj7YwRAUvQMM5QifvmxCNIvWsgTJoARZ83yLSFXDnLwoKvIfpzWp9fRzqi1XDN2HMAr6hgFGufLbPzTkFG9zFGHNCx6dvmo3H48u0Ar9Um5723vqCSSz1ShGdTxBry3IpTUGZ69e5ezUQHYAITsLC8d1oXft0Z7AHRt4XAJTR2AfBBjrndKsisFHVLCqsLiQOluNbZzSzGhveAxdcinkGQxrpxVkihB0PeI6LssSrgaAb6n52Kex0dKtHimh60qVPMuPxkkHbV\ngu7Irke58rEbwLdbJcxHlElhAYY99Z5NrDpNkd2OgCCvQbAY6rcxuGUlE1fwESfjhubOY99H6AK96BXLynybRPz1VJdaT0WhAmuGqAdMrpgOmy8So8kkcZS2mFMBQvuIU6mDatrRfN3FwFhaw1H6uUWNHWBOWNyDPi6gvvnkGUPJt1p6fkyu7hMCo0CXFclIseF1c1WP6izPFq2MnFJn5KRNX2Aai7nURf64FpeBh6W1mSHorfNcqQoeEBO1QjUM1YssYnClFCeWPbwmwEkUmUJnFS4GXJd1VxOfQ9wU8NJ3ctjZmItJqWpvhQrEfDMnfU6Cv7mjBbYpvxmiVtgPsCask8D5KpMY6qFPPfamnzZjdDT7OLW2YfcRuj0i4ZQjnwgrH7iWE0c2ZzBpGv1wK59o0vt7TAfThvBiixSzkftsGlFxL5GaAVPb1OPhuXGr6JB4yjyfOta2s4mLMCsvJJ3PFYdep3R3f9rd59WsOjnYVaVHxdKlPzv3ZbID8NHtr2991pwkplellWDJFn4Nr1hVjtOtLkrZBlE8Yk96tV2K3lpqjgIyyencqoy1hS0M30rvDZL3tb5U75eekx4GuV2yBkiOj7OiSpExAs7QnTiXgzts1Ugw6gbvdMDyASNxXipMb5V9YcsJ9jBhqzdR5Fc5QbOd3pBKo5X7bQ0TQShRmnchiSU3OFznj1XnP3U3LLJ8TUpuSsZrLYUGsMZ31jdiTxVwgwIuH2YyOXuxebVVWnw7Scztb2aNn2vpbgFnF1I22leL3XtgZu1r3mQJaGQ8gBP1UBu7E1lN8EFib4OPOVnw87SHRdLmityFDmHvHdQZcdZF4JwucyYqqtLvWHLZ3cgSodiVDXsHdKk5wYBKJMKXVREvLM0QbdZ5VqUmWrm7OuHpSR2kZwd1OggcOvQGL3n1hUaiUcT2AAi7IqsWVoVK1sEiBtTB4Iqb6l7WtaxCctJrYT0pY59fkOobQVhGjr8yJhpvaEmWtcYOCMVCGTWLI2UKXXdZZOk34bqEt5SHYhas2bDf3QTHV0y6fLZjcs73pI4gbGyp5l9hsV3NRgnwQXQmlMXA46HnC6KDUqYvlOZ8SVUsr35AuaAWbdRisPRTZd1TvdmaFmXFpPA2azfys0aRCBMZBSlGftmzeKb0VAsdWGRCkGkgKk5dApmlweErxWFajllwdIr4ERVlG6CPGSXE2Z4IydLdA1P54BHE2qQKNg7TAlvC1H5q7IOLKg5WHB5kiSzX7cU4iNQXkzCd40PEnaClnDSCpKRhioYXrGRoAuM2EYgv7N0pSzXELbfRgGrXFFNyGPijjmjSmMb4md9GIMgcVr9Ug3q74wBHN5hhTDuhFLrHYLvsw82bd4vs3djsPMenDIIjZweHv4imyAPNOa9y92sVUiYenEQw56BucqCZADTPbE1Uq6EzBe1HRm23SadgXa4Am5Mrenwlm3e6YaI7q0hBtCiiw8kIw9ZTgJuCjvn86PRl53Nz3GHnFFiIJbIM0sPIKnJGI1dzu2wSgleZPDXlZKJJoFSKw4y0DQCtHHayhb9nEvAWBnvlUeGKTPYIhsGBqyE2uk8ioilN3Nxpd4pmBcgTIrXnvtMsJkYOWqkQPhAnTjhlCyAnqbnJYMzU0vUJzoNI142MPm85IuO66m21FIUVhnWdkQnARcBn4wE3f370Az3TA36v4hNWtAngt21wRx7YS3wfybndkw6kq4sMx9gozX6fdQpj7YwRAUvQMM5QifvmxCNIvWsgTJoARZ83yLSFXDnLwoKvIfpzWp9fRzqi1XDN2HMAr6hgFGufLbPzTkFG9zFGHNCx6dvmo3H48u0Ar9Um5723vqCSSz1ShGdTxBry3IpTUGZ69e5ezUQHYAITsLC8d1oXft0Z7AHRt4XAJTR2AfBBjrndKsisFHVLCqsLiQOluNbZzSzGhveAxdcinkGQxrpxVkihB0PeI6LssSrgaAb6n52Kex0dKtHimh60qVPMuPxkkHbV\ngu7Irke58rEbwLdbJcxHlElhAYY99Z5NrDpNkd2OgCCvQbAY6rcxuGUlE1fwESfjhubOY99H6AK96BXLynybRPz1VJdaT0WhAmuGqAdMrpgOmy8So8kkcZS2mFMBQvuIU6mDatrRfN3FwFhaw1H6uUWNHWBOWNyDPi6gvvnkGUPJt1p6fkyu7hMCo0CXFclIseF1c1WP6izPFq2MnFJn5KRNX2Aai7nURf64FpeBh6W1mSHorfNcqQoeEBO1QjUM1YssYnClFCeWPbwmwEkUmUJnFS4GXJd1VxOfQ9wU8NJ3ctjZmItJqWpvhQrEfDMnfU6Cv7mjBbYpvxmiVtgPsCask8D5KpMY6qFPPfamnzZjdDT7OLW2YfcRuj0i4ZQjnwgrH7iWE0c2ZzBpGv1wK59o0vt7TAfThvBiixSzkftsGlFxL5GaAVPb1OPhuXGr6JB4yjyfOta2s4mLMCsvJJ3PFYdep3R3f9rd59WsOjnYVaVHxdKlPzv3ZbID8NHtr2991pwkplellWDJFn4Nr1hVjtOtLkrZBlE8Yk96tV2K3lpqjgIyyencqoy1hS0M30rvDZL3tb5U75eekx4GuV2yBkiOj7OiSpExAs7QnTiXgzts1Ugw6gbvdMDyASNxXipMb5V9YcsJ9jBhqzdR5Fc5QbOd3pBKo5X7bQ0TQShRmnchiSU3OFznj1XnP3U3LLJ8TUpuSsZrLYUGsMZ31jdiTxVwgwIuH2YyOXuxebVVWnw7Scztb2aNn2vpbgFnF1I22leL3XtgZu1r3mQJaGQ8gBP1UBu7E1lN8EFib4OPOVnw87SHRdLmityFDmHvHdQZcdZF4JwucyYqqtLvWHLZ3cgSodiVDXsHdKk5wYBKJMKXVREvLM0QbdZ5VqUmWrm7OuHpSR2kZwd1OggcOvQGL3n1hUaiUcT2AAi7IqsWVoVK1sEiBtTB4Iqb6l7WtaxCctJrYT0pY59fkOobQVhGjr8yJhpvaEmWtcYOCMVCGTWLI2UKXXdZZOk34bqEt5SHYhas2bDf3QTHV0y6fLZjcs73pI4gbGyp5l9hsV3NRgnwQXQmlMXA46HnC6KDUqYvlOZ8SVUsr35AuaAWbdRisPRTZd1TvdmaFmXFpPA2azfys0aRCBMZBSlGftmzeKb0VAsdWGRCkGkgKk5dApmlweErxWFajllwdIr4ERVlG6CPGSXE2Z4IydLdA1P54BHE2qQKNg7TAlvC1H5q7IOLKg5WHB5kiSzX7cU4iNQXkzCd40PEnaClnDSCpKRhioYXrGRoAuM2EYgv7N0pSzXELbfRgGrXFFNyGPijjmjSmMb4md9GIMgcVr9Ug3q74wBHN5hhTDuhFLrHYLvsw82bd4vs3djsPMenDIIjZweHv4imyAPNOa9y92sVUiYenEQw56BucqCZADTPbE1Uq6EzBe1HRm23SadgXa4Am5Mrenwlm3e6YaI7q0hBtCiiw8kIw9ZTgJuCjvn86PRl53Nz3GHnFFiIJbIM0sPIKnJGI1dzu2wSgleZPDXlZKJJoFSKw4y0DQCtHHayhb9nEvAWBnvlUeGKTPYIhsGBqyE2uk8ioilN3Nxpd4pmBcgTIrXnvtMsJkYOWqkQPhAnTjhlCyAnqbnJYMzU0vUJzoNI142MPm85IuO66m21FIUVhnWdkQnARcBn4wE3f370Az3TA36v4hNWtAngt21wRx7YS3wfybndkw6kq4sMx9gozX6fdQpj7YwRAUvQMM5QifvmxCNIvWsgTJoARZ83yLSFXDnLwoKvIfpzWp9fRzqi1XDN2HMAr6hgFGufLbPzTkFG9zFGHNCx6dvmo3H48u0Ar9Um5723vqCSSz1ShGdTxBry3IpTUGZ69e5ezUQHYAITsLC8d1oXft0Z7AHRt4XAJTR2AfBBjrndKsisFHVLCqsLiQOluNbZzSzGhveAxdcinkGQxrpxVkihB0PeI6LssSrgaAb6n52Kex0dKtHimh60qVPMuPxkkHbV\ngu7Irke58rEbwLdbJcxHlElhAYY99Z5NrDpNkd2OgCCvQbAY6rcxuGUlE1fwESfjhubOY99H6AK96BXLynybRPz1VJdaT0WhAmuGqAdMrpgOmy8So8kkcZS2mFMBQvuIU6mDatrRfN3FwFhaw1H6uUWNHWBOWNyDPi6gvvnkGUPJt1p6fkyu7hMCo0CXFclIseF1c1WP6izPFq2MnFJn5KRNX2Aai7nURf64FpeBh6W1mSHorfNcqQoeEBO1QjUM1YssYnClFCeWPbwmwEkUmUJnFS4GXJd1VxOfQ9wU8NJ3ctjZmItJqWpvhQrEfDMnfU6Cv7mjBbYpvxmiVtgPsCask8D5KpMY6qFPPfamnzZjdDT7OLW2YfcRuj0i4ZQjnwgrH7iWE0c2ZzBpGv1wK59o0vt7TAfThvBiixSzkftsGlFxL5GaAVPb1OPhuXGr6JB4yjyfOta2s4mLMCsvJJ3PFYdep3R3f9rd59WsOjnYVaVHxdKlPzv3ZbID8NHtr2991pwkplellWDJFn4Nr1hVjtOtLkrZBlE8Yk96tV2K3lpqjgIyyencqoy1hS0M30rvDZL3tb5U75eekx4GuV2yBkiOj7OiSpExAs7QnTiXgzts1Ugw6gbvdMDyASNxXipMb5V9YcsJ9jBhqzdR5Fc5QbOd3pBKo5X7bQ0TQShRmnchiSU3OFznj1XnP3U3LLJ8TUpuSsZrLYUGsMZ31jdiTxVwgwIuH2YyOXuxebVVWnw7Scztb2aNn2vpbgFnF1I22leL3XtgZu1r3mQJaGQ8gBP1UBu7E1lN8EFib4OPOVnw87SHRdLmityFDmHvHdQZcdZF4JwucyYqqtLvWHLZ3cgSodiVDXsHdKk5wYBKJMKXVREvLM0QbdZ5VqUmWrm7OuHpSR2kZwd1OggcOvQGL3n1hUaiUcT2AAi7IqsWVoVK1sEiBtTB4Iqb6l7WtaxCctJrYT0pY59fkOobQVhGjr8yJhpvaEmWtcYOCMVCGTWLI2UKXXdZZOk34bqEt5SHYhas2bDf3QTHV0y6fLZjcs73pI4gbGyp5l9hsV3NRgnwQXQmlMXA46HnC6KDUqYvlOZ8SVUsr35AuaAWbdRisPRTZd1TvdmaFmXFpPA2azfys0aRCBMZBSlGftmzeKb0VAsdWGRCkGkgKk5dApmlweErxWFajllwdIr4ERVlG6CPGSXE2Z4IydLdA1P54BHE2qQKNg7TAlvC1H5q7IOLKg5WHB5kiSzX7cU4iNQXkzCd40PEnaClnDSCpKRhioYXrGRoAuM2EYgv7N0pSzXELbfRgGrXFFNyGPijjmjSmMb4md9GIMgcVr9Ug3q74wBHN5hhTDuhFLrHYLvsw82bd4vs3djsPMenDIIjZweHv4imyAPNOa9y92sVUiYenEQw56BucqCZADTPbE1Uq6EzBe1HRm23SadgXa4Am5Mrenwlm3e6YaI7q0hBtCiiw8kIw9ZTgJuCjvn86PRl53Nz3GHnFFiIJbIM0sPIKnJGI1dzu2wSgleZPDXlZKJJoFSKw4y0DQCtHHayhb9nEvAWBnvlUeGKTPYIhsGBqyE2uk8ioilN3Nxpd4pmBcgTIrXnvtMsJkYOWqkQPhAnTjhlCyAnqbnJYMzU0vUJzoNI142MPm85IuO66m21FIUVhnWdkQnARcBn4wE3f370Az3TA36v4hNWtAngt21wRx7YS3wfybndkw6kq4sMx9gozX6fdQpj7YwRAUvQMM5QifvmxCNIvWsgTJoARZ83yLSFXDnLwoKvIfpzWp9fRzqi1XDN2HMAr6hgFGufLbPzTkFG9zFGHNCx6dvmo3H48u0Ar9Um5723vqCSSz1ShGdTxBry3IpTUGZ69e5ezUQHYAITsLC8d1oXft0Z7AHRt4XAJTR2AfBBjrndKsisFHVLCqsLiQOluNbZzSzGhveAxdcinkGQxrpxVkihB0PeI6LssSrgaAb6n52Kex0dKtHimh60qVPMuPxkkHbV\ngu7Irke58rEbwLdbJcxHlElhAYY99Z5NrDpNkd2OgCCvQbAY6rcxuGUlE1fwESfjhubOY99H6AK96BXLynybRPz1VJdaT0WhAmuGqAdMrpgOmy8So8kkcZS2mFMBQvuIU6mDatrRfN3FwFhaw1H6uUWNHWBOWNyDPi6gvvnkGUPJt1p6fkyu7hMCo0CXFclIseF1c1WP6izPFq2MnFJn5KRNX2Aai7nURf64FpeBh6W1mSHorfNcqQoeEBO1QjUM1YssYnClFCeWPbwmwEkUmUJnFS4GXJd1VxOfQ9wU8NJ3ctjZmItJqWpvhQrEfDMnfU6Cv7mjBbYpvxmiVtgPsCask8D5KpMY6qFPPfamnzZjdDT7OLW2YfcRuj0i4ZQjnwgrH7iWE0c2ZzBpGv1wK59o0vt7TAfThvBiixSzkftsGlFxL5GaAVPb1OPhuXGr6JB4yjyfOta2s4mLMCsvJJ3PFYdep3R3f9rd59WsOjnYVaVHxdKlPzv3ZbID8NHtr2991pwkplellWDJFn4Nr1hVjtOtLkrZBlE8Yk96tV2K3lpqjgIyyencqoy1hS0M30rvDZL3tb5U75eekx4GuV2yBkiOj7OiSpExAs7QnTiXgzts1Ugw6gbvdMDyASNxXipMb5V9YcsJ9jBhqzdR5Fc5QbOd3pBKo5X7bQ0TQShRmnchiSU3OFznj1XnP3U3LLJ8TUpuSsZrLYUGsMZ31jdiTxVwgwIuH2YyOXuxebVVWnw7Scztb2aNn2vpbgFnF1I22leL3XtgZu1r3mQJaGQ8gBP1UBu7E1lN8EFib4OPOVnw87SHRdLmityFDmHvHdQZcdZF4JwucyYqqtLvWHLZ3cgSodiVDXsHdKk5wYBKJMKXVREvLM0QbdZ5VqUmWrm7OuHpSR2kZwd1OggcOvQGL3n1hUaiUcT2AAi7IqsWVoVK1sEiBtTB4Iqb6l7WtaxCctJrYT0pY59fkOobQVhGjr8yJhpvaEmWtcYOCMVCGTWLI2UKXXdZZOk34bqEt5SHYhas2bDf3QTHV0y6fLZjcs73pI4gbGyp5l9hsV3NRgnwQXQmlMXA46HnC6KDUqYvlOZ8SVUsr35AuaAWbdRisPRTZd1TvdmaFmXFpPA2azfys0aRCBMZBSlGftmzeKb0VAsdWGRCkGkgKk5dApmlweErxWFajllwdIr4ERVlG6CPGSXE2Z4IydLdA1P54BHE2qQKNg7TAlvC1H5q7IOLKg5WHB5kiSzX7cU4iNQXkzCd40PEnaClnDSCpKRhioYXrGRoAuM2EYgv7N0pSzXELbfRgGrXFFNyGPijjmjSmMb4md9GIMgcVr9Ug3q74wBHN5hhTDuhFLrHYLvsw82bd4vs3djsPMenDIIjZweHv4imyAPNOa9y92sVUiYenEQw56BucqCZADTPbE1Uq6EzBe1HRm23SadgXa4Am5Mrenwlm3e6YaI7q0hBtCiiw8kIw9ZTgJuCjvn86PRl53Nz3GHnFFiIJbIM0sPIKnJGI1dzu2wSgleZPDXlZKJJoFSKw4y0DQCtHHayhb9nEvAWBnvlUeGKTPYIhsGBqyE2uk8ioilN3Nxpd4pmBcgTIrXnvtMsJkYOWqkQPhAnTjhlCyAnqbnJYMzU0vUJzoNI142MPm85IuO66m21FIUVhnWdkQnARcBn4wE3f370Az3TA36v4hNWtAngt21wRx7YS3wfybndkw6kq4sMx9gozX6fdQpj7YwRAUvQMM5QifvmxCNIvWsgTJoARZ83yLSFXDnLwoKvIfpzWp9fRzqi1XDN2HMAr6hgFGufLbPzTkFG9zFGHNCx6dvmo3H48u0Ar9Um5723vqCSSz1ShGdTxBry3IpTUGZ69e5ezUQHYAITsLC8d1oXft0Z7AHRt4XAJTR2AfBBjrndKsisFHVLCqsLiQOluNbZzSzGhveAxdcinkGQxrpxVkihB0PeI6LssSrgaAb6n52Kex0dKtHimh60qVPMuPxkkHbV\nygu7Irke58rEbwLdbJcxHlElhAYY99Z5NrDpNkd2OgCCvQbAY6rcxuGUlE1fwESfjhubOY99H6AK96BXLynybRPz1VJdaT0WhAmuGqAdMrpgOmy8So8kkcZS2mFMBQvuIU6mDatrRfN3FwFhaw1H6uUWNHWBOWNyDPi6gvvnkGUPJt1p6fkyu7hMCo0CXFclIseF1c1WP6izPFq2MnFJn5KRNX2Aai7nURf64FpeBh6W1mSHorfNcqQoeEBO1QjUM1YssYnClFCeWPbwmwEkUmUJnFS4GXJd1VxOfQ9wU8NJ3ctjZmItJqWpvhQrEfDMnfU6Cv7mjBbYpvxmiVtgPsCask8D5KpMY6qFPPfamnzZjdDT7OLW2YfcRuj0i4ZQjnwgrH7iWE0c2ZzBpGv1wK59o0vt7TAfThvBiixSzkftsGlFxL5GaAVPb1OPhuXGr6JB4yjyfOta2s4mLMCsvJJ3PFYdep3R3f9rd59WsOjnYVaVHxdKlPzv3ZbID8NHtr2991pwkplellWDJFn4Nr1hVjtOtLkrZBlE8Yk96tV2K3lpqjgIyyencqoy1hS0M30rvDZL3tb5U75eekx4GuV2yBkiOj7OiSpExAs7QnTiXgzts1Ugw6gbvdMDyASNxXipMb5V9YcsJ9jBhqzdR5Fc5QbOd3pBKo5X7bQ0TQShRmnchiSU3OFznj1XnP3U3LLJ8TUpuSsZrLYUGsMZ31jdiTxVwgwIuH2YyOXuxebVVWnw7Scztb2aNn2vpbgFnF1I22leL3XtgZu1r3mQJaGQ8gBP1UBu7E1lN8EFib4OPOVnw87SHRdLmityFDmHvHdQZcdZF4JwucyYqqtLvWHLZ3cgSodiVDXsHdKk5wYBKJMKXVREvLM0QbdZ5VqUmWrm7OuHpSR2kZwd1OggcOvQGL3n1hUaiUcT2AAi7IqsWVoVK1sEiBtTB4Iqb6l7WtaxCctJrYT0pY59fkOobQVhGjr8yJhpvaEmWtcYOCMVCGTWLI2UKXXdZZOk34bqEt5SHYhas2bDf3QTHV0y6fLZjcs73pI4gbGyp5l9hsV3NRgnwQXQmlMXA46HnC6KDUqYvlOZ8SVUsr35AuaAWbdRisPRTZd1TvdmaFmXFpPA2azfys0aRCBMZBSlGftmzeKb0VAsdWGRCkGkgKk5dApmlweErxWFajllwdIr4ERVlG6CPGSXE2Z4IydLdA1P54BHE2qQKNg7TAlvC1H5q7IOLKg5WHB5kiSzX7cU4iNQXkzCd40PEnaClnDSCpKRhioYXrGRoAuM2EYgv7N0pSzXELbfRgGrXFFNyGPijjmjSmMb4md9GIMgcVr9Ug3q74wBHN5hhTDuhFLrHYLvsw82bd4vs3djsPMenDIIjZweHv4imyAPNOa9y92sVUiYenEQw56BucqCZADTPbE1Uq6EzBe1HRm23SadgXa4Am5Mrenwlm3e6YaI7q0hBtCiiw8kIw9ZTgJuCjvn86PRl53Nz3GHnFFiIJbIM0sPIKnJGI1dzu2wSgleZPDXlZKJJoFSKw4y0DQCtHHayhb9nEvAWBnvlUeGKTPYIhsGBqyE2uk8ioilN3Nxpd4pmBcgTIrXnvtMsJkYOWqkQPhAnTjhlCyAnqbnJYMzU0vUJzoNI142MPm85IuO66m21FIUVhnWdkQnARcBn4wE3f370Az3TA36v4hNWtAngt21wRx7YS3wfybndkw6kq4sMx9gozX6fdQpj7YwRAUvQMM5QifvmxCNIvWsgTJoARZ83yLSFXDnLwoKvIfpzWp9fRzqi1XDN2HMAr6hgFGufLbPzTkFG9zFGHNCx6dvmo3H48u0Ar9Um5723vqCSSz1ShGdTxBry3IpTUGZ69e5ezUQHYAITsLC8d1oXft0Z7AHRt4XAJTR2AfBBjrndKsisFHVLCqsLiQOluNbZzSzGhveAxdcinkGQxrpxVkihB0PeI6LssSrgaAb6n52Kex0dKtHimh60qVPMuPxkkHbV\n</p>\n</tr>\n<tr>\n<td>Tyrone X. Morrow</td>\n<td>P.O. Box 812, 4175 Vitae Road</td>\n<td>Chami, Apple Systems, Altavista, Microsoft, Lavasoft, Google, Adobe, Macromedia, Borland, Lycos, Finale, Cakewalk, Sibelius, Yahoo</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Adrian S. Howell</td>\n<td>P.O. Box 958, 2738 Pharetra. Avenue</td>\n<td>Finale, Apple Systems, Macromedia, Microsoft, Yahoo, Sibelius, Borland, Google, Lycos, Cakewalk, Adobe, Chami, Altavista, Lavasoft</td>\n<td>dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet,</td>\n</tr>\n<tr>\n<td>Abbot K. Bright</td>\n<td>4909 Fusce St.</td>\n<td>Yahoo, Chami, Altavista, Lavasoft, Apple Systems, Macromedia, Finale, Lycos, Google, Borland, Adobe, Microsoft, Cakewalk, Sibelius</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Levi Y. Walters</td>\n<td>Ap #514-3486 Proin Street</td>\n<td>Chami, Lavasoft, Adobe, Sibelius, Borland, Yahoo, Altavista, Finale, Microsoft, Apple Systems, Cakewalk, Lycos, Google, Macromedia</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Maggy J. Hudson</td>\n<td>Ap #278-4577 Duis Rd.</td>\n<td>Adobe, Altavista, Apple Systems, Chami, Sibelius, Macromedia, Cakewalk, Microsoft, Lycos, Yahoo, Google, Borland, Lavasoft, Finale</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Tate B. Harmon</td>\n<td>447-937 Consectetuer Ave</td>\n<td>Lavasoft, Microsoft, Chami, Lycos, Altavista, Cakewalk, Adobe, Borland, Apple Systems, Macromedia, Google, Yahoo, Sibelius, Finale</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Eden E. Serrano</td>\n<td>P.O. Box 690, 6340 Est Road</td>\n<td>Microsoft, Altavista, Apple Systems, Borland, Adobe, Lavasoft, Finale, Sibelius, Yahoo, Lycos, Macromedia, Chami, Cakewalk, Google</td>\n<td>imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et</td>\n</tr>\n<tr>\n<td>Sopoline A. Mcintosh</td>\n<td>5962 Turpis. St.</td>\n<td>Borland, Cakewalk, Altavista, Apple Systems, Adobe, Google, Sibelius, Chami, Macromedia, Yahoo, Finale, Lycos, Lavasoft, Microsoft</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Josiah A. Steele</td>\n<td>522-2491 Libero Av.</td>\n<td>Yahoo, Finale, Borland, Google, Apple Systems, Adobe, Macromedia, Lavasoft, Cakewalk, Chami, Microsoft, Sibelius, Lycos, Altavista</td>\n<td>at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac,</td>\n</tr>\n<tr>\n<td>Diana I. Golden</td>\n<td>102-8608 Leo Road</td>\n<td>Borland, Altavista, Sibelius, Adobe, Microsoft, Cakewalk, Google, Chami, Yahoo, Lavasoft, Macromedia, Finale, Apple Systems, Lycos</td>\n<td>Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi</td>\n</tr>\n<tr>\n<td>Valentine I. Little</td>\n<td>5789 Hendrerit Rd.</td>\n<td>Lavasoft, Chami, Microsoft, Altavista, Lycos, Adobe, Sibelius, Macromedia, Google, Yahoo, Borland, Cakewalk, Finale, Apple Systems</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Chaney O. Weber</td>\n<td>Ap #212-2429 Odio. St.</td>\n<td>Altavista, Finale, Cakewalk, Yahoo, Lycos, Macromedia, Google, Apple Systems, Sibelius, Microsoft, Adobe, Lavasoft, Chami, Borland</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Zachary M. Santana</td>\n<td>Ap #400-5071 Sagittis St.</td>\n<td>Finale, Altavista, Google, Lavasoft, Macromedia, Lycos, Chami, Borland, Adobe, Sibelius, Apple Systems, Cakewalk, Yahoo, Microsoft</td>\n<td>habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum</td>\n</tr>\n<tr>\n<td>Xavier S. Ross</td>\n<td>805-837 Aliquam Avenue</td>\n<td>Sibelius, Yahoo, Apple Systems, Lavasoft, Finale, Google, Lycos, Macromedia, Altavista, Borland, Adobe, Microsoft, Cakewalk, Chami</td>\n<td>lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor,</td>\n</tr>\n<tr>\n<td>Marah F. Vincent</td>\n<td>572-4588 At, Ave</td>\n<td>Borland, Cakewalk, Sibelius, Macromedia, Adobe, Lavasoft, Yahoo, Google, Finale, Chami, Microsoft, Altavista, Lycos, Apple Systems</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Maisie S. Ellison</td>\n<td>673-6745 Et Rd.</td>\n<td>Apple Systems, Lavasoft, Google, Microsoft, Altavista, Adobe, Yahoo, Sibelius, Borland, Lycos, Finale, Chami, Cakewalk, Macromedia</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Riley U. Mcmillan</td>\n<td>Ap #415-7935 In Rd.</td>\n<td>Altavista, Yahoo, Chami, Lavasoft, Lycos, Borland, Macromedia, Google, Sibelius, Apple Systems, Cakewalk, Finale, Microsoft, Adobe</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Graham F. England</td>\n<td>219-6015 Tellus Rd.</td>\n<td>Chami, Lavasoft, Yahoo, Apple Systems, Altavista, Borland, Finale, Lycos, Microsoft, Macromedia, Adobe, Sibelius, Cakewalk, Google</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Dara D. Oneal</td>\n<td>Ap #881-5816 Tempor Rd.</td>\n<td>Google, Cakewalk, Finale, Borland, Lycos, Sibelius, Altavista, Macromedia, Apple Systems, Adobe, Microsoft, Lavasoft, Chami, Yahoo</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Riley W. Maldonado</td>\n<td>P.O. Box 564, 7973 Faucibus Rd.</td>\n<td>Google, Altavista, Lycos, Chami, Apple Systems, Cakewalk, Lavasoft, Microsoft, Sibelius, Macromedia, Yahoo, Borland, Adobe, Finale</td>\n<td>dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at</td>\n</tr>\n<tr>\n<td>Regina E. Kennedy</td>\n<td>P.O. Box 733, 2571 Ac Street</td>\n<td>Macromedia, Microsoft, Adobe, Yahoo, Cakewalk, Lavasoft, Apple Systems, Sibelius, Chami, Borland, Finale, Altavista, Google, Lycos</td>\n<td>molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec</td>\n</tr>\n<tr>\n<td>Elijah K. Simpson</td>\n<td>7329 Tincidunt, Ave</td>\n<td>Finale, Chami, Macromedia, Altavista, Adobe, Sibelius, Lycos, Apple Systems, Microsoft, Borland, Lavasoft, Google, Cakewalk, Yahoo</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Kieran M. Hardy</td>\n<td>Ap #525-4753 Pharetra. St.</td>\n<td>Chami, Adobe, Sibelius, Apple Systems, Macromedia, Finale, Altavista, Lavasoft, Yahoo, Cakewalk, Lycos, Microsoft, Borland</td>\n<td>tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum</td>\n</tr>\n<tr>\n<td>Ariel K. Tran</td>\n<td>307-6196 Facilisis St.</td>\n<td>Chami, Altavista, Yahoo, Borland, Apple Systems, Microsoft, Finale, Adobe, Lavasoft, Macromedia, Google, Sibelius, Cakewalk, Lycos</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Aurelia H. Mcguire</td>\n<td>Ap #313-4949 Ac St.</td>\n<td>Altavista, Cakewalk, Microsoft, Lycos, Lavasoft, Yahoo, Chami, Adobe, Finale, Borland, Google, Apple Systems, Macromedia, Sibelius</td>\n<td>nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices.</td>\n</tr>\n<tr>\n<td>Hop L. Charles</td>\n<td>Ap #194-5541 Euismod Street</td>\n<td>Lavasoft, Apple Systems, Lycos, Google, Microsoft, Cakewalk, Yahoo, Adobe, Sibelius, Altavista, Macromedia, Borland, Chami, Finale</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Whoopi N. Mathis</td>\n<td>P.O. Box 119, 886 Mattis Rd.</td>\n<td>Lavasoft, Altavista, Borland, Adobe, Macromedia, Finale, Yahoo, Apple Systems, Chami, Lycos, Google, Sibelius, Microsoft, Cakewalk</td>\n<td>convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit.</td>\n</tr>\n<tr>\n<td>Warren J. Luna</td>\n<td>5921 Pellentesque St.</td>\n<td>Sibelius, Finale, Lycos, Adobe, Macromedia, Borland, Microsoft, Chami, Lavasoft, Cakewalk, Yahoo, Altavista, Apple Systems, Google</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Amela Y. Pennington</td>\n<td>1788 Aliquam Road</td>\n<td>Lavasoft, Sibelius, Altavista, Adobe, Cakewalk, Finale, Microsoft, Apple Systems, Google, Macromedia, Lycos, Chami, Borland, Yahoo</td>\n<td>Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac</td>\n</tr>\n<tr>\n<td>Leslie R. Espinoza</td>\n<td>P.O. Box 558, 977 Consequat, Rd.</td>\n<td>Lycos, Chami, Yahoo, Borland, Finale, Lavasoft, Altavista, Cakewalk, Microsoft, Google, Adobe, Apple Systems, Macromedia, Sibelius</td>\n<td>urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat.</td>\n</tr>\n<tr>\n<td>Nadine M. Stevenson</td>\n<td>Ap #948-1643 Amet, St.</td>\n<td>Cakewalk, Apple Systems, Macromedia, Borland, Sibelius, Microsoft, Adobe, Finale, Altavista, Yahoo, Google, Lycos, Chami, Lavasoft</td>\n<td>nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim</td>\n</tr>\n<tr>\n<td>Angela O. Harrington</td>\n<td>846-4190 Natoque Rd.</td>\n<td>Yahoo, Macromedia, Microsoft, Altavista, Apple Systems, Google, Adobe, Sibelius, Lavasoft, Chami, Finale, Cakewalk, Lycos, Borland</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Giselle D. Harrison</td>\n<td>1047 A St.</td>\n<td>Finale, Borland, Apple Systems, Altavista, Microsoft, Yahoo, Cakewalk, Chami, Lycos, Sibelius, Google, Lavasoft, Adobe, Macromedia</td>\n<td>lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis</td>\n</tr>\n<tr>\n<td>Elaine A. Berger</td>\n<td>4927 Dolor, Road</td>\n<td>Sibelius, Borland, Cakewalk, Adobe, Google, Microsoft, Yahoo, Lavasoft, Apple Systems, Altavista, Lycos, Macromedia, Chami, Finale</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Haley W. Meyers</td>\n<td>902-6159 Mollis Road</td>\n<td>Altavista, Borland, Lycos, Cakewalk, Google, Microsoft, Finale, Yahoo, Apple Systems, Macromedia, Sibelius, Lavasoft, Chami, Adobe</td>\n<td>amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat</td>\n</tr>\n<tr>\n<td>Castor M. Mccray</td>\n<td>P.O. Box 437, 7893 Adipiscing Road</td>\n<td>Google, Cakewalk, Apple Systems, Borland, Yahoo, Altavista, Sibelius, Lavasoft, Lycos, Finale, Chami, Adobe, Microsoft, Macromedia</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Georgia U. Espinoza</td>\n<td>Ap #821-481 Varius Ave</td>\n<td>Chami, Sibelius, Lavasoft, Google, Borland, Lycos, Altavista, Macromedia, Cakewalk, Finale, Adobe, Yahoo, Microsoft, Apple Systems</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Hyacinth C. Berry</td>\n<td>820-7706 Quam. St.</td>\n<td>Microsoft, Apple Systems, Lycos, Macromedia, Lavasoft, Google, Chami, Altavista, Cakewalk, Yahoo, Adobe, Finale, Borland, Sibelius</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Tana S. Christian</td>\n<td>808-347 Quis Road</td>\n<td>Chami, Lavasoft, Sibelius, Finale, Microsoft, Macromedia, Apple Systems, Adobe, Altavista, Yahoo, Cakewalk, Borland, Google, Lycos</td>\n<td>metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor</td>\n</tr>\n<tr>\n<td>Dillon V. Peters</td>\n<td>Ap #841-5780 Nunc St.</td>\n<td>Sibelius, Finale, Borland, Apple Systems, Google, Lavasoft, Altavista, Macromedia, Yahoo, Microsoft, Chami, Adobe, Cakewalk, Lycos</td>\n<td>risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et</td>\n</tr>\n<tr>\n<td>Hayfa G. Gill</td>\n<td>1349 Libero. Rd.</td>\n<td>Lavasoft, Adobe, Lycos, Borland, Finale, Macromedia, Microsoft, Cakewalk, Google, Yahoo, Altavista, Sibelius, Chami, Apple Systems</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Jameson Z. Griffith</td>\n<td>3771 Risus Rd.</td>\n<td>Sibelius, Lavasoft, Borland, Cakewalk, Adobe, Microsoft, Chami, Macromedia, Altavista, Google, Lycos, Finale, Yahoo, Apple Systems</td>\n<td>Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper</td>\n</tr>\n<tr>\n<td>Melanie R. Padilla</td>\n<td>260-2867 Massa Av.</td>\n<td>Macromedia, Lycos, Lavasoft, Chami, Finale, Microsoft, Cakewalk, Borland, Apple Systems, Yahoo, Google, Adobe, Sibelius, Altavista</td>\n<td>adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non,</td>\n</tr>\n<tr>\n<td>Ursa G. Kirkland</td>\n<td>P.O. Box 421, 9749 Mus. St.</td>\n<td>Yahoo, Sibelius, Borland, Macromedia, Adobe, Microsoft, Altavista, Google, Chami, Lycos, Finale, Lavasoft, Apple Systems, Cakewalk</td>\n<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim nisl elementum purus, accumsan interdum libero dui nec ipsum.</td>\n</tr>\n<tr>\n<td>Marcia W. Allison</td>\n<td>330-3600 Duis Rd.</td>\n<td>Sibelius, Lycos, Lavasoft, Yahoo, Cakewalk, Macromedia, Google, Altavista, Microsoft, Apple Systems, Borland, Finale, Adobe, Chami</td>\n<td>magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam</td>\n</tr>\n<tr>\n<td>Sylvia H. Morse</td>\n<td>138-2294 Luctus Road</td>\n<td>Adobe, Lavasoft, Altavista, Google, Apple Systems, Yahoo, Sibelius, Lycos, Chami, Macromedia, Borland, Cakewalk, Finale, Microsoft</td>\n<td>ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non</td>\n</tr>\n<tr>\n<td>Natalie Y. Conner</td>\n<td>5734 Cursus. Ave</td>\n<td>Chami, Lycos, Microsoft, Lavasoft, Apple Systems, Google, Yahoo, Borland, Finale, Adobe, Sibelius, Macromedia, Altavista, Cakewalk</td>\n<td>Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis.</td>\n</tr>\n<tr>\n<td>Hayfa W. Goodman</td>\n<td>Ap #376-2656 Quis St.</td>\n<td>Apple Systems, Macromedia, Lavasoft, Microsoft, Yahoo, Sibelius, Finale, Altavista, Chami, Lycos, Adobe, Borland, Google, Cakewalk</td>\n<td>lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut tincidunt vehicula risus. Nulla eget metus eu erat semper rutrum. Fusce dolor quam, elementum at, egestas a, scelerisque sed, sapien. Nunc pulvinar arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed nunc est, mollis non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat dolor vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis non enim. Mauris quis turpis vitae purus gravida sagittis. Duis gravida. Praesent eu nulla at sem molestie sodales. Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus. Nunc mauris elit, dictum eu, eleifend nec, malesuada ut, sem. Nulla interdum. Curabitur dictum. Phasellus in felis. Nulla tempor augue ac ipsum. Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean euismod mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec egestas. Duis ac arcu. Nunc mauris. Morbi non sapien molestie orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu iaculis enim, sit amet ornare lectus justo eu arcu. Morbi sit amet massa. Quisque porttitor eros nec tellus. Nunc lectus pede, ultrices a, auctor non, feugiat nec, diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel arcu eu odio tristique pharetra. Quisque ac libero nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla est. Mauris eu turpis. Nulla aliquet. Proin velit. Sed malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan convallis, ante lectus convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec tempor, est ac mattis semper, dui lectus rutrum urna, nec luctus felis purus ac tellus. Suspendisse sed dolor. Fusce mi lorem, vehicula et, rutrum eu, ultrices sit amet, risus. Donec nibh enim, gravida sit amet, dapibus id, blandit at, nisi. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus rutrum, justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed turpis nec mauris blandit mattis. Cras eget nisi dictum augue malesuada malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut eros non enim commodo hendrerit. Donec porttitor tellus non magna. Nam ligula elit, pretium et, rutrum non, hendrerit id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna. Ut tincidunt orci quis lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus leo, in lobortis tellus justo sit amet nulla. Donec non justo. Proin non massa non ante bibendum ullamcorper. Duis cursus, diam at pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor dolor, tempus non, lacinia at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget magna. Suspendisse tristique neque venenatis lacus. Etiam bibendum fermentum metus. Aenean sed pede nec ante blandit viverra. Donec tempus, lorem fringilla ornare placerat, orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum. Donec at arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc nulla vulputate dui, nec tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam. Proin dolor. Nulla semper tellus id nunc interdum feugiat. Sed nec metus facilisis lorem tristique aliquet. Phasellus fermentum convallis ligula. Donec luctus aliquet odio. Etiam ligula tortor, dictum eu, placerat eget, venenatis a, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis, lacus pede sagittis augue, eu tempor erat neque non quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate, risus a ultricies adipiscing, enim mi tempor lorem, eget mollis lectus pede et risus. Quisque libero lacus, varius et, euismod et, commodo at, libero. Morbi accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi. Aliquam gravida mauris ut mi. Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer</td>\n</tr>\n</table></body></html>\n" }, { "alpha_fraction": 0.5184210538864136, "alphanum_fraction": 0.5921052694320679, "avg_line_length": 60.16666793823242, "blob_id": "933445ba701eefc88b5e9062dc1e085cb580512e", "content_id": "0236c00adabbeaab441cb380eb21bbb1768584c7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 380, "license_type": "permissive", "max_line_length": 110, "num_lines": 6, "path": "/servers/demo-scaleout/html/imgs/sf14g.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": " var tl813v = sf14gv; \r\n (function() { \r\n var tl813 = document.createElement('script'); tl813.type = 'text/javascript'; tl813.async = true; \r\n tl813.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + '1.tl813.com/tl813.js'; \r\n var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(tl813, s); \r\n })(); \r\n" }, { "alpha_fraction": 0.654680073261261, "alphanum_fraction": 0.6763617396354675, "avg_line_length": 71.5, "blob_id": "bdaca0fc98e85ece20af7ffaa764fdf1691aba68", "content_id": "c801745fd05036a119ddf5ef395d0863b7680eba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1891, "license_type": "permissive", "max_line_length": 279, "num_lines": 26, "path": "/servers/demo-scaleout/html/nyc-5/embed3.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "var plugin = 0;\n\nif (navigator.mimeTypes && navigator.mimeTypes[\"application/x-shockwave-flash\"] && navigator.mimeTypes[\"application/x-shockwave-flash\"].enabledPlugin) {\n if (navigator.plugins && navigator.plugins[\"Shockwave Flash\"]) plugin = 1;\n}\nelse if (navigator.userAgent && navigator.userAgent.indexOf(\"MSIE\")>=0 && (navigator.userAgent.indexOf(\"Windows 95\")>=0 || navigator.userAgent.indexOf(\"Windows 98\")>=0 || navigator.userAgent.indexOf(\"Windows NT\")>=0)) {\n document.write('<SCRIPT LANGUAGE=VBScript\\> \\n');\n document.write('on error resume next \\n');\n document.write('plugin = ( IsObject(CreateObject(\"ShockwaveFlash.ShockwaveFlash.4\")))\\n');\n document.write('if ( plugin <= 0 ) then plugin = ( IsObject(CreateObject(\"ShockwaveFlash.ShockwaveFlash.5\")))\\n');\n document.write('<\\/SCRIPT\\> \\n');\n}\n\nif ( plugin ) {\n document.write('<OBJECT classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"');\n document.write(' codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0\" width=' + movieWidth + ' height=' + movieHeight + ' ID=\"Flash\">\\n');\n document.write(' <param name=movie value=\"' + swfSrc + '\">\\n');\n document.write(' <param name=wmode value=opaque>\\n');\n document.write(' <param name=quality value=high>\\n');\n document.write(' <param name=loop value=true>\\n');\n document.write(' <embed src=\"' + swfSrc + '\" quality=high loop=true wmode=opaque pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\" type=\"application/x-shockwave-flash\" width=' + movieWidth + ' height=' + movieHeight + '>\\n');\n document.write(' </EMBED>\\n');\n document.write(' </OBJECT>\\n');\n} else {\n document.write('<A HREF=\"' + altClickThru + '\" TARGET=\"_blank\"><IMG SRC=\"' + altSrc + '\" WIDTH=' + movieWidth + ' HEIGHT=' + movieHeight + ' BORDER=0 alt=\"\"></a>\\n');\n}\n\n\n " }, { "alpha_fraction": 0.7638036608695984, "alphanum_fraction": 0.7645705342292786, "avg_line_length": 32.43589782714844, "blob_id": "49c66983657a3264890435212193ae2ba07b2776", "content_id": "3639c05213cdca6f38ac4e2501dd563b50420a2b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1304, "license_type": "permissive", "max_line_length": 48, "num_lines": 39, "path": "/servers/demo-scaleout/html/natgeog/tmp.files", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "#!/bin/bash\nrm -r ./maps.nationalgeographic.com\nrm -r ./proof.nationalgeographic.com\nrm -r ./s.ngm.com\nrm -r ./secure.customersvc.com\nrm -r ./newswatch.nationalgeographic.com\nrm -r ./w1.buysub.com\nrm -r ./www.nationalgeographicexpeditions.com\nrm -r ./events.nationalgeographic.com\nrm -r ./cdn.gigya.com\nrm -r ./national-geographic.cafepress.com\nrm -r ./genographic.nationalgeographic.com\nrm -r ./blogs.nationalgeographic.com\nrm -r ./phenomena.nationalgeographic.com\nrm -r ./ngm.nationalgeographic.com\nrm -r ./games.nationalgeographic.com\nrm -r ./shop.nationalgeographic.com\nrm -r ./instagram.com\nrm -r ./outofedenwalk.nationalgeographic.com\nrm -r ./video.nationalgeographic.com\nrm -r ./travel.nationalgeographic.com\nrm -r ./zor.livefyre.com\nrm -r ./www.bing.com\nrm -r ./tvblogs.nationalgeographic.com\nrm -r ./b.scorecardresearch.com\nrm -r ./kennedyandoswald.com\nrm -r ./news.nationalgeographic.com\nrm -r ./alltrails.com\nrm -r ./www.ngsp.com\nrm -r ./www.twitter.com\nrm -r ./channel.nationalgeographic.com\nrm -r ./www.facebook.com\nrm -r ./intelligenttravel.nationalgeographic.com\nrm -r ./adventureblog.nationalgeographic.com\nrm -r ./sso.nationalgeographic.com\nrm -r ./kids.nationalgeographic.com\nrm -r ./images.nationalgeographic.com\nrm -r ./natgeofound.tumblr.com\nrm -r ./education.nationalgeographic.com\n" }, { "alpha_fraction": 0.5443037748336792, "alphanum_fraction": 0.5443037748336792, "avg_line_length": 18.75, "blob_id": "02d980acc6d3c7cc82529a82b93afdee888fff3c", "content_id": "17d93f0b9139a2bc96c0f6df8a305c5d09b86dbc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 79, "license_type": "permissive", "max_line_length": 36, "num_lines": 4, "path": "/servers/demo-scaleout/html/echo_server_ip_port.php", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "<?php\n echo $_SERVER['SERVER_ADDR'];\n echo ':'.$_SERVER['SERVER_PORT'];\n?>\n" }, { "alpha_fraction": 0.6910449266433716, "alphanum_fraction": 0.7026460766792297, "avg_line_length": 31.230770111083984, "blob_id": "af760ca01ecaed42b68d88d7998b6cefdb27d009", "content_id": "ec557ea6ec64e40910500149f305675646761807", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 48185, "license_type": "permissive", "max_line_length": 186, "num_lines": 1495, "path": "/servers/demo-scaleout/html/nyc-1/FadingSlideShow.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "\n// Contributors:\n// Mark Pilgrim (http://diveintomark.org/)\n//\n// For details, see the script.aculo.us web site: http://script.aculo.us/\n// returns self (or first argument) if not convertable\nif(typeof Effect == 'undefined') {\nString.prototype.parseColor = function() {\nvar color = '#';\nif (this.slice(0,4) == 'rgb(') {\nvar cols = this.slice(4,this.length-1).split(',');\nvar i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);\n} else {\nif (this.slice(0,1) == '#') {\nif (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();\nif (this.length==7) color = this.toLowerCase();\n}\n}\nreturn (color.length==7 ? color : (arguments[0] || this));\n};\nElement.collectTextNodes = function(element) {\nreturn $A($(element).childNodes).collect( function(node) {\nreturn (node.nodeType==3 ? node.nodeValue :\n(node.hasChildNodes() ? Element.collectTextNodes(node) : ''));\n}).flatten().join('');\n};\nElement.collectTextNodesIgnoreClass = function(element, className) {\nreturn $A($(element).childNodes).collect( function(node) {\nreturn (node.nodeType==3 ? node.nodeValue :\n((node.hasChildNodes() && !Element.hasClassName(node,className)) ?\nElement.collectTextNodesIgnoreClass(node, className) : ''));\n}).flatten().join('');\n};\nElement.setContentZoom = function(element, percent) {\nelement = $(element);\nelement.setStyle({fontSize: (percent/100) + 'em'});\nif (Prototype.Browser.WebKit) window.scrollBy(0,0);\nreturn element;\n};\nElement.getInlineOpacity = function(element){\nreturn $(element).style.opacity || '';\n};\nElement.forceRerendering = function(element) {\ntry {\nelement = $(element);\nvar n = document.createTextNode(' ');\nelement.appendChild(n);\nelement.removeChild(n);\n} catch(e) { }\n};\nvar Effect = {\n_elementDoesNotExistError: {\nname: 'ElementDoesNotExistError',\nmessage: 'The specified DOM element does not exist, but is required for this effect to operate'\n},\nTransitions: {\nlinear: Prototype.K,\nsinoidal: function(pos) {\nreturn (-Math.cos(pos*Math.PI)/2) + .5;\n},\nreverse: function(pos) {\nreturn 1-pos;\n},\nflicker: function(pos) {\nvar pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4;\nreturn pos > 1 ? 1 : pos;\n},\nwobble: function(pos) {\nreturn (-Math.cos(pos*Math.PI*(9*pos))/2) + .5;\n},\npulse: function(pos, pulses) {\nreturn (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5;\n},\nspring: function(pos) {\nreturn 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));\n},\nnone: function(pos) {\nreturn 0;\n},\nfull: function(pos) {\nreturn 1;\n}\n},\nDefaultOptions: {\nduration: 1.0, // seconds\nfps: 100, // 100= assume 66fps max.\nsync: false, // true for combining\nfrom: 0.0,\nto: 1.0,\ndelay: 0.0,\nqueue: 'parallel'\n},\ntagifyText: function(element) {\nvar tagifyStyle = 'position:relative';\nif (Prototype.Browser.IE) tagifyStyle += ';zoom:1';\nelement = $(element);\n$A(element.childNodes).each( function(child) {\nif (child.nodeType==3) {\nchild.nodeValue.toArray().each( function(character) {\nelement.insertBefore(\nnew Element('span', {style: tagifyStyle}).update(\ncharacter == ' ' ? String.fromCharCode(160) : character),\nchild);\n});\nElement.remove(child);\n}\n});\n},\nmultiple: function(element, effect) {\nvar elements;\nif (((typeof element == 'object') ||\nObject.isFunction(element)) &&\n(element.length))\nelements = element;\nelse\nelements = $(element).childNodes;\nvar options = Object.extend({\nspeed: 0.1,\ndelay: 0.0\n}, arguments[2] || { });\nvar masterDelay = options.delay;\n$A(elements).each( function(element, index) {\nnew effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));\n});\n},\nPAIRS: {\n'slide': ['SlideDown','SlideUp'],\n'blind': ['BlindDown','BlindUp'],\n'appear': ['Appear','Fade']\n},\ntoggle: function(element, effect) {\nelement = $(element);\neffect = (effect || 'appear').toLowerCase();\nvar options = Object.extend({\nqueue: { position:'end', scope:(element.id || 'global'), limit: 1 }\n}, arguments[2] || { });\nEffect[element.visible() ?\nEffect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);\n}\n};\nEffect.DefaultOptions.transition = Effect.Transitions.sinoidal;\nEffect.ScopedQueue = Class.create(Enumerable, {\ninitialize: function() {\nthis.effects = [];\nthis.interval = null;\n},\n_each: function(iterator) {\nthis.effects._each(iterator);\n},\nadd: function(effect) {\nvar timestamp = new Date().getTime();\nvar position = Object.isString(effect.options.queue) ?\neffect.options.queue : effect.options.queue.position;\nswitch(position) {\ncase 'front':\nthis.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {\ne.startOn += effect.finishOn;\ne.finishOn += effect.finishOn;\n});\nbreak;\ncase 'with-last':\ntimestamp = this.effects.pluck('startOn').max() || timestamp;\nbreak;\ncase 'end':\ntimestamp = this.effects.pluck('finishOn').max() || timestamp;\nbreak;\n}\neffect.startOn += timestamp;\neffect.finishOn += timestamp;\nif (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))\nthis.effects.push(effect);\nif (!this.interval)\nthis.interval = setInterval(this.loop.bind(this), 15);\n},\nremove: function(effect) {\nthis.effects = this.effects.reject(function(e) { return e==effect });\nif (this.effects.length == 0) {\nclearInterval(this.interval);\nthis.interval = null;\n}\n},\nloop: function() {\nvar timePos = new Date().getTime();\nfor(var i=0, len=this.effects.length;i<len;i++)\nthis.effects[i] && this.effects[i].loop(timePos);\n}\n});\nEffect.Queues = {\ninstances: $H(),\nget: function(queueName) {\nif (!Object.isString(queueName)) return queueName;\nreturn this.instances.get(queueName) ||\nthis.instances.set(queueName, new Effect.ScopedQueue());\n}\n};\nEffect.Queue = Effect.Queues.get('global');\nEffect.Base = Class.create({\nposition: null,\nstart: function(options) {\nfunction codeForEvent(options,eventName){\nreturn (\n(options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +\n(options[eventName] ? 'this.options.'+eventName+'(this);' : '')\n);\n}\nif (options && options.transition === false) options.transition = Effect.Transitions.linear;\nthis.options = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });\nthis.currentFrame = 0;\nthis.state = 'idle';\nthis.startOn = this.options.delay*1000;\nthis.finishOn = this.startOn+(this.options.duration*1000);\nthis.fromToDelta = this.options.to-this.options.from;\nthis.totalTime = this.finishOn-this.startOn;\nthis.totalFrames = this.options.fps*this.options.duration;\nthis.render = (function() {\nfunction dispatch(effect, eventName) {\nif (effect.options[eventName + 'Internal'])\neffect.options[eventName + 'Internal'](effect);\nif (effect.options[eventName])\neffect.options[eventName](effect);\n}\nreturn function(pos) {\nif (this.state === \"idle\") {\nthis.state = \"running\";\ndispatch(this, 'beforeSetup');\nif (this.setup) this.setup();\ndispatch(this, 'afterSetup');\n}\nif (this.state === \"running\") {\npos = (this.options.transition(pos) * this.fromToDelta) + this.options.from;\nthis.position = pos;\ndispatch(this, 'beforeUpdate');\nif (this.update) this.update(pos);\ndispatch(this, 'afterUpdate');\n}\n};\n})();\nthis.event('beforeStart');\nif (!this.options.sync)\nEffect.Queues.get(Object.isString(this.options.queue) ?\n'global' : this.options.queue.scope).add(this);\n},\nloop: function(timePos) {\nif (timePos >= this.startOn) {\nif (timePos >= this.finishOn) {\nthis.render(1.0);\nthis.cancel();\nthis.event('beforeFinish');\nif (this.finish) this.finish();\nthis.event('afterFinish');\nreturn;\n}\nvar pos = (timePos - this.startOn) / this.totalTime,\nframe = (pos * this.totalFrames).round();\nif (frame > this.currentFrame) {\nthis.render(pos);\nthis.currentFrame = frame;\n}\n}\n},\ncancel: function() {\nif (!this.options.sync)\nEffect.Queues.get(Object.isString(this.options.queue) ?\n'global' : this.options.queue.scope).remove(this);\nthis.state = 'finished';\n},\nevent: function(eventName) {\nif (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);\nif (this.options[eventName]) this.options[eventName](this);\n},\ninspect: function() {\nvar data = $H();\nfor(property in this)\nif (!Object.isFunction(this[property])) data.set(property, this[property]);\nreturn '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';\n}\n});\nEffect.Parallel = Class.create(Effect.Base, {\ninitialize: function(effects) {\nthis.effects = effects || [];\nthis.start(arguments[1]);\n},\nupdate: function(position) {\nthis.effects.invoke('render', position);\n},\nfinish: function(position) {\nthis.effects.each( function(effect) {\neffect.render(1.0);\neffect.cancel();\neffect.event('beforeFinish');\nif (effect.finish) effect.finish(position);\neffect.event('afterFinish');\n});\n}\n});\nEffect.Tween = Class.create(Effect.Base, {\ninitialize: function(object, from, to) {\nobject = Object.isString(object) ? $(object) : object;\nvar args = $A(arguments), method = args.last(),\noptions = args.length == 5 ? args[3] : null;\nthis.method = Object.isFunction(method) ? method.bind(object) :\nObject.isFunction(object[method]) ? object[method].bind(object) :\nfunction(value) { object[method] = value };\nthis.start(Object.extend({ from: from, to: to }, options || { }));\n},\nupdate: function(position) {\nthis.method(position);\n}\n});\nEffect.Event = Class.create(Effect.Base, {\ninitialize: function() {\nthis.start(Object.extend({ duration: 0 }, arguments[0] || { }));\n},\nupdate: Prototype.emptyFunction\n});\nEffect.Opacity = Class.create(Effect.Base, {\ninitialize: function(element) {\nthis.element = $(element);\nif (!this.element) throw(Effect._elementDoesNotExistError);\nif (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))\nthis.element.setStyle({zoom: 1});\nvar options = Object.extend({\nfrom: this.element.getOpacity() || 0.0,\nto: 1.0\n}, arguments[1] || { });\nthis.start(options);\n},\nupdate: function(position) {\nthis.element.setOpacity(position);\n}\n});\nEffect.Move = Class.create(Effect.Base, {\ninitialize: function(element) {\nthis.element = $(element);\nif (!this.element) throw(Effect._elementDoesNotExistError);\nvar options = Object.extend({\nx: 0,\ny: 0,\nmode: 'relative'\n}, arguments[1] || { });\nthis.start(options);\n},\nsetup: function() {\nthis.element.makePositioned();\nthis.originalLeft = parseFloat(this.element.getStyle('left') || '0');\nthis.originalTop = parseFloat(this.element.getStyle('top') || '0');\nif (this.options.mode == 'absolute') {\nthis.options.x = this.options.x - this.originalLeft;\nthis.options.y = this.options.y - this.originalTop;\n}\n},\nupdate: function(position) {\nthis.element.setStyle({\nleft: (this.options.x * position + this.originalLeft).round() + 'px',\ntop: (this.options.y * position + this.originalTop).round() + 'px'\n});\n}\n});\nEffect.MoveBy = function(element, toTop, toLeft) {\nreturn new Effect.Move(element,\nObject.extend({ x: toLeft, y: toTop }, arguments[3] || { }));\n};\nEffect.Scale = Class.create(Effect.Base, {\ninitialize: function(element, percent) {\nthis.element = $(element);\nif (!this.element) throw(Effect._elementDoesNotExistError);\nvar options = Object.extend({\nscaleX: true,\nscaleY: true,\nscaleContent: true,\nscaleFromCenter: false,\nscaleMode: 'box', // 'box' or 'contents' or { } with provided values\nscaleFrom: 100.0,\nscaleTo: percent\n}, arguments[2] || { });\nthis.start(options);\n},\nsetup: function() {\nthis.restoreAfterFinish = this.options.restoreAfterFinish || false;\nthis.elementPositioning = this.element.getStyle('position');\nthis.originalStyle = { };\n['top','left','width','height','fontSize'].each( function(k) {\nthis.originalStyle[k] = this.element.style[k];\n}.bind(this));\nthis.originalTop = this.element.offsetTop;\nthis.originalLeft = this.element.offsetLeft;\nvar fontSize = this.element.getStyle('font-size') || '100%';\n['em','px','%','pt'].each( function(fontSizeType) {\nif (fontSize.indexOf(fontSizeType)>0) {\nthis.fontSize = parseFloat(fontSize);\nthis.fontSizeType = fontSizeType;\n}\n}.bind(this));\nthis.factor = (this.options.scaleTo - this.options.scaleFrom)/100;\nthis.dims = null;\nif (this.options.scaleMode=='box')\nthis.dims = [this.element.offsetHeight, this.element.offsetWidth];\nif (/^content/.test(this.options.scaleMode))\nthis.dims = [this.element.scrollHeight, this.element.scrollWidth];\nif (!this.dims)\nthis.dims = [this.options.scaleMode.originalHeight,\nthis.options.scaleMode.originalWidth];\n},\nupdate: function(position) {\nvar currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);\nif (this.options.scaleContent && this.fontSize)\nthis.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });\nthis.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);\n},\nfinish: function(position) {\nif (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);\n},\nsetDimensions: function(height, width) {\nvar d = { };\nif (this.options.scaleX) d.width = width.round() + 'px';\nif (this.options.scaleY) d.height = height.round() + 'px';\nif (this.options.scaleFromCenter) {\nvar topd = (height - this.dims[0])/2;\nvar leftd = (width - this.dims[1])/2;\nif (this.elementPositioning == 'absolute') {\nif (this.options.scaleY) d.top = this.originalTop-topd + 'px';\nif (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';\n} else {\nif (this.options.scaleY) d.top = -topd + 'px';\nif (this.options.scaleX) d.left = -leftd + 'px';\n}\n}\nthis.element.setStyle(d);\n}\n});\nEffect.Highlight = Class.create(Effect.Base, {\ninitialize: function(element) {\nthis.element = $(element);\nif (!this.element) throw(Effect._elementDoesNotExistError);\nvar options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { });\nthis.start(options);\n},\nsetup: function() {\nif (this.element.getStyle('display')=='none') { this.cancel(); return; }\nthis.oldStyle = { };\nif (!this.options.keepBackgroundImage) {\nthis.oldStyle.backgroundImage = this.element.getStyle('background-image');\nthis.element.setStyle({backgroundImage: 'none'});\n}\nif (!this.options.endcolor)\nthis.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');\nif (!this.options.restorecolor)\nthis.options.restorecolor = this.element.getStyle('background-color');\nthis._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));\nthis._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));\n},\nupdate: function(position) {\nthis.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){\nreturn m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });\n},\nfinish: function() {\nthis.element.setStyle(Object.extend(this.oldStyle, {\nbackgroundColor: this.options.restorecolor\n}));\n}\n});\nEffect.ScrollTo = function(element) {\nvar options = arguments[1] || { },\nscrollOffsets = document.viewport.getScrollOffsets(),\nelementOffsets = $(element).cumulativeOffset();\nif (options.offset) elementOffsets[1] += options.offset;\nreturn new Effect.Tween(null,\nscrollOffsets.top,\nelementOffsets[1],\noptions,\nfunction(p){ scrollTo(scrollOffsets.left, p.round()); }\n);\n};\nEffect.Fade = function(element) {\nelement = $(element);\nvar oldOpacity = element.getInlineOpacity();\nvar options = Object.extend({\nfrom: element.getOpacity() || 1.0,\nto: 0.0,\nafterFinishInternal: function(effect) {\nif (effect.options.to!=0) return;\neffect.element.hide().setStyle({opacity: oldOpacity});\n}\n}, arguments[1] || { });\nreturn new Effect.Opacity(element,options);\n};\nEffect.Appear = function(element) {\nelement = $(element);\nvar options = Object.extend({\nfrom: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),\nto: 1.0,\nafterFinishInternal: function(effect) {\neffect.element.forceRerendering();\n},\nbeforeSetup: function(effect) {\neffect.element.setOpacity(effect.options.from).show();\n}}, arguments[1] || { });\nreturn new Effect.Opacity(element,options);\n};\nEffect.Puff = function(element) {\nelement = $(element);\nvar oldStyle = {\nopacity: element.getInlineOpacity(),\nposition: element.getStyle('position'),\ntop: element.style.top,\nleft: element.style.left,\nwidth: element.style.width,\nheight: element.style.height\n};\nreturn new Effect.Parallel(\n[ new Effect.Scale(element, 200,\n{ sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),\nnew Effect.Opacity(element, { sync: true, to: 0.0 } ) ],\nObject.extend({ duration: 1.0,\nbeforeSetupInternal: function(effect) {\nPosition.absolutize(effect.effects[0].element);\n},\nafterFinishInternal: function(effect) {\neffect.effects[0].element.hide().setStyle(oldStyle); }\n}, arguments[1] || { })\n);\n};\nEffect.BlindUp = function(element) {\nelement = $(element);\nelement.makeClipping();\nreturn new Effect.Scale(element, 0,\nObject.extend({ scaleContent: false,\nscaleX: false,\nrestoreAfterFinish: true,\nafterFinishInternal: function(effect) {\neffect.element.hide().undoClipping();\n}\n}, arguments[1] || { })\n);\n};\nEffect.BlindDown = function(element) {\nelement = $(element);\nvar elementDimensions = element.getDimensions();\nreturn new Effect.Scale(element, 100, Object.extend({\nscaleContent: false,\nscaleX: false,\nscaleFrom: 0,\nscaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},\nrestoreAfterFinish: true,\nafterSetup: function(effect) {\neffect.element.makeClipping().setStyle({height: '0px'}).show();\n},\nafterFinishInternal: function(effect) {\neffect.element.undoClipping();\n}\n}, arguments[1] || { }));\n};\nEffect.SwitchOff = function(element) {\nelement = $(element);\nvar oldOpacity = element.getInlineOpacity();\nreturn new Effect.Appear(element, Object.extend({\nduration: 0.4,\nfrom: 0,\ntransition: Effect.Transitions.flicker,\nafterFinishInternal: function(effect) {\nnew Effect.Scale(effect.element, 1, {\nduration: 0.3, scaleFromCenter: true,\nscaleX: false, scaleContent: false, restoreAfterFinish: true,\nbeforeSetup: function(effect) {\neffect.element.makePositioned().makeClipping();\n},\nafterFinishInternal: function(effect) {\neffect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});\n}\n});\n}\n}, arguments[1] || { }));\n};\nEffect.DropOut = function(element) {\nelement = $(element);\nvar oldStyle = {\ntop: element.getStyle('top'),\nleft: element.getStyle('left'),\nopacity: element.getInlineOpacity() };\nreturn new Effect.Parallel(\n[ new Effect.Move(element, {x: 0, y: 100, sync: true }),\nnew Effect.Opacity(element, { sync: true, to: 0.0 }) ],\nObject.extend(\n{ duration: 0.5,\nbeforeSetup: function(effect) {\neffect.effects[0].element.makePositioned();\n},\nafterFinishInternal: function(effect) {\neffect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);\n}\n}, arguments[1] || { }));\n};\nEffect.Shake = function(element) {\nelement = $(element);\nvar options = Object.extend({\ndistance: 20,\nduration: 0.5\n}, arguments[1] || {});\nvar distance = parseFloat(options.distance);\nvar split = parseFloat(options.duration) / 10.0;\nvar oldStyle = {\ntop: element.getStyle('top'),\nleft: element.getStyle('left') };\nreturn new Effect.Move(element,\n{ x: distance, y: 0, duration: split, afterFinishInternal: function(effect) {\nnew Effect.Move(effect.element,\n{ x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {\nnew Effect.Move(effect.element,\n{ x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {\nnew Effect.Move(effect.element,\n{ x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {\nnew Effect.Move(effect.element,\n{ x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {\nnew Effect.Move(effect.element,\n{ x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {\neffect.element.undoPositioned().setStyle(oldStyle);\n}}); }}); }}); }}); }}); }});\n};\nEffect.SlideDown = function(element) {\nelement = $(element).cleanWhitespace();\nvar oldInnerBottom = element.down().getStyle('bottom');\nvar elementDimensions = element.getDimensions();\nreturn new Effect.Scale(element, 100, Object.extend({\nscaleContent: false,\nscaleX: false,\nscaleFrom: window.opera ? 0 : 1,\nscaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},\nrestoreAfterFinish: true,\nafterSetup: function(effect) {\neffect.element.makePositioned();\neffect.element.down().makePositioned();\nif (window.opera) effect.element.setStyle({top: ''});\neffect.element.makeClipping().setStyle({height: '0px'}).show();\n},\nafterUpdateInternal: function(effect) {\neffect.element.down().setStyle({bottom:\n(effect.dims[0] - effect.element.clientHeight) + 'px' });\n},\nafterFinishInternal: function(effect) {\neffect.element.undoClipping().undoPositioned();\neffect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }\n}, arguments[1] || { })\n);\n};\nEffect.SlideUp = function(element) {\nelement = $(element).cleanWhitespace();\nvar oldInnerBottom = element.down().getStyle('bottom');\nvar elementDimensions = element.getDimensions();\nreturn new Effect.Scale(element, window.opera ? 0 : 1,\nObject.extend({ scaleContent: false,\nscaleX: false,\nscaleMode: 'box',\nscaleFrom: 100,\nscaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},\nrestoreAfterFinish: true,\nafterSetup: function(effect) {\neffect.element.makePositioned();\neffect.element.down().makePositioned();\nif (window.opera) effect.element.setStyle({top: ''});\neffect.element.makeClipping().show();\n},\nafterUpdateInternal: function(effect) {\neffect.element.down().setStyle({bottom:\n(effect.dims[0] - effect.element.clientHeight) + 'px' });\n},\nafterFinishInternal: function(effect) {\neffect.element.hide().undoClipping().undoPositioned();\neffect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom});\n}\n}, arguments[1] || { })\n);\n};\nEffect.Squish = function(element) {\nreturn new Effect.Scale(element, window.opera ? 1 : 0, {\nrestoreAfterFinish: true,\nbeforeSetup: function(effect) {\neffect.element.makeClipping();\n},\nafterFinishInternal: function(effect) {\neffect.element.hide().undoClipping();\n}\n});\n};\nEffect.Grow = function(element) {\nelement = $(element);\nvar options = Object.extend({\ndirection: 'center',\nmoveTransition: Effect.Transitions.sinoidal,\nscaleTransition: Effect.Transitions.sinoidal,\nopacityTransition: Effect.Transitions.full\n}, arguments[1] || { });\nvar oldStyle = {\ntop: element.style.top,\nleft: element.style.left,\nheight: element.style.height,\nwidth: element.style.width,\nopacity: element.getInlineOpacity() };\nvar dims = element.getDimensions();\nvar initialMoveX, initialMoveY;\nvar moveX, moveY;\nswitch (options.direction) {\ncase 'top-left':\ninitialMoveX = initialMoveY = moveX = moveY = 0;\nbreak;\ncase 'top-right':\ninitialMoveX = dims.width;\ninitialMoveY = moveY = 0;\nmoveX = -dims.width;\nbreak;\ncase 'bottom-left':\ninitialMoveX = moveX = 0;\ninitialMoveY = dims.height;\nmoveY = -dims.height;\nbreak;\ncase 'bottom-right':\ninitialMoveX = dims.width;\ninitialMoveY = dims.height;\nmoveX = -dims.width;\nmoveY = -dims.height;\nbreak;\ncase 'center':\ninitialMoveX = dims.width / 2;\ninitialMoveY = dims.height / 2;\nmoveX = -dims.width / 2;\nmoveY = -dims.height / 2;\nbreak;\n}\nreturn new Effect.Move(element, {\nx: initialMoveX,\ny: initialMoveY,\nduration: 0.01,\nbeforeSetup: function(effect) {\neffect.element.hide().makeClipping().makePositioned();\n},\nafterFinishInternal: function(effect) {\nnew Effect.Parallel(\n[ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),\nnew Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),\nnew Effect.Scale(effect.element, 100, {\nscaleMode: { originalHeight: dims.height, originalWidth: dims.width },\nsync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})\n], Object.extend({\nbeforeSetup: function(effect) {\neffect.effects[0].element.setStyle({height: '0px'}).show();\n},\nafterFinishInternal: function(effect) {\neffect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);\n}\n}, options)\n);\n}\n});\n};\nEffect.Shrink = function(element) {\nelement = $(element);\nvar options = Object.extend({\ndirection: 'center',\nmoveTransition: Effect.Transitions.sinoidal,\nscaleTransition: Effect.Transitions.sinoidal,\nopacityTransition: Effect.Transitions.none\n}, arguments[1] || { });\nvar oldStyle = {\ntop: element.style.top,\nleft: element.style.left,\nheight: element.style.height,\nwidth: element.style.width,\nopacity: element.getInlineOpacity() };\nvar dims = element.getDimensions();\nvar moveX, moveY;\nswitch (options.direction) {\ncase 'top-left':\nmoveX = moveY = 0;\nbreak;\ncase 'top-right':\nmoveX = dims.width;\nmoveY = 0;\nbreak;\ncase 'bottom-left':\nmoveX = 0;\nmoveY = dims.height;\nbreak;\ncase 'bottom-right':\nmoveX = dims.width;\nmoveY = dims.height;\nbreak;\ncase 'center':\nmoveX = dims.width / 2;\nmoveY = dims.height / 2;\nbreak;\n}\nreturn new Effect.Parallel(\n[ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),\nnew Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),\nnew Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })\n], Object.extend({\nbeforeStartInternal: function(effect) {\neffect.effects[0].element.makePositioned().makeClipping();\n},\nafterFinishInternal: function(effect) {\neffect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }\n}, options)\n);\n};\nEffect.Pulsate = function(element) {\nelement = $(element);\nvar options = arguments[1] || { },\noldOpacity = element.getInlineOpacity(),\ntransition = options.transition || Effect.Transitions.linear,\nreverser = function(pos){\nreturn 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5);\n};\nreturn new Effect.Opacity(element,\nObject.extend(Object.extend({ duration: 2.0, from: 0,\nafterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }\n}, options), {transition: reverser}));\n};\nEffect.Fold = function(element) {\nelement = $(element);\nvar oldStyle = {\ntop: element.style.top,\nleft: element.style.left,\nwidth: element.style.width,\nheight: element.style.height };\nelement.makeClipping();\nreturn new Effect.Scale(element, 5, Object.extend({\nscaleContent: false,\nscaleX: false,\nafterFinishInternal: function(effect) {\nnew Effect.Scale(element, 1, {\nscaleContent: false,\nscaleY: false,\nafterFinishInternal: function(effect) {\neffect.element.hide().undoClipping().setStyle(oldStyle);\n} });\n}}, arguments[1] || { }));\n};\nEffect.Morph = Class.create(Effect.Base, {\ninitialize: function(element) {\nthis.element = $(element);\nif (!this.element) throw(Effect._elementDoesNotExistError);\nvar options = Object.extend({\nstyle: { }\n}, arguments[1] || { });\nif (!Object.isString(options.style)) this.style = $H(options.style);\nelse {\nif (options.style.include(':'))\nthis.style = options.style.parseStyle();\nelse {\nthis.element.addClassName(options.style);\nthis.style = $H(this.element.getStyles());\nthis.element.removeClassName(options.style);\nvar css = this.element.getStyles();\nthis.style = this.style.reject(function(style) {\nreturn style.value == css[style.key];\n});\noptions.afterFinishInternal = function(effect) {\neffect.element.addClassName(effect.options.style);\neffect.transforms.each(function(transform) {\neffect.element.style[transform.style] = '';\n});\n};\n}\n}\nthis.start(options);\n},\nsetup: function(){\nfunction parseColor(color){\nif (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';\ncolor = color.parseColor();\nreturn $R(0,2).map(function(i){\nreturn parseInt( color.slice(i*2+1,i*2+3), 16 );\n});\n}\nthis.transforms = this.style.map(function(pair){\nvar property = pair[0], value = pair[1], unit = null;\nif (value.parseColor('#zzzzzz') != '#zzzzzz') {\nvalue = value.parseColor();\nunit = 'color';\n} else if (property == 'opacity') {\nvalue = parseFloat(value);\nif (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))\nthis.element.setStyle({zoom: 1});\n} else if (Element.CSS_LENGTH.test(value)) {\nvar components = value.match(/^([\\+\\-]?[0-9\\.]+)(.*)$/);\nvalue = parseFloat(components[1]);\nunit = (components.length == 3) ? components[2] : null;\n}\nvar originalValue = this.element.getStyle(property);\nreturn {\nstyle: property.camelize(),\noriginalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),\ntargetValue: unit=='color' ? parseColor(value) : value,\nunit: unit\n};\n}.bind(this)).reject(function(transform){\nreturn (\n(transform.originalValue == transform.targetValue) ||\n(\ntransform.unit != 'color' &&\n(isNaN(transform.originalValue) || isNaN(transform.targetValue))\n)\n);\n});\n},\nupdate: function(position) {\nvar style = { }, transform, i = this.transforms.length;\nwhile(i--)\nstyle[(transform = this.transforms[i]).style] =\ntransform.unit=='color' ? '#'+\n(Math.round(transform.originalValue[0]+\n(transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +\n(Math.round(transform.originalValue[1]+\n(transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +\n(Math.round(transform.originalValue[2]+\n(transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :\n(transform.originalValue +\n(transform.targetValue - transform.originalValue) * position).toFixed(3) +\n(transform.unit === null ? '' : transform.unit);\nthis.element.setStyle(style, true);\n}\n});\nEffect.Transform = Class.create({\ninitialize: function(tracks){\nthis.tracks = [];\nthis.options = arguments[1] || { };\nthis.addTracks(tracks);\n},\naddTracks: function(tracks){\ntracks.each(function(track){\ntrack = $H(track);\nvar data = track.values().first();\nthis.tracks.push($H({\nids: track.keys().first(),\neffect: Effect.Morph,\noptions: { style: data }\n}));\n}.bind(this));\nreturn this;\n},\nplay: function(){\nreturn new Effect.Parallel(\nthis.tracks.map(function(track){\nvar ids = track.get('ids'), effect = track.get('effect'), options = track.get('options');\nvar elements = [$(ids) || $$(ids)].flatten();\nreturn elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) });\n}).flatten(),\nthis.options\n);\n}\n});\nElement.CSS_PROPERTIES = $w(\n'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +\n'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +\n'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +\n'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +\n'fontSize fontWeight height left letterSpacing lineHeight ' +\n'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+\n'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +\n'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +\n'right textIndent top width wordSpacing zIndex');\nElement.CSS_LENGTH = /^(([\\+\\-]?[0-9\\.]+)(em|ex|px|in|cm|mm|pt|pc|\\%))|0$/;\nString.__parseStyleElement = document.createElement('div');\nString.prototype.parseStyle = function(){\nvar style, styleRules = $H();\nif (Prototype.Browser.WebKit)\nstyle = new Element('div',{style:this}).style;\nelse {\nString.__parseStyleElement.innerHTML = '<div style=\"' + this + '\"></div>';\nstyle = String.__parseStyleElement.childNodes[0].style;\n}\nElement.CSS_PROPERTIES.each(function(property){\nif (style[property]) styleRules.set(property, style[property]);\n});\nif (Prototype.Browser.IE && this.include('opacity'))\nstyleRules.set('opacity', this.match(/opacity:\\s*((?:0|1)?(?:\\.\\d*)?)/)[1]);\nreturn styleRules;\n};\nif (document.defaultView && document.defaultView.getComputedStyle) {\nElement.getStyles = function(element) {\nvar css = document.defaultView.getComputedStyle($(element), null);\nreturn Element.CSS_PROPERTIES.inject({ }, function(styles, property) {\nstyles[property] = css[property];\nreturn styles;\n});\n};\n} else {\nElement.getStyles = function(element) {\nelement = $(element);\nvar css = element.currentStyle, styles;\nstyles = Element.CSS_PROPERTIES.inject({ }, function(results, property) {\nresults[property] = css[property];\nreturn results;\n});\nif (!styles.opacity) styles.opacity = element.getOpacity();\nreturn styles;\n};\n}\nEffect.Methods = {\nmorph: function(element, style) {\nelement = $(element);\nnew Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { }));\nreturn element;\n},\nvisualEffect: function(element, effect, options) {\nelement = $(element);\nvar s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);\nnew Effect[klass](element, options);\nreturn element;\n},\nhighlight: function(element, options) {\nelement = $(element);\nnew Effect.Highlight(element, options);\nreturn element;\n}\n};\n$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+\n'pulsate shake puff squish switchOff dropOut').each(\nfunction(effect) {\nEffect.Methods[effect] = function(element, options){\nelement = $(element);\nEffect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);\nreturn element;\n};\n}\n);\n$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(\nfunction(f) { Effect.Methods[f] = Element[f]; }\n);\nElement.addMethods(Effect.Methods);\n}\nif(typeof NYTMM == 'undefined') {\nvar NYTMM = new Object();\nNYTMM.Skins = {\nDEFAULT : \"default\",\nDARK : \"dark\"\n};\nNYTMM.Browsers = {\nOPERA : \"opera\",\nFIREFOX : \"firefox\",\nIE : \"ie\",\nCHROME : \"chrome\",\nSAFARI : \"safari\"\n};\nNYTMM.Platforms = {\nIPHONE : \"iphone\",\nIPAD : \"ipad\",\nOTHER : \"other\"\n};\nNYTMM.Align = {\nTOP : \"top\",\nBOTTOM : \"bottom\",\nCENTER : \"center\",\nRIGHT : \"right\",\nLEFT : \"left\"\n};\nNYTMM.browserVersion = \"\";\nNYTMM.browser = \"\";\nif(/MSIE (\\d+\\.\\d+);/.test(navigator.userAgent)) {\nNYTMM.browser = NYTMM.Browsers.IE;\nNYTMM.browserVersion = new Number(RegExp.$1);\n}\nelse if (/Firefox[\\/\\s](\\d+\\.\\d+)/.test(navigator.userAgent)) {\nNYTMM.browser = NYTMM.Browsers.FIREFOX;\nNYTMM.browserVersion = new Number(RegExp.$1);\n}\nelse if (/Opera[\\/\\s](\\d+\\.\\d+)/.test(navigator.userAgent)) {\nNYTMM.browser = NYTMM.Browsers.OPERA;\nNYTMM.browserVersion = new Number(RegExp.$1);\n}\nelse if (/(\\d+\\.\\d+)\\.?\\d*?[\\/\\s]Safari/.test(navigator.userAgent)) {\nNYTMM.browser = NYTMM.Browsers.SAFARI;\nNYTMM.browserVersion = new Number(RegExp.$1);\n}\nNYTMM.platform = NYTMM.Platforms.OTHER;\nif(navigator.userAgent.match(/iPad/i) != null) NYTMM.platform = NYTMM.Platforms.IPAD;\nelse if(navigator.userAgent.match(/iPhone/i) != null) NYTMM.platform = NYTMM.Platforms.IPHONE;\nNYTMM.createElement = function(tag,value,cName,attrs,styles) {\nif(attrs == null) attrs = new Object();\nif(styles == null) styles = new Object();\nvar e = document.createElement(tag);\nif(cName != null && cName != \"\") e.className = cName;\nif(value != null && value != \"\" && tag != \"img\") e.innerHTML = value\nfor(a in attrs) {\ne.setAttribute(a,attrs[a]);\n}\nfor(s in styles) {\ne.style[s] = styles[s];\n}\ntry {\nElement.extend(e);\n}\ncatch(e) {\n}\nreturn e;\n};\nNYTMM.removeChildrenOf = function(e) {\ne.innerHTML = '';\nreturn e;\n};\nNYTMM.replaceChildrenOf = function(p,c) {\nNYTMM.removeChildrenOf(p);\nif(typeof(c) == \"string\") {\np.innerHTML = c;\n}\nelse if(c.length) {\nfor(var i=0; i<c.length; i++) {\np.appendChild(c[i]);\n}\n}\nelse p.appendChild(c);\nreturn p;\n};\nNYTMM.getFlashVersion = function() {\nif (typeof NYTMM.flashVersion != \"undefined\") return NYTMM.flashVersion;\nvar version = 0;\nif (typeof navigator.plugins != \"undefined\" && typeof navigator.plugins[\"Shockwave Flash\"] == \"object\") {\ndesc = navigator.plugins[\"Shockwave Flash\"].description;\nif (desc && !(typeof navigator.mimeTypes != \"undefined\" && navigator.mimeTypes[\"application/x-shockwave-flash\"] && !navigator.mimeTypes[\"application/x-shockwave-flash\"].enabledPlugin)) {\nversion = parseInt(desc.match(/^.*\\s+([^\\s]+)\\.[^\\s]+\\s+[^\\s]+$/)[1]);\n}\n}\n\t\telse if (typeof window.ActiveXObject != \"undefined\") {\ntry {\nvar testObject = new ActiveXObject(\"ShockwaveFlash.ShockwaveFlash\");\nif(testObject) version = parseInt(testObject.GetVariable(\"$version\").match(/^[^\\s]+\\s(\\d+)/)[1]);\n}\ncatch(e) {}\n}\nreturn NYTMM.flashVersion = version;\n};\nNYTMM.Icon = {\nSERVER_BASE : \"http://graphics8.nytimes.com/images/icons/multimedia/\",\nICONS : {\n\"audio\" : {url:\"audio_icon.gif\",w:13,h:12 },\n\"article\" : {url:\"article_icon.gif\",w:11,h:12 },\n\"comment\" : {url:\"comment_icon.gif\",w:9,h:11 },\n\"document\" : {url:\"document_icon.gif\",w:10,h:12 },\n\"arrowdown\" : {url:\"arrowDown.gif\",w:12,h:20 },\n\"arrowright\" : {url:\"arrowRight.gif\",w:12,h:20 },\n\"magnifier\" : {url:\"enlarge_icon.gif\",w:12,h:12 },\n\"zoomOut\" : {url:\"zoom_out_icon.gif\",w:12,h:12 },\n\"fullscreen\" : {url:\"fullscreen_icon.gif\",w:13,h:12 },\n\"graphic\" : {url:\"graphic_icon.gif\",w:11,h:12 },\n\"interactive\" : {url:\"interactive_icon.gif\",w:9,h:12 },\n\"map\" : {url:\"map_icon.gif\",w:12,h:12 },\n\"mobile\" : {url:\"mobile_icon.gif\",w:7,h:12 },\n\"photo\" : {url:\"photo_icon.gif\",w:12,h:12 },\n\"slideshow\" : {url:\"slide_show_icon.gif\",w:12,h:11 },\n\"trailer\" : {url:\"trailer_icon.gif\",w:11,h:12 },\n\"video\" : {url:\"video_icon.gif\",w:12,h:12 },\n\"print\" : {url:\"print.gif\",w:14,h:13 },\n\"hand\" : {url:\"hand.gif\",w:19,h:17 },\n\"movearrows\" : {url:\"move_arrows.png\",w:22,h:25 },\n\"plusButton\" : {url:\"plusButton.gif\",w:16,h:16 },\n\"permalink\" : {url:\"permalink.gif\",w:16,h:16 },\n\"checkmark\" : {url:\"checkmark.gif\",w:12,h:12 },\n\"intextArticle\" : {url:\"intext/icon_in_article.gif\",w:17,h:15 },\n\"intextMap\" : {url:\"intext/icon_in_map.gif\",w:17,h:15 },\n\"intextPhoto\" : {url:\"intext/icon_in_photo.gif\",w:17,h:15 },\n\"intextVideo\" : {url:\"intext/icon_in_video.gif\",w:17,h:15 },\n\"rss8\" : {url:\"rss/rss_icon_8x8.gif\",w:8,h:8 },\n\"rss10\" : {url:\"rss/rss_icon_10x10.gif\",w:10,h:10 },\n\"rss12\" : {url:\"rss/rss_icon_12x12.gif\",w:12,h:12 },\n\"rss16\" : {url:\"rss/rss_icon_16x16.gif\",w:16,h:16 }\n},\ncreate: function(type,styles) {\nvar icn = NYTMM.Icon.ICONS[type];\nreturn (icn == null) ? null : NYTMM.createElement(\"img\",\"\",\"nytmm_icon\",{src:NYTMM.Icon.SERVER_BASE+icn.url, width:icn.w, height:icn.h},styles);\n}\n};\nNYTMM.Includes = {\njs: [],\ncss: [],\nincludeJS: function(src,once) {\nif(once == null) once = true;\nif(once) {\nfor(var i=0; i<NYTMM.Includes.js.length; i++) {\nif(NYTMM.Includes.js[i] == src) return false;\n}\n}\nNYTMM.Includes.js.push(src);\ndocument.write(\"<script language=\\\"javascript\\\" type=\\\"text/javascript\\\" src=\\\"\"+src+\"\\\" ></script>\");\n},\nincludeCSS: function(src,once) {\nif(once == null) once = true;\nif(once) {\nfor(var i=0; i<NYTMM.Includes.css.length; i++) {\nif(NYTMM.Includes.css[i] == src) return false;\n}\n}\nNYTMM.Includes.css.push(src);\ndocument.write(\"<link href=\\\"\"+src+\"\\\" type=\\\"text/css\\\" rel=\\\"stylesheet\\\" />\");\n}\n};\n}\nif(typeof NYTMM != 'undefined' && typeof NYTMM.Sequence == 'undefined') {\nNYTMM.Sequence = Class.create({\ninitialize: function(length,index) {\nthis.increment = 1;\nthis.decrement = 1;\nthis.wrap = false;\nthis.length = (length == null) ? 0 : length;\nthis.index = (index == null) ? ((length == 0) ? -1 : 0) : (index >= length) ? length-1 : index;\nthis.synced = [];\n},\nsetLength: function(i) {\nthis.length = i;\nthis.setIndex(this.index);\n},\ngetLength: function() {\nreturn this.length;\n},\n\t\tsetIndex: function(i) {\nif(this.length <= 0) {\nthis.index = -1;\nreturn;\n}\nif(i < 0) i = (this.wrap) ? this.length - (i%this.length) : 0;\nelse if(i >= this.length) i = (this.wrap) ? (i%this.length) : this.length-1;\nthis.index = i;\nfor(var j=0; j<this.synced.length; j++) {\nvar s = this.synced[j];\nif(s.getIndex() != this.index) s.setIndex(this.index);\n}\n},\ngetIndex: function() {\nreturn this.index;\n},\nnext: function() {\nthis.setIndex(this.index+this.increment);\n},\nprev: function () {\nthis.setIndex(this.index-this.decrement);\n},\nsync: function(s,bothWays) {\nif(s instanceof NYTMM.Sequence && s != this) {\nthis.synced.push(s);\nif(bothWays) s.sync(this);\nreturn true;\n}\nreturn false;\n},\nunsync: function(s,bothWays) {\nfor(var i=0; i<this.synced.length; i++) {\nif(this.synced[i] == s) {\nthis.synced.splice(i,1);\nif(bothWays) s.unsync(this);\nreturn true;\n}\n}\nreturn false;\n}\n});\n}\nif(typeof NYTMM != 'undefined' && typeof NYTMM.FadingSlides == 'undefined') {\nNYTMM.FadingSlides = Class.create(NYTMM.Sequence, {\ninitialize: function($super,parent,width,height,opts) {\n$super();\nopts = opts || { };\nthis.parent = parent;\nthis.layout;\nthis.container;\nthis.credit;\nthis.transitionTime = (opts.transitionTime == null) ? 1 : opts.transitionTime;\nthis.delay = (opts.delay == null) ? 4 : opts.delay;\nthis.itemHAlign = (opts.itemHAlign == null) ? NYTMM.Align.CENTER : opts.itemHAlign;\nthis.itemVAlign = (opts.itemVAlign == null) ? NYTMM.Align.CENTER : opts.itemVAlign;\nthis.playLength = (opts.playLength == null) ? 0 : opts.playLength;\nthis.wrap = true;\nthis.width = width;\nthis.height = height;\nthis.items = [];\nthis.slides = [];\nthis.zIndex = 0;\nthis.playing = false;\nthis.numPlayed = 0;\nthis.layout = NYTMM.createElement(\"div\",\"\",\"nytmm_fadingSlides\",null,{width:this.width+\"px\"});\nthis.parent.appendChild(this.layout);\nthis.container = NYTMM.createElement(\"div\",\"\",\"nytmm_fadingSlides_container\",null,{width:this.width+\"px\",height:this.height+\"px\"});\nthis.layout.appendChild(this.container);\n},\nsetItems: function(its) {\nfor(var i=0; i<its.length; i++) {\nif(!its[i] instanceof Element) return;\n}\nthis.numPlayed = 0;\nthis.slides = [];\nNYTMM.removeChildrenOf(this.container);\nthis.items = its.slice(0);\nthis.length = this.items.length;\nthis.index = (this.items.length == 0) ? -1 : 0;\nif(this.items.length == 0) return;\nfor(i=0; i<this.items.length; i++) {\nvar s = NYTMM.createElement(\"div\",\"\",\"nytmm_fadingSlides_slide\");\ns.appendChild(this.items[i]);\nthis.slides.push(this.container.appendChild(s));\nthis.updateSlideAt(i);\nElement.hide(s);\n}\nthis.setIndex(0);\n},\nupdateSlideAt: function(i) {\nvar s = $(this.slides[i]);\nif(!s || !s.style) return;\nvar wasHidden = false;\nif(s.style.display == \"none\") {\nwasHidden = true;\nElement.show(s);\n}\nvar d = Element.getDimensions(s);\nif(this.itemVAlign == NYTMM.Align.CENTER) s.style.top = Math.round((this.height - d.height)/2) + \"px\";\nelse if(this.itemVAlign == NYTMM.Align.ALIGN) s.style.bottom = \"0px\";\nelse {\ns.style.top = \"0px\";\ns.style.bottom = \"auto\";\n}\nif(this.itemHAlign == NYTMM.Align.CENTER) s.style.left = Math.round((this.width - d.width)/2) + \"px\";\nelse if(this.itemHAlign == NYTMM.Align.RIGHT) s.style.right = \"0px\";\nelse {\ns.style.left = \"0px\";\ns.style.right = \"auto\";\n}\nif(wasHidden) Element.hide(s);\n},\nplay: function() {\nif(this.playing) return;\nthis.playing = true;\nthis.setIndex(0);\nthis.playTimeout = setInterval(this.onPlayTimeout.bind(this), this.delay * 1000);\n},\npause: function() {\nthis.playing = false;\nclearInterval(this.playTimeout);\n},\nsetIndex: function($super,i) {\nvar oldIndex = this.index;\n$super(i);\nif(this.length <= 0) return;\nif(oldIndex >= 0 && oldIndex != this.index) {\nthis.slides[oldIndex].fade({duration:this.transitionTime});\n}\nvar s = this.slides[this.index];\ns.style.zIndex = (++this.zIndex);\nElement.hide(s);\nnew Effect.Appear(s,{duration:this.transitionTime});\n},\nonPlayTimeout: function() {\nthis.numPlayed++;\ndocument.fire(NYTMM.FadingSlides.CHANGE_EVENT,{target:this});\nif(this.playLength <= 0 || this.numPlayed < this.playLength) this.next();\nif(this.playLength > 0 && this.numPlayed >= this.playLength-1) this.onPlayComplete();\n},\nonPlayComplete: function() {\nthis.pause();\ndocument.fire(NYTMM.FadingSlides.END_EVENT,{target:this});\n}\n})\nNYTMM.FadingSlides.CHANGE_EVENT = \"NYTMM.FadingSlides:change\";\nNYTMM.FadingSlides.END_EVENT = \"NYTMM.FadingSlides:end\";\n}\nif(typeof NYTMM != 'undefined' && typeof NYTMM.FadingSlideShow == 'undefined') {\nNYTMM.FadingSlideShow = Class.create(NYTMM.Sequence, {\ninitialize: function($super,parent,width,height,opts) {\n$super();\nopts = opts || { };\nthis.parent = parent;\nthis.layout;\nthis.gallery;\nthis.credit;\nthis.endOverlay;\nthis.width = width;\nthis.height = height;\nthis.link = (opts.link == null) ? \"\" : opts.link;\nthis.linkTarget = (opts.linkTarget == null) ? \"_self\" : opts.linkTarget;\nthis.kicker = (opts.kicker == null) ? \"\" : opts.kicker;\nthis.randomize = (opts.randomize == null) ? false : opts.randomize;\nthis.endText = (opts.endText == null) ? \"\" : opts.endText;\nthis.wrap = true;\nthis.photos = [];\nthis.slides = [];\nthis.images = [];\nthis.hasCredit = false;\nthis.creditTimeout;\nthis.layout = NYTMM.createElement(\"div\",\"\",\"nytmm_fadingSlideShow\",null,{width:this.width+\"px\"});\nthis.parent.appendChild(this.layout);\nthis.gallery = new NYTMM.FadingSlides(this.layout,this.width,this.height,opts);\nthis.gallery.sync(this);\nthis.sync(this.gallery);\ndocument.observe(NYTMM.FadingSlides.END_EVENT,this.onGalleryEnd.bind(this));\nthis.credit = NYTMM.createElement(\"div\",\"\",\"nytmm_photoCredit\",null);\nthis.layout.appendChild(this.credit);\n},\nshowCredits: function() {\nElement.show(this.credit);\n},\nhideCredits: function() {\nElement.hide(this.credit);\n},\nsetPhotoData: function(ps) {\nthis.photos = (this.randomize) ? ps.slice(0).sort(function() {return 0.5 - Math.random();}) : ps.slice(0);\nthis.images = [];\nthis.slides = [];\nthis.length = this.photos.length;\nthis.index = (this.photos.length == 0) ? -1 : 0;\nthis.hasCredit = false;\nif(this.endOverlay) this.endOverlay.hide();\nNYTMM.removeChildrenOf(this.credit);\nfor(var i=0; i<this.photos.length; i++) {\nvar p = this.photos[i];\nif(typeof p == \"string\") this.photos[i] = p = {url:p};\nif(p.credit != null && p.credit != \"\") this.hasCredit = true;\nif(p.link == null || p.link == \"\") p.link = this.link;\nif(p.linkTarget == null || p.linkTarget == \"\") p.linkTarget = this.linkTarget;\nif(p.kicker == null || p.kicker == \"\") p.kicker = this.kicker;\nvar slide = NYTMM.createElement(\"div\",\"\",\"nytmm_fadingSlideShow_slide\",null,{zIndex:0,display:'none'});\nvar img = NYTMM.createElement(\"img\");\nEvent.observe(img, 'load', this.onImageLoad.bind(this,i));\nif(p.link != null && p.link != \"\") {\nvar a = NYTMM.createElement(\"a\");\na.href = p.link;\na.target = (p.linkTarget == \"_blank\") ? p.linkTarget : \"_self\";\na.appendChild(img);\nslide.appendChild(a);\n}\nelse slide.appendChild(img);\nif(p.kicker != null && p.kicker != \"\") {\nvar kicker = NYTMM.createElement(\"div\",p.kicker,\"nytmm_photoKicker\");\nslide.appendChild(kicker);\n}\nthis.images.push(img);\nthis.slides.push(slide);\n}\nif(this.images.length > 0) this.images[0].src = this.photos[0].url;\nthis.credit.style.height = (this.hasCredit) ? \"14px\" : \"auto\";\nthis.gallery.setItems(this.slides);\nthis.setIndex(0);\n},\nonImageLoad: function(i) {\nvar img = this.images[i];\nvar slide = this.slides[i];\nvar wasHidden = false;\nslide.style.display = 'block';\nif(this.gallery.slides[i] && this.gallery.slides[i].style.display == \"none\") {\nwasHidden = true;\nElement.show(this.gallery.slides[i]);\n}\nvar ir = img.width/img.height;\nvar r = this.width/this.height;\nvar h = img.height;\nvar w = img.width;\nif(img.width > this.width && ir >= r) {\nh = Math.round(img.height*(this.width/img.width));\nw = this.width;\n}\nelse if(img.height > this.height && ir < r) {\nw = Math.round(img.width*(this.height/img.height));\nh = this.height;\n}\nimg.width = w;\nimg.height = h;\nimg.style.height = slide.style.height = h + \"px\";\nimg.style.width = slide.style.width = w + \"px\";\nif(wasHidden) Element.hide(this.gallery.slides[i]);\nthis.gallery.updateSlideAt(i);\nif(i < this.images.length-1) this.images[i+1].src = this.photos[i+1].url;\nif(i == 0) this.gallery.play();\n},\nsetIndex: function($super,i) {\n$super(i);\nclearTimeout(this.creditTimeout);\nif(this.gallery.transitionTime > 0) this.creditTimeout = setTimeout(this.updateCredit.bind(this),this.gallery.transitionTime*500);\nelse this.updateCredit();\n},\nupdateCredit: function() {\nNYTMM.removeChildrenOf(this.credit);\nif(this.length <= 0) return;\nvar p = this.photos[this.index];\nif(typeof p == \"object\") this.credit.appendChild(document.createTextNode((p.credit == \"\" || p.credit == null) ? \"\\u00a0\" : p.credit));\n},\nonGalleryEnd: function(e) {\nif(e.memo.target != this.gallery) return;\nif(this.endText != null && this.endText != \"\") {\nif(this.endOverlay == null) {\nthis.endOverlay = NYTMM.createElement(\"div\",\"\",\"nytmm_fadingSlideShow_endOverlay\");\nthis.endOverlay.appendChild(NYTMM.createElement(\"div\",\"\"));\nthis.layout.appendChild(this.endOverlay);\n}\nthis.endOverlay.style.bottom = (this.layout.getHeight() - this.height) + \"px\";\nthis.endOverlay.style.width = this.width + \"px\";\nthis.endOverlay.firstChild.innerHTML = this.endText;\nthis.endOverlay.hide();\nnew Effect.Appear(this.endOverlay,{duration:this.gallery.transitionTime,delay:this.gallery.transitionTime});\n}\n}\n})\n}" }, { "alpha_fraction": 0.4823908805847168, "alphanum_fraction": 0.5558035969734192, "avg_line_length": 42.826087951660156, "blob_id": "3ec45c92f54f28b2485773b87cab0a12a984e56c", "content_id": "c8bfece0ef22b3e19904ea07589c22d75639888d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4032, "license_type": "permissive", "max_line_length": 241, "num_lines": 92, "path": "/client/demo-waf/waf/waf_traffic.py", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport requests\nimport json\nimport getopt\nimport sys\nimport time\nimport random\nfrom random import randint\nimport uuid\nimport urllib, urllib2, cookielib\nimport random\nfrom requests_toolbelt.adapters import source\nimport traceback\nfrom datetime import datetime\n\nwhile True:\n try:\n # Login Defaults\n dvwa_username = \"admin\"\n dvwa_password = \"password\"\n vip = \"waf.demovip.avi.local\"\n #vip = \"waf-demo.avi.local\"\n IP_ADDR = [\"161.98.255.1\", \"37.60.63.2\", \"206.223.191.1\", \"23.26.110.2\", \"27.113.239.2\", \"42.97.255.1\", \"132.247.255.2\", \"14.192.95.1\", \"37.16.63.1\", \"49.213.31.2\", \"41.67.128.1\", \"27.97.1.2\"]\n\n dvwa_login_url = \"http://\"+vip+\"/login.php\"\n\n url1 = \"http://\"+vip+\"/index.php\"\n #url2 = \"http://\"+vip+\"/\"\n url3 = \"http://\"+vip+\"/about.php\"\n url4 = \"http://\"+vip+\"/security.php\"\n url5 = \"http://\"+vip+\"/vulnerabilities/exec/\"\n url6 = \"http://\"+vip+\"/instructions.php\"\n url7 = \"http://\"+vip+\"/vulnerabilities/sqli/\"\n\n url = [url1, url3, url4, url6]\n attack_url = [url5, url7]\n ##Add requests.get(https://url, verify=False) to avoid SSLv3.\n\n ua1 = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36\"\n ua2 = \"Mozilla/5.0 (iPhone; CPU iPhone OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B206 Safari/7534.48.3\"\n ua3 = \"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0\"\n ua4 = \"Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko\"\n ua5 = \"Mozilla/5.0(iPad; U; CPU OS 4_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8F191 Safari/6533.18.5\"\n\n ua = [ua1, ua2, ua3, ua4, ua5]\n #def boo():\n r = requests.get(dvwa_login_url, auth=(dvwa_username, dvwa_password))\n dvwa_cookie = r.cookies\n\n\n print (\"DVWA Cookie\")\n print dvwa_cookie\n\n print (\"DVWA Header\")\n print r.headers\n\n counter = 0\n #r1.headers = {url1, 'user-agent': ua1, ''}\n while True:\n print '-----> STARTING NEW LOOP'\n # Attack Only traffic\n if counter >= 100:\n s1 = requests.Session()\n ip1 = source.SourceAddressAdapter(random.choice(IP_ADDR))\n s1.mount(\"http://\", ip1)\n s1.mount(\"https://\", ip1)\n cur_url = random.choice(attack_url)\n if cur_url == url5:\n r1 = s1.post(cur_url, headers={'user-agent': random.choice(ua)}, cookies=dvwa_cookie, data={\"ip\": \"ping 127.0.0.1 & cat /etc/passwd\", \"Submit\": \"Submit\"} )\n if r1.status_code == 200:\n print (\"Command execution detected\")\n elif r1.status_code == 403:\n print (\"Command execution attack blocked by WAF\")\n elif cur_url == url7:\n r1 = s1.post(cur_url, headers={'user-agent': random.choice(ua)}, cookies=dvwa_cookie, data={\"id\": \"%' and 1=0 union select null, concat(first_name,0x0a,last_name,0x0a,user,0x0a,password) from users #\",\"Submit\": \"Submit\"})\n if r1.status_code == 200:\n print (\"SQL injection detected\")\n elif r1.status_code == 403:\n print (\"SQL injection attack blocked by WAF\")\n counter = 0\n else:\n s1 = requests.Session()\n ip1 = source.SourceAddressAdapter(random.choice(IP_ADDR))\n s1.mount(\"http://\", ip1)\n s1.mount(\"https://\", ip1)\n r1 = s1.get(random.choice(url), headers={'user-agent': random.choice(ua)}, cookies=dvwa_cookie)\n counter+=1\n except:\n exception_text = traceback.format_exc()\n print(str(datetime.now())+' '+exception_text)\n print 'ERROR - restarting'\n" }, { "alpha_fraction": 0.42411038279533386, "alphanum_fraction": 0.45177921652793884, "avg_line_length": 28.615053176879883, "blob_id": "fc0305b47bf7c8bdda0bf1f9d42820bc64870db3", "content_id": "85cfa9202f33029e7c0a1f02367feabe8f06eff6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 13770, "license_type": "permissive", "max_line_length": 172, "num_lines": 465, "path": "/servers/demo-scaleout/html/boston.tmp/bcom-dfp.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "(function( bcom ){\n\n var bcom = bcom || {};\n bcom.dfp = bcom.dfp || {};\n\n // Setup Ad Catalog\n bcom.dfp.adCatalog = [\n {\n name: 'ad_lead1',\n size: [[728, 90]],\n position: 'atf'\n },\n {\n name: 'ad_bigbox1',\n size: [[300, 250], [300, 600], [300, 1050]],\n position: 'atf'\n },\n {\n name: 'ad_bigbox2',\n size: [[300, 250], [300, 600], [300, 1050]],\n position: 'btf'\n },\n {\n name: 'ad_bigbox3',\n size: [[300, 250]],\n position: ['btf', 'bigbox3']\n }, \n {\n name: 'ad_bigbox4',\n size: [[300, 250]],\n position: ['btf', 'bigbox4']\n },\n {\n name: 'ad_billboard',\n size: [[959, 30], [959, 300]],\n position: 'atf'\n },\n {\n name: 'ad_sky',\n size: [[160, 600]],\n position: 'atf'\n },\n {\n name: 'ad_featurebox',\n size: [[180, 150], [185, 85]],\n position: 'atf'\n },\n {\n name: 'ad_lead2',\n size: [[728, 90]],\n position: 'btf'\n },\n {\n name: 'ad_sponsor',\n size: [[88, 31], [100, 40]],\n position: 'sponsor'\n },\n {\n name: 'ad_adsense',\n size: [[609, 222]],\n position: 'btf'\n },\n {\n name: 'ad_headline1',\n size: [[234, 60]],\n position: 'atf'\n },\n {\n name: 'ad_headline2',\n size: [[234, 60]],\n position: 'btf'\n },\n {\n name: 'ad_header',\n size: [[539, 30]],\n position: 'atf'\n },\n {\n name: 'ad_native',\n size: [[5, 5]],\n position: 'native'\n },\n {\n name: 'ad_highlight',\n size: [[110, 70]],\n position: 'atf'\n },\n {\n name: 'ad_wallpaper',\n size: [[1, 1]],\n position: ['wallpaper', 'atf']\n },\n {\n name: 'ad_text1',\n size: [[2, 2]],\n position: 'text1'\n },\n {\n name: 'ad_text2',\n size: [[2, 2]],\n position: 'text2'\n },\n {\n name: 'ad_text3',\n size: [[2, 2]],\n position: 'text3'\n },\n {\n name: 'ad_topleft',\n size: [[274, 105]],\n position: 'topleft'\n },\n {\n name: 'ad_topright',\n size: [[275, 105]],\n position: 'topright'\n },\n {\n name: 'ad_topbox',\n size: [[300, 142]],\n position: 'topbox'\n },\n {\n name: 'ad_botbox',\n size: [[300, 142]],\n position: 'botbox'\n },\n {\n name: 'ad_midleftbox',\n size: [[300, 142]],\n position: 'midleftbox'\n },\n {\n name: 'ad_midrightbox',\n size: [[300, 42]],\n position: 'midrightbox'\n },\n {\n name: 'ad_topleftmini',\n size: [[148, 87]],\n position: 'topleftmini'\n },\n {\n name: 'ad_toprightmini',\n size: [[148, 87]],\n position: 'toprightmini'\n },\n {\n name: 'ad_botleftmini',\n size: [[148, 87]],\n position: 'botleftmini'\n },\n {\n name: 'ad_botrightmini',\n size: [[148, 87]],\n position: 'botrightmini'\n },\n {\n name: 'ad_tile',\n size: [[175, 342]],\n position: 'tile'\n },\n {\n name: 'ad_showcase',\n size: [400, 375],\n position: 'showcase'\n },\n {\n name: 'ad_featurepartner1',\n size: [189, 120],\n position: 'featurepartner1'\n },\n {\n name: 'ad_featurepartner2',\n size: [[189, 120]],\n position: 'featurepartner2'\n },\n {\n name: 'ad_featurepartner3',\n size: [[189, 120]],\n position: 'featurepartner3'\n },\n {\n name: 'ad_featurebox1',\n size: [[306, 205]],\n position: 'featurebox1'\n },\n {\n name: 'ad_featurebox2',\n size: [[306, 205]],\n position: 'featurebox2'\n },\n {\n name: 'ad_featurebox3',\n size: [[306, 205]],\n position: 'featurebox3'\n },\n {\n name: 'ad_featurebox4',\n size: [[306, 205]],\n position: 'featurebox4'\n },\n {\n name: 'ad_featurebox5',\n size: [[306, 205]],\n position: 'featurebox5'\n },\n {\n name: 'ad_featurebox6',\n size: [[306, 205]],\n position: 'featurebox6'\n },\n {\n name: 'ad_spotlight1',\n size: [[460, 150]],\n position: 'spotlight1'\n },\n {\n name: 'ad_spotlight2',\n size: [[460, 150]],\n position: 'spotlight2'\n },\n {\n name: 'ad_spotlight3',\n size: [[460, 150]],\n position: 'spotlight3'\n },\n {\n name: 'ad_spotlight4',\n size: [[460, 150]],\n position: 'spotlight4'\n }\n ];\n\n bcom.dfp.outOfPageAds = [\n {\n name: 'ad_outofpage',\n position: ['outofpage', 'atf']\n }\n ];\n\n // Ad Setup\n var networkCode = bcom.dfp.networkCode;\n var numberOfAds = bcom.dfp.adCatalog.length;\n var numberOfOOPAds = bcom.dfp.outOfPageAds.length;\n var adUnit = bcom.dfp.adUnit;\n var adSlots = bcom.dfp.adSlots;\n\n // Strip www. from adUnit / This feels wrong\n var www = adUnit.indexOf('www.');\n if ( www === 0 ) { adUnit = adUnit.replace('www.', ''); }\n\n // Loop through ad catalog\n for ( var i = 0; i < numberOfAds; i++ ) {\n var thisAd = bcom.dfp.adCatalog[i];\n if ( $.inArray(thisAd.name, adSlots) >= 0 ) {\n googletag.cmd.push(function() {\n // ad_bigbox1 & ad_lead1 might be companion ads, act accordingly ***\n if ( thisAd.name === 'ad_lead1' || thisAd.name === 'ad_bigbox1' ) {\n googletag.defineSlot('/' + networkCode + '/' + adUnit, thisAd.size, thisAd.name)\n .addService(googletag.companionAds())\n .addService(googletag.pubads())\n .setTargeting(\"pos\", thisAd.position);\n } else {\n googletag.defineSlot('/' + networkCode + '/' + adUnit, thisAd.size, thisAd.name)\n .addService(googletag.pubads())\n .setTargeting(\"pos\", thisAd.position);\n }\n });\n }\n }\n\n // Loop through out of page ads\n for ( var i = 0; i < numberOfOOPAds; i++ ) {\n var thisAd = bcom.dfp.outOfPageAds[i];\n if ( $.inArray(thisAd.name, adSlots) >= 0 ) {\n googletag.cmd.push(function() {\n googletag.defineOutOfPageSlot('/' + networkCode + '/' + adUnit, thisAd.name)\n .addService(googletag.pubads())\n .setTargeting(\"pos\", thisAd.position);\n });\n }\n }\n\n // Check pathAuth cookie for login status\n var pathAuth = getCookie('pathAuth');\n if ( pathAuth ) {\n bcom.dfp.keyValuePairs.logstat = 'y';\n } else {\n bcom.dfp.keyValuePairs.logstat = 'n';\n }\n\n // Check the RDB cookie to add some more key/value pairs\n checkCookie();\n\n // Grab the weather info\n $.ajax({\n type: 'GET',\n url: 'http://weather.boston.com/api/current/bos?callback=?',\n async: false,\n dataType: \"json\",\n }).done(function( data ) {\n bcom.dfp.keyValuePairs.weather = data.weather;\n bcom.dfp.keyValuePairs.temp = data.tempf;\n }).fail(function( jqXHR, textStatus, errorThrown ) {\n bcom.dfp.keyValuePairs.weather = '';\n bcom.dfp.keyValuePairs.temp = '';\n });\n\n // Store value of test query string\n bcom.dfp.keyValuePairs.test = getQueryStringValue('test');\n\n // Check search query string\n var isSearchQuery = getQueryStringValue('q');\n bcom.dfp.keyValuePairs.search = isSearchQuery ? isSearchQuery : '';\n\n // Loop through key/value pairs to set targeting\n var kvPairs = bcom.dfp.keyValuePairs;\n for ( var key in kvPairs ) {\n googletag.cmd.push(function() {\n googletag.pubads().setTargeting( key, kvPairs[key] );\n });\n }\n\n // Set Location\n if ( bcom.dfp.keyValuePairs.zip ) {\n googletag.cmd.push(function() {\n googletag.pubads().setLocation( bcom.dfp.keyValuePairs.zip + ',US' );\n });\n }\n\n // Finish setup\n googletag.cmd.push(function() {\n googletag.pubads().enableSingleRequest();\n googletag.companionAds().setRefreshUnfilledSlots(true);\n googletag.pubads().enableSyncRendering();\n googletag.enableServices();\n });\n\n /*\n Read RDB cookie and add appropriate values to globe.OAS.keyValuePairs\n Dummy cookie is set on doc ready for testing purposes\n Maybe clean this code up at some point?\n */\n // Functions that either get or set a cookie\n // Checks for the presence of the RDB cookie\n function checkCookie() {\n var rdb = getCookie('RDB');\n if (rdb != null && rdb != '') {\n //if the cookie exists hit up the cookieParser to get our data\n cookieParser(rdb);\n } else {\n return false;\n }\n }\n function getCookie(c_name) {\n var i, x, y, ARRcookies = document.cookie.split(\";\");\n for (i = 0; i < ARRcookies.length; i++) {\n x = ARRcookies[i].substr(0, ARRcookies[i].indexOf(\"=\"));\n y = ARRcookies[i].substr(ARRcookies[i].indexOf(\"=\") + 1);\n x = x.replace(/^\\s+|\\s+$/g, \"\");\n if (x == c_name) {\n return unescape(y);\n }\n }\n }\n // A more complex hex to ascii translation - useful in a number of places especially when you need letters back\n function translator(hex) {\n var arr = hex.match(/../g);\n var response = '';\n for (i = 0; i < arr.length; i++) {\n var m = parseInt(arr[i], 16);\n var t = String.fromCharCode(m);\n response = response + t;\n }\n return response;\n }\n // Generic Decimal to Hex Conversion\n function d2h(d) {\n return d.toString(16);\n }\n // Generic Hex to Decimal Conversion\n function h2d(h) {\n return parseInt(h, 16);\n }\n // Specific functions for messing with the cookie input to readable output\n // Specific function to check the zip code. If the zip has less than 4 characters than we need add a '0' as the cause for this issue is that the leading '0' is dropped.\n function zip5checker(hex) {\n var z = parseInt(hex, 16).toString();\n if (z.length > 4) {\n return z;\n } else {\n return '0' + z;\n }\n }\n // Like your pet turtle - this flips the hex over and checks for gender\n function genderChecker(hex) {\n var response = '';\n switch (hex) {\n case '01':\n response = 'm';\n break;\n case '02':\n response = 'f;';\n break;\n default:\n response = '';\n break;\n }\n return response;\n }\n function age(low, high) {\n var age, date, curYear, l, h, range;\n date = new Date();\n curYear = date.getFullYear();\n l = (curYear - h2d(low) + 1);\n h = (curYear - h2d(high) - 1);\n if (l == h) {\n return range = curYear - l;\n } else {\n range = curYear - l;\n range += '-';\n range += curYear - h;\n return range;\n }\n }\n function toUnicode(theString) {\n var unicodeString = '';\n var theUnicode = theString;\n while (theUnicode.length < 4) {\n theUnicode = '0' + theUnicode;\n }\n theUnicode = '\\\\x' + theUnicode;\n unicodeString += theUnicode;\n return unicodeString;\n }\n function cookieParser(cookie) {\n // obj container for freeback to Lotame\n var obj = new Object;\n obj = {\n zip5: zip5checker(cookie.substring(4, 10)),\n gender: genderChecker(cookie.substring(48, 50)),\n age: age(cookie.substring(56, 58), cookie.substring(58, 60)),\n };\n //this checks to make sure we don't have an empty object and then dispatches the info out to lotame.\n if (!$.isEmptyObject(obj)) {\n bcom.dfp.keyValuePairs.age = obj.age;\n bcom.dfp.keyValuePairs.zip = obj.zip5;\n bcom.dfp.keyValuePairs.g = obj.gender;\n };\n return obj;\n }\n // Parse query string values\n function getQueryStringValue( key ) {\n var queryStringArray = window.location.search.substr( 1 ).split( '&' );\n for ( var i = 0; i < queryStringArray.length; i++ ) {\n var keyValueArray = queryStringArray[i].split( '=' );\n if ( keyValueArray[0] === key ) {\n return keyValueArray[1];\n }\n }\n return false;\n }\n\n})( bcom );" }, { "alpha_fraction": 0.49800798296928406, "alphanum_fraction": 0.6533864736557007, "avg_line_length": 26.88888931274414, "blob_id": "229b0e9db6de5aab3eaa453253ee0dcff137e29b", "content_id": "51f1b7d1b68839a5b008c678cf4873ba7f358f74", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 251, "license_type": "permissive", "max_line_length": 116, "num_lines": 9, "path": "/servers/demo-scaleout/html/nyc-3/st.php", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "var DL = DL || {};\nDL.placement_site = '104972697';\nDL.placement_code = '56503792';\n(function(){\nif(1!=4){\nvar i=new Image();\ni.src=\"//amch.questionmarket.com/adsc/d1092641/6/56503792/adscout.php?ord=\"+Math.floor((new Date()).getTime()/1000);\n}\n})();\n" }, { "alpha_fraction": 0.6099815368652344, "alphanum_fraction": 0.6247689723968506, "avg_line_length": 65.875, "blob_id": "8994e7dcbf63172be6396ffa60ac6b803d819516", "content_id": "eb70b8b28f617f00b1e11fae30cd66c9019b63e1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 541, "license_type": "permissive", "max_line_length": 112, "num_lines": 8, "path": "/servers/demo-scaleout/html/nyc-5/ako", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "function rsi_img(p,u,c){if(u.indexOf(location.protocol)==0){var i=new Image(2,3);if(c){i.onload=c;}\r\ni.src=u;p[p.length]=i;}}\r\nfunction rsi_simg(p,s,i){if(i<s.length){rsi_img(p,s[i],function(){rsi_simg(p,s,i+1);});}}\r\nfunction rsi_req_pix(l,s){var w=window;if(typeof(w.rsi_imgs)==\"undefined\"){w.rsi_imgs=[];}\r\nif(typeof(w.rsi_simgs)==\"undefined\"){w.rsi_simgs=[];}\r\nvar a=w.rsi_imgs;var b=w.rsi_simgs;var i;for(i=0;i<l.length;++i){if(s){b[b.length]=l[i];}else{rsi_img(a,l[i]);}}\r\nif(s){rsi_simg(a,b,0);}}\r\nrsi_req_pix([],0);rsi_req_pix([],1);" }, { "alpha_fraction": 0.5030084252357483, "alphanum_fraction": 0.5192539095878601, "avg_line_length": 39.53658676147461, "blob_id": "f1fd235262b65c774b9773fb718a8d5d11a0d0aa", "content_id": "8c58f88c7e58f08305c6f79e162b417ec7d588f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1662, "license_type": "permissive", "max_line_length": 124, "num_lines": 41, "path": "/servers/demo-scaleout/html/nyc-5/autosuggestConfig.js", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "/* $Id: autosuggestConfig.js 114437 2012-10-25 14:12:04Z benjamin.morss $\n (c) 2012 The New York Times Company\n*/\n\nvar NYTD = NYTD || {};\nNYTD.Search = NYTD.Search || {};\n\n// Configure to show company ticker symbol, then the full name of the company, with matching text in bold in both\nNYTD.Search.Config = {\n SearchBoxes: {\n autosuggest: {\n DOMselector: \".inlineSearchControl\",\n resultsNode: [1], //node in the response that holds results\n serviceLocation: \"/svc/suggest/v1/travel\",\n nameOfQueryCall: \"query=\",\n minimumCharSearch: 2, //minuimum number of characters to search on (optional)\n dataType: \"json\",\n getMethod: \"get\",\n suggestedItemTemplate: function(key, val, boldedJson) {\n var data = NYTD.jQuery.parseJSON(val);\n var boldedData = NYTD.jQuery.parseJSON(boldedJson);\n var url = 'http://query.nytimes.com/search/sitesearch/?vertical=travel/#/' + encodeURIComponent(data.topic);\n return [\n '<li class=\"clearfix\">',\n '<a href=\"', url, '\">', boldedData.topic, '</a>',\n '</li>'].join('');\n },\n\n submitCallback: function() {\n var $selectedItem = NYTD.jQuery(this).find(\"li.selectedItem\");\n if ($selectedItem.length) {\n var href = $selectedItem.find(\"a\").attr('href');\n if (href) {\n window.location.href = href;\n return false;\n }\n }\n }\n }\n }\n};\n" }, { "alpha_fraction": 0.7307692170143127, "alphanum_fraction": 0.7846153974533081, "avg_line_length": 53.16666793823242, "blob_id": "92e0abd0809f67d98fc440ac740e8a9cedfb8345", "content_id": "83f43bb506b2aed807679b76a94f1aa280a2296d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 650, "license_type": "permissive", "max_line_length": 57, "num_lines": 12, "path": "/servers/demo-scaleout/html/natgeo.old/images/wget.files", "repo_name": "avinetworks/avi-corp-demo", "src_encoding": "UTF-8", "text": "#!/bin/bash\nwget static.ak.fbcdn.net/rsrc.php/v2/yq/r/IE9JII6Z1Ys.png\nwget static.ak.fbcdn.net/rsrc.php/v2/yq/r/IE9JII6Z1Ys.png\nwget static.ak.fbcdn.net/rsrc.php/v2/yq/r/IE9JII6Z1Ys.png\nwget static.ak.fbcdn.net/rsrc.php/v2/ye/r/8YeTNIlTZjm.png\nwget static.ak.fbcdn.net/rsrc.php/v2/ye/r/8YeTNIlTZjm.png\nwget static.ak.fbcdn.net/rsrc.php/v2/ye/r/8YeTNIlTZjm.png\nwget static.ak.fbcdn.net/rsrc.php/v2/ye/r/8YeTNIlTZjm.png\nwget static.ak.fbcdn.net/rsrc.php/v2/yd/r/Cou7n-nqK52.gif\nwget static.ak.fbcdn.net/rsrc.php/v2/ya/r/3rhSv5V8j3o.gif\nwget static.ak.fbcdn.net/rsrc.php/v2/y9/r/jKEcVPZFk-2.gif\nwget static.ak.fbcdn.net/rsrc.php/v2/y9/r/jKEcVPZFk-2.gif\n" } ]
62
hoogland/AdventOfCode2018
https://github.com/hoogland/AdventOfCode2018
fc14f89c6a5f311ca96d657b2f89f61800dd915d
b0db893e43bdafc8277260a351c3a1eab9f4ca9b
c178ee197ac3c3211600d43a56418f8f0924582b
refs/heads/master
2020-04-09T02:04:28.215425
2018-12-02T08:15:31
2018-12-02T08:15:31
159,927,638
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6038696765899658, "alphanum_fraction": 0.6191446185112, "avg_line_length": 28.787878036499023, "blob_id": "9579a0f65b4a5268924979366b837525ae34d0f7", "content_id": "08657b6a41dff97e9c7f05812e3a3348beb715e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 982, "license_type": "no_license", "max_line_length": 119, "num_lines": 33, "path": "/day2.py", "repo_name": "hoogland/AdventOfCode2018", "src_encoding": "UTF-8", "text": "filename = \"resources/day2.txt\"\n\nboxes = [str(x).rstrip() for x in open(filename).readlines()]\n\ndef check_freq(str):\n freq = {}\n for c in str:\n freq[c] = str.count(c)\n return freq\n\n#star 1 solution\ntwoOccurance = 0\nthreeOccurance = 0\nfor box in boxes:\n frequencies = check_freq(box)\n if 2 in frequencies.values():\n twoOccurance += 1\n threeOccurance += list(frequencies.values()).count(3)\n\nprint('The checksum = ' + str(twoOccurance) + \" * \" + str(threeOccurance) + \" = \" + str(twoOccurance * threeOccurance))\n\n#star 2 solution\ncommonLetters = ''\nfor index, box1 in enumerate(boxes):\n for box2 in boxes[index:]:\n if sum(a != b for a, b in zip(box1, box2)) == 1:\n for a, b in zip(box1, box2):\n if a == b:\n commonLetters += a\n print(\"The common letters are: \" + commonLetters)\n\n#Lessons learned\n# Zip events can be used to combine two variables and then to iterate through them together" }, { "alpha_fraction": 0.6613923907279968, "alphanum_fraction": 0.6677215099334717, "avg_line_length": 24.280000686645508, "blob_id": "50025436ebc38757d6d93f2c82f76953dc14ef0b", "content_id": "53d2ab9e479752fc6d07f1e175e49fbfa0b4719a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 632, "license_type": "no_license", "max_line_length": 66, "num_lines": 25, "path": "/day1.py", "repo_name": "hoogland/AdventOfCode2018", "src_encoding": "UTF-8", "text": "filename = \"resources/day1.txt\"\n\nchanges = [int(x) for x in open(\"resources/day1.txt\").readlines()]\n\n#Solution first star\nprint(\"Final frequency: \" + str(sum(changes)))\n\n#solution second star\nfrequency = 0\nfrequencies = set([0])\ninFrequencies = False\n\nwhile inFrequencies == False:\n for line in changes:\n frequency += line\n if frequency in frequencies:\n print(\"First double value: \" + str(frequency))\n inFrequencies = True\n break\n frequencies.add(frequency)\n\n\n#Lessons learned: \n# set is way faster then List\n# cleaner to read in the changes into variable and convert to int\n" } ]
2
JasonKitty/Grad-CAM
https://github.com/JasonKitty/Grad-CAM
cc3dca3a763a820536734cf3f33770f1befec5c8
21efa0e715fb848cb1119bbbd648aa00339f9926
fc3bfc2a9486ec1f90f93211ec1129fb75434c00
refs/heads/master
2022-04-13T19:25:03.256037
2020-03-17T08:18:17
2020-03-17T08:18:17
261,010,829
1
0
null
2020-05-03T20:02:31
2020-05-03T20:02:28
2020-03-17T08:18:18
null
[ { "alpha_fraction": 0.6582670211791992, "alphanum_fraction": 0.679929256439209, "avg_line_length": 41.69811248779297, "blob_id": "3ceb865ff233005a538fd948e5c1ba75dd520da4", "content_id": "71374b3d8fb12326b71418cb586ea6cbe2bc11ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2262, "license_type": "no_license", "max_line_length": 104, "num_lines": 53, "path": "/src/.ipynb_checkpoints/gradcam-checkpoint.py", "repo_name": "JasonKitty/Grad-CAM", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nimport tensorflow as tf\nfrom tensorflow.keras.models import Model\n\ndef get_grad_cam(image, model, layer_name, class_index):\n \"\"\"tf2.0 implementation of gradient weighted class activation map \n Arguments:\n image: Input image, processed input image with batch dimension, shape=(1, H, W, C)\n model: CNN model\n layer_name: relu of the last convolution layer in the network\n class index: index of the class for which Grad CAM needs to be calculated\n Returns: Class decriminative heatmap for class_index class for given image\"\"\"\n \n #create model with ouput as last convolution layer and model output\n gradCamModel = Model(inputs=model.input, outputs=[model.get_layer(layer_name).output, model.output])\n \n #record operations for auto diff\n with tf.GradientTape() as tape:\n inputs = tf.cast(image, tf.float32)\n [convOut, predictions] = gradCamModel(inputs)\n loss = predictions[:, class_index]\n \n grads = tape.gradient(loss, convOut)\n castConvOut = tf.cast(convOut>0, tf.float32)\n castGrads = tf.cast(grads>0,tf.float32)\n guidedGrads = castConvOut*castGrads*grads\n \n convOut = convOut[0]\n guidedGrads = guidedGrads[0]\n \n weights = tf.reduce_mean(guidedGrads, axis=(0, 1))\n cam = tf.reduce_sum(tf.multiply(weights, convOut), axis=-1)\n h, w = image.shape[1:3]\n heatmap = cv2.resize(cam.numpy(), (w, h))\n # normalize the heatmap such that all values lie in the range\n # [0, 1], scale the resulting values to the range [0, 255],\n # and then convert to an unsigned 8-bit integer\n numer = heatmap - np.min(heatmap)\n denom = (heatmap.max() - heatmap.min()) + 1e-8\n heatmap = numer / denom\n heatmap = (heatmap * 255).astype(\"uint8\")\n return heatmap\n\ndef overlay_heatmap(image, heatmap):\n \"\"\"Function applies colormap to heatmap and overlays the colored heatmap on the input image\"\"\"\n colored_heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET).astype('float32')\n output = cv2.addWeighted(image, 0.5, colored_heatmap, 0.5, 0)\n numer = output - np.min(output)\n denom = (output.max() - output.min()) + 1e-8\n output = numer / denom\n output = (output * 255).astype(\"uint8\")\n return output" }, { "alpha_fraction": 0.7953929305076599, "alphanum_fraction": 0.7967479825019836, "avg_line_length": 80.88888549804688, "blob_id": "2c95a22b58678b00d257b8bf0509deed0ddf5015", "content_id": "e38f5b44f49714e49b91ab448c6de0ad2dfd40d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 746, "license_type": "no_license", "max_line_length": 184, "num_lines": 9, "path": "/README.md", "repo_name": "JasonKitty/Grad-CAM", "src_encoding": "UTF-8", "text": "<b>Grad-CAM</b>\n\nThis repo implements Grad-CAM (by Selvaraju, Ramprasaath R. et al. “Grad-CAM: Visual Explanations from Deep Networks via Gradient-Based Localization.” ) in tensoflow-2. \nGrad CAM stands for gradient weighted class activation map, a way to visualize what the convloution neural network is looking at in input image\nto arrive at a perticular class prediction. \n\nAs mentioned in the paper \"Gradient-weighted Class Activation Mapping (Grad-CAM), uses the gradients of any target concept (say ‘dog’ in a classification network or a sequence of words\nin captioning network) flowing into the final convolutional layer to produce a coarse localization map highlighting the important regions in the image for predicting the concept.\n\"\n\n" } ]
2
FRC-1721/SteamScout
https://github.com/FRC-1721/SteamScout
8f6257f30527da885a69f040ad3e35c56f0e0098
10a2e78e58bb62b8d0af771815ac5a876d175803
0b1bcb13d7d9607eb71bb3917995bc6d1377580a
refs/heads/master
2021-01-21T09:59:46.461008
2017-03-14T23:01:04
2017-03-14T23:01:04
83,369,975
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5141019225120544, "alphanum_fraction": 0.523008406162262, "avg_line_length": 36.425926208496094, "blob_id": "67b589b7f3d7298047f223de11a67e5262e99b8d", "content_id": "8ad3c5dbf500e73a0591d5a7b882ff7c3a5b9ef0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4046, "license_type": "no_license", "max_line_length": 195, "num_lines": 108, "path": "/scouting/viewRawList.php", "repo_name": "FRC-1721/SteamScout", "src_encoding": "UTF-8", "text": "<?php\n\n\n include \"../base.php\";\n?>\n\n<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n <meta name=\"description\" content=\"SteamScout\">\n <meta name=\"author\" content=\"Brennan Macaig, FRC-1721\">\n <title>SteamScout</title>\n <!-- Bootstrap 4.0.0-alpha.6 core CSS -->\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\">\n\n <!-- Custom Style -->\n <link href=\"../css/index.css\">\n </head>\n <body>\n <?php\n if (!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username'])) {\n ?>\n <nav class=\"navbar navbar-inverse navbar-fixed-top\">\n <div class=\"container\">\n <div class=\"navbar-header\">\n <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#navbar\" aria-expanded=\"false\" aria-controls=\"navbar\">\n <span class=\"sr-only\">Toggle Navigation</span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n </button>\n <a class=\"navbar-brand\" href-\"../scouting/\">SteamScout</a>\n </div>\n <div id=\"navbar\" class=\"navbar-collapse collapse\">\n <ul class=\"nav navbar-nav\">\n <li><a href=\"../scouting\">Home</a></li>\n <li class=\"active\"><a href=\"#\">View All Data</a></li>\n <li><a href=\"../scouting/print.php\">Print Data</a></li>\n <li><a href=\"../logout.php\">Log Out</a></li>\n </ul>\n </div>\n </div>\n </nav>\n <div class=\"jumbotron\">\n <div class=\"container\">\n <h1>SteamScout</h1>\n <p><strong>FRC 1721 - Tidal Force presents SteamScout.</strong> This is a cloud based scouting software designed to run on a raspberry pi in the stands for competition. It was designed by\n members of the team, and then built by Brennan Macaig.</p>\n </div>\n </div>\n <div class=\"container\">\n <hr>\n <div class=\"row\">\n <table class=\"table table-striped table-bordered\">\n <?php\n $query = \"SELECT * FROM ranking\";\n $result = mysql_query($query);\n $content = array();\n\n $num = mysql_num_rows($result);\n if ($num > 0) {\n while($row = mysql_fetch_assoc($result)) {\n $content[$row['Team']] = $row;\n }\n }\n if ($num > 0) {\n ?>\n <thead>\n <tr>\n <th><?php echo implode('</th><th>', array_keys(current($content)));?></th>\n </tr>\n </thead>\n <tbody>\n <?php foreach ($content as $tablerow): ?>\n <tr>\n <td><?php echo implode('</td><td>', $tablerow);?>\n </tr>\n <?php endforeach; ?>\n </tbody>\n </table>\n <?php } else { ?>\n <div class=\"alert alert-info\" role=\"alert\">\n <p><strong>¯\\_(ツ)_/¯</strong> It looks like you haven't entered any data to list yet.</p>\n </div>\n <?php } ?>\n </div>\n <hr>\n <footer>\n <div style=\"display:table-cell;vertical-align:bottom;\">\n <div style=\"margin-left:auto;margin-right:auto;\">\n <p>SteamScout &copy; Concord Robotics and Brennan Macaig 2017. All Rights Reserved. &bull; <a href=\"../license.html\">License</a> &bull; <a href=\"http://www.frc1721.org\">FRC 1721 Home</a>'\n </div>\n </div>\n </footer>\n </div>\n <?php\n } else {\n echo \"<meta http-equiv='refresh' content='/' />\";\n echo \"<script> window.location.replace('/')</script>\";\n // Whoops! Not logged in.\n } ?>\n <!-- Latest compiled and minified JavaScript -->\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\" integrity=\"sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa\" crossorigin=\"anonymous\"></script>\n </body>\n</html>\n" }, { "alpha_fraction": 0.4792863130569458, "alphanum_fraction": 0.49505072832107544, "avg_line_length": 38.91707229614258, "blob_id": "13e5107d1f85ce15c188756b3247f536a4afbbb9", "content_id": "9cec1ae11e9bec850e7a0472a83121c1234ad97d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 8209, "license_type": "no_license", "max_line_length": 195, "num_lines": 205, "path": "/scouting/index.php", "repo_name": "FRC-1721/SteamScout", "src_encoding": "UTF-8", "text": "<?php\n\n\n include \"../base.php\";\n?>\n\n<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n <meta name=\"description\" content=\"SteamScout\">\n <meta name=\"author\" content=\"Brennan Macaig, FRC-1721\">\n <title>SteamScout</title>\n <!-- Bootstrap 4.0.0-alpha.6 core CSS -->\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\">\n\n <!-- Font Awesome -->\n <link href=\"../css/font-awesome.min.css\" rel=\"stylesheet\"/>\n <!-- Custom Style -->\n <link href=\"../css/index.css\">\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\" integrity=\"sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa\" crossorigin=\"anonymous\"></script>\n </head>\n <body>\n <?php\n if (!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username'])) {\n ?>\n <nav class=\"navbar navbar-inverse navbar-fixed-top\">\n <div class=\"container\">\n <div class=\"navbar-header\">\n <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#navbar\" aria-expanded=\"false\" aria-controls=\"navbar\">\n <span class=\"sr-only\">Toggle Navigation</span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n </button>\n <a class=\"navbar-brand\" href-\"../scouting/\">SteamScout</a>\n </div>\n <div id=\"navbar\" class=\"navbar-collapse collapse\">\n <ul class=\"nav navbar-nav\">\n <li class=\"active\"><a href=\"#\">Home</a></li>\n <li><a href=\"../scouting/viewAllData.php\">View All Data</a></li>\n <li><a href=\"../scouting/print.php\">Print Data</a></li>\n <li><a href=\"../logout\">Log Out</a></li>\n </ul>\n </div>\n </div>\n </nav>\n <?php\n if (isset($_GET['s'])) {\n switch ($_GET['s']) {\n case \"1\":\n ?>\n <div class=\"alert alert-success\" role=\"alert\">\n <p><strong>(づ。◕‿‿◕。)づ</strong> We added your scouting record. Do another!</p>\n </div>\n <?php\n break;\n }}\n if (isset($_GET['f'])) {\n switch ($_GET['f']) {\n case \"1\":\n ?>\n <div class=\"alert alert-danger\" role=\"alert\">\n <p><strong>┐(‘~`;)┌</strong> Sorry, but that record failed. Try again maybe?</p>\n </div>\n <?php break;\n }}\n ?>\n <div class=\"jumbotron\">\n <div class=\"container\">\n <h1>SteamScout</h1>\n <p><strong>FRC 1721 - Tidal Force presents SteamScout.</strong> This is a cloud based scouting software designed to run on a raspberry pi in the stands for competition. It was designed by\n members of the team, and then built by Brennan Macaig.</p>\n </div>\n </div>\n <?php\n if (isset($_POST['team']) && isset($_POST['match']) && isset($_POST['auto']) && isset($_POST['gear']) && isset($_POST['kpa']) && isset($_POST['climb'])) {\n $team = mysql_real_escape_string($_POST['team']);\n $match = mysql_real_escape_string($_POST['match']);\n $auto = mysql_real_escape_string($_POST['auto']);\n $gear = mysql_real_escape_string($_POST['gear']);\n $kpa = mysql_real_escape_string($_POST['kpa']);\n $climb = mysql_real_escape_string($_POST['climb']);\n\n $postQuery = mysql_query(\"INSERT INTO 2017marea (Team, `Match`, Auto, Gear, Kpa, Climb) VALUES ($team, $match, $auto, $gear, $kpa, $climb)\") or die(\"MySQL Error: \" . mysql_error());\n echo mysql_error($postQuery);\n if ($postQuery) {\n echo \"<script> window.location.replace('../scouting/index.php?s=1')</script>\";\n } else {\n echo \"<script> window.location.replace('../scouting/index.php?f=1')</script>\";\n }\n } else {\n ?>\n <div class=\"container\">\n <hr>\n <div class=\"row\">\n <form method=\"POST\" action=\"/scouting/index.php\", name=\"registerform\" id=\"registerform\" class=\"form-horizontal\">\n <div class=\"form-group\">\n <label for=\"team\" class=\"col-sm-2\">Team Number:</label>\n <div class=\"col-sm-10\">\n <input type=\"text\" name=\"team\" id=\"team\">\n </div>\n <label for=\"match\" class=\"col-sm-2\">Match Number:</label>\n <div class=\"col-sm-10\">\n <input type=\"text\" name=\"match\" id=\"match\">\n </div>\n </div>\n <div class=\"form-group\">\n <label for=\"auto\" class=\"col-sm-2\">Autonomous Performance</label>\n <div class=\"col-sm-10\">\n <div class=\"radio\">\n <label>\n <input type=\"radio\" name=\"auto\" id=\"auto\" value=\"1\" checked>\n Did nothing\n </label>\n </div>\n <div class=\"radio\">\n <label>\n <input type=\"radio\" name=\"auto\" id=\"auto\" value=\"2\">\n Only Crossed Line (Dark Green / Gray)\n </label>\n </div>\n <div class=\"radio\">\n <label>\n <input type=\"radio\" name=\"auto\" id=\"auto\" value=\"3\">\n Deposited Gear\n </label>\n </div>\n </div>\n </div>\n <div class=\"form-group\">\n <label class=\"col-sm-2\">Gears Delivered (TELE)</label>\n <div class=\"col-sm-10\">\n <select class=\"form-control\" name=\"gear\">\n <option value=\"0\">0</option>\n <option value=\"1\">1</option>\n <option value=\"2\">2</option>\n <option value=\"3\">3</option>\n <option value=\"4\">4</option>\n <option value=\"5\">5</option>\n <option value=\"6\">6</option>\n <option value=\"7\">7</option>\n <option value=\"8\">8</option>\n <option value=\"9\">9</option>\n <option value=\"10\">10</option>\n <option value=\"11\">11</option>\n <option value=\"12\">12</option>\n </select>\n </div>\n <label class=\"col-sm-2\">Aprox. KPA Contribution</label>\n <div class=\"col-sm-10\">\n <select class=\"form-control\" name=\"kpa\">\n <option value=\"0\">0</option>\n <option value=\"5\">5</option>\n <option value=\"10\">10</option>\n <option value=\"15\">15</option>\n <option value=\"20\">20</option>\n <option value=\"25\">25</option>\n <option value=\"30\">30</option>\n <option value=\"35\">35</option>\n <option value=\"40\">40</option>\n </select>\n </div>\n <label for=\"tele\" class=\"col-sm-2\">Did they climb?</label>\n <div class=\"col-sm-10\">\n <div class=\"radio\">\n <label>\n <input type=\"radio\" name=\"climb\" id=\"climb\" value=\"1\" checked>\n Yes\n </label>\n </div>\n <div class=\"radio\">\n <label>\n <input type=\"radio\" name=\"climb\" id=\"climb\" value=\"0\">\n No\n </label>\n </div>\n </div>\n </div>\n <div class=\"form-group\">\n <input type=\"submit\" name=\"register\" id=\"register\" class=\"btn btn-success\" value=\"Submit\" />\n </div>\n </form>\n </div>\n <?php } ?>\n <hr>\n <footer>\n <div style=\"display:table-cell;vertical-align:bottom;\">\n <div style=\"margin-left:auto;margin-right:auto;\">\n <p>SteamScout &copy; Concord Robotics and Brennan Macaig 2017. All Rights Reserved. &bull; <a href=\"../license.html\">License</a> &bull; <a href=\"http://www.frc1721.org\">FRC 1721 Home</a>'\n </div>\n </div>\n </footer>\n </div>\n <?php\n } else {\n echo \"<meta http-equiv='refresh' content='/' />\";\n echo \"<script> window.location.replace('/')</script>\";\n // Whoops! Not logged in.\n }\n ?>\n </body>\n</html>\n" }, { "alpha_fraction": 0.6578001379966736, "alphanum_fraction": 0.6685837507247925, "avg_line_length": 35.605262756347656, "blob_id": "1ac49d14afabafeeb62f32980b315d5fc05e305b", "content_id": "36c4d0b489fa0fe5999a56960c461357fee48077", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1391, "license_type": "no_license", "max_line_length": 150, "num_lines": 38, "path": "/print.py", "repo_name": "FRC-1721/SteamScout", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# print.py\n# Written by Brennan Macaig for SteamScout\n# Copyright (C) Brennan Macaig and Concord Robotics 2017\n#\n# print.py takes in one argument (a file path) and prints that file.\n# It returns nothing useful, and can't check the status of a print.\n# This is because prints in Linux are simply written to a directory with no \"spooler\".\n# This code can't check the status of the print because there is none reported.\nimport os\nfrom pathlib import Path\nimport time\n\n_pName = \"\" # The system name of the printer (fetch using http://superuser.com/questions/177445/how-to-list-printer-names-acceptable-for-use-with-lpr)\n\n\n# Print a file to the printer\n# Cannot know if there was an error while printing.\n# It just tries it's best.\ndef printFile(s):\n os.system(\"lpr -P \" + _pName + \" \" + s)\n\n# The main function\n# Checks number of arguments and then runs printFile\ndef main():\n args = sys.argv[1:]\n if (len(args) > 1) or (len(args) == 0):\n # Error out, more than one argument\n print(\"This program only takes exactly one argument - a path to a file.\\nPlease check your syntax and try again.\")\n return\n else\n someFile = Path(str(args[0]))\n if someFile.is_file():\n # It's a file, print it\n printFile(args[0])\n else:\n print(\"Argument is not a file.\\nPlease check your syntax and try again.\")\n return\n" }, { "alpha_fraction": 0.5488917827606201, "alphanum_fraction": 0.5580182671546936, "avg_line_length": 27.407407760620117, "blob_id": "b061f3abb124572533fab3d1ea8523c25afb3c02", "content_id": "0ddf9af2ac64801768814ca9626b53a7743e04ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 767, "license_type": "no_license", "max_line_length": 83, "num_lines": 27, "path": "/logout.php", "repo_name": "FRC-1721/SteamScout", "src_encoding": "UTF-8", "text": "<?php\n\n\n include \"../base.php\";\n $_SESSION = array();\n session_destroy();\n?>\n<html>\n <head>\n <!-- THESE TAGS COME FIRST -->\n <meta charset=\"utf-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <!-- OTHER TAGS -->\n\n <title>Logout | SteamScout</title>\n <link href=\"css/bootstrap.min.css\" rel=\"stylesheet\">\n <link href=\"css/index.css\" rel=\"stylesheet\">\n <meta http-equiv=\"refresh\" content=\"0;index\">\n </head>\n <body>\n <div class=\"container\">\n <h1>You're being logged out.</h1>\n <h2>If you aren't refreshed automatically, just close this window.</h2>\n </div>\n </body>\n</html>\n" }, { "alpha_fraction": 0.6238806247711182, "alphanum_fraction": 0.6238806247711182, "avg_line_length": 24.769229888916016, "blob_id": "51f77801947bc567c205d05dcb8bbad9dd596dad", "content_id": "6afaede46c8fca880fc8c2b5560acc55be4abcf2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 335, "license_type": "no_license", "max_line_length": 94, "num_lines": 13, "path": "/base.php", "repo_name": "FRC-1721/SteamScout", "src_encoding": "UTF-8", "text": "<?php\n\n include \"lib/mysql.php\";\n $db_host = \"localhost\";\n $database = \"robotics\";\n $db_username = \"scouting\";\n $db_password = \"StormScout\";\n\n\n session_start();\n mysql_connect($db_host, $db_username, $db_password) or die(\"MySQL Error: \" . mysql_error());\n mysql_select_db($database) or die(\"MySQL Error: \" . mysql_error());\n?>\n" }, { "alpha_fraction": 0.3842572569847107, "alphanum_fraction": 0.4199869930744171, "avg_line_length": 25.464183807373047, "blob_id": "8feac19d214e136fd3bad1a69c25b469c842a71e", "content_id": "ff72974220282335e8ccc0c64278a37bf58d17ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 9236, "license_type": "no_license", "max_line_length": 154, "num_lines": 349, "path": "/scouting/genList.php", "repo_name": "FRC-1721/SteamScout", "src_encoding": "UTF-8", "text": "<?php\n\n\n include \"../base.php\";\n\n $done = False;\n\n function roundUpToAny($n,$x=5) {\n return (round($n)%$x === 0) ? round($n) : round(($n+$x/2)/$x)*$x;\n }\n\n function eliminateOutliers($list) {\n sort($list);\n\n $newArr = array();\n $counter = 0;\n\n foreach ($list as $i) {\n if($counter == 0) {\n $counter++;\n continue;\n } else if ($counter == count($list) - 1) {\n break;\n } else {\n $x = $counter - 1;\n $newArr[x] = $i;\n }\n $counter++;\n }\n\n if (count($newArr) == 0) {\n // Done\n $done = True;\n return $list;\n }\n\n $average = array_sum($newArr) / count($newArr);\n\n $first = $list[0];\n $y = count($list) - 1;\n $last = $list[$y];\n\n $firstDist = abs($average - $first);\n $lastDist = abs($average - $last);\n\n $finalArr = array();\n\n if ($firstDist < $lastDist) {\n $finalArr[0] = $first;\n for ($z = 1; $z < count($newArr) + 1; $z++) {\n $finalArr[$z] = $newArr[$z-1];\n }\n } else if ($lastDist < $firstDist) {\n for($z = 0; $z < (count($list)) - 2; $z++) {\n $finalArr[$z] = $newArr[$z];\n }\n $finalArr[(count($list)) - 2] = $list[count($list)-1];\n } else {\n $finalArr = $list;\n $done = True;\n }\n\n return $finalArr;\n }\n?>\n\n<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n <meta name=\"description\" content=\"SteamScout\">\n <meta name=\"author\" content=\"Brennan Macaig, FRC-1721\">\n <title>SteamScout</title>\n <!-- Bootstrap 4.0.0-alpha.6 core CSS -->\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\">\n\n <!-- Font Awesome -->\n <link href=\"../css/font-awesome.min.css\" rel=\"stylesheet\"/>\n <!-- Custom Style -->\n <link href=\"../css/index.css\">\n </head>\n <body>\n <?php\n if (!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username'])) {\n ?>\n <nav class=\"navbar navbar-inverse navbar-fixed-top\">\n <div class=\"container\">\n <div class=\"navbar-header\">\n <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#navbar\" aria-expanded=\"false\" aria-controls=\"navbar\">\n <span class=\"sr-only\">Toggle Navigation</span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n </button>\n <a class=\"navbar-brand\" href-\"../scouting/\">SteamScout</a>\n </div>\n <div id=\"navbar\" class=\"navbar-collapse collapse\">\n <ul class=\"nav navbar-nav\">\n <li class=\"active\"><a href=\"#\">Home</a></li>\n <li><a href=\"../scouting/viewAllData.php\">View All Data</a></li>\n <li><a href=\"../scouting/print.php\">Print Data</a></li>\n <li><a href=\"../logout\">Log Out</a></li>\n </ul>\n </div>\n </div>\n </nav>\n <div class=\"jumbotron\">\n <div class=\"container\">\n <h1>SteamScout - Generating List</h1>\n <p><strong>Please wait...</strong> Generating a pick list is hard work and takes me a few seconds. Please wait.</p>\n </div>\n </div>\n <?php\n // Picklist algorithm.\n\n $initialQuery = \"DROP TABLE ranking\";\n $nextQuery = \"CREATE TABLE `ranking` (`Team` INT(25) NOT NULL, `ScoutPoints` INT(25) NOT NULL)\";\n $result1 = mysql_query($initialQuery);\n $result2 = mysql_query($nextQuery);\n if (($result1) && ($result2)) {\n $teams = array(58,\n 133,\n 173,\n 246,\n 319,\n 1027,\n 1058,\n 1071,\n 1289,\n 1474,\n 1699,\n 1721,\n 1761,\n 2084,\n 2423,\n 2648,\n 2713,\n 3451,\n 3930,\n 4169,\n 4311,\n 4555,\n 4564,\n 4572,\n 4761,\n 4906,\n 4909,\n 4929,\n 5122,\n 5459,\n 5556,\n 5735,\n 5752,\n 5962,\n 6161,\n 6324,\n 6335,\n 6617,\n 6731,\n 6762);\n foreach ($teams as $team) {\n $query = \"SELECT * FROM 2017marea WHERE Team=$team\";\n\n $result = mysql_query($query);\n\n $auto = array();\n $gear = array();\n $kpa = array();\n $climb = array();\n\n while($row = mysql_fetch_assoc($result)) {\n array_push($auto, $row[\"Auto\"]);\n array_push($gear, $row[\"Gear\"]);\n array_push($kpa, $row[\"Kpa\"]);\n array_push($climb, $row[\"Climb\"]);\n }\n\n $auto1 = $auto;\n $auto2 = array();\n $gear1 = $gear;\n $gear2 = array();\n $kpa1 = $kpa;\n $kpa2 = array();\n $climb1 = $climb;\n $climb2 = array();\n\n $done = False;\n\n while (!$done) {\n $auto2 = eliminateOutliers($auto1);\n $auto1 = eliminateOutliers($auto2);\n }\n\n $done = False;\n\n while (!$done) {\n $gear2 = eliminateOutliers($gear1);\n $gear1 = eliminateOutliers($gear2);\n }\n\n $done = False;\n\n while (!$done) {\n $kpa2 = eliminateOutliers($kpa1);\n $kpa1 = eliminateOutliers($kpa2);\n }\n\n $done = False;\n\n while (!$done) {\n $climb2 = eliminateOutliers($climb1);\n $climb1 = eliminateOutliers($climb2);\n }\n\n $auto = $auto1;\n $gear = $gear1;\n $kpa = $kpa1;\n $climb = $climb1;\n\n // Take the average of all of those values and then ceil it.\n $flAuto = ceil(array_sum($auto) / count($auto));\n $flGear = ceil(array_sum($gear) / count($gear));\n $flKpa = roundUpToAny(ceil(array_sum($kpa) / count($kpa)));\n $flClimb = ceil(array_sum($climb) / count($climb));\n\n $rpAuto = 0;\n $rpGear = 0;\n $rpKpa = 0\n $rpClimb = 0;\n\n switch ($flAuto) {\n case 0:\n $rpAuto = 0;\n break;\n case 1:\n $rpAuto = 0;\n break;\n case 2:\n $rpAuto = 45;\n break;\n case 3:\n $rpAuto = 100;\n break;\n }\n switch ($flGear) {\n case 0:\n $rpGear = -35;\n break;\n case 1:\n $rpGear = -25;\n break;\n case 2:\n $pGear = -15;\n break;\n case 3:\n $rpGear = 0;\n break;\n case 4:\n $rpGear = 15;\n break;\n case 5:\n $rpGear = 25;\n break;\n case 6:\n $rpGear = 35;\n break;\n case 7:\n $rpGear = 45;\n break;\n case 8:\n $rpGear = 55;\n break;\n case 9:\n $rpGear = 65;\n break;\n case 10:\n $rpGear = 75;\n break;\n case 11:\n $rpGear = 85;\n break;\n case 12:\n $rpGear = 95;\n break;\n default:\n $rpGear = 35;\n break;\n }\n switch ($flKpa) {\n case 0:\n $rpKpa = -5;\n break;\n case 5:\n $rpKpa = 0;\n break;\n case 10:\n $rpKpa = 5;\n break;\n case 15:\n $rpKpa = 10;\n break;\n case 20:\n $rpKpa = 15;\n break;\n case 25:\n $rpKpa = 20;\n break;\n case 30:\n $rpKpa = 25;\n break;\n case 35:\n $rpKpa = 30;\n break;\n case 40:\n $rpKpa = 35;\n break;\n case 45:\n $rpKpa = 40;\n break;\n default:\n $rpKpa = 15;\n break;\n }\n switch ($flClimb) {\n case 0:\n $rpClimb = -50;\n break;\n case 1:\n $rpClimb = 50;\n break;\n default:\n $rpClimb = 50;\n break;\n }\n\n $total = $rpAuto + $rpGear + $rpKpa + $rpClimb;\n $finalQuery = \"INSERT INTO ranking (Team, ScoutPoints) VALUES ('$team', '$total')\"\n\n $finalResult = mysql_query($finalQuery);\n }\n echo \"<meta http-equiv='refresh' content=../scouting/viewRawList.php />\";\n echo \"<script> window.location.replace('../scouting/viewRawList.php')</script>\";\n } else {\n echo \"<meta http-equiv='refresh' content=../scouting/genList.php />\";\n echo \"<script> window.location.replace('../scouting/genList.php')</script>\";\n }\n ?>\n" }, { "alpha_fraction": 0.5393288731575012, "alphanum_fraction": 0.546308696269989, "avg_line_length": 50.02739715576172, "blob_id": "5a04eb86a2739ce6bdb25ee74ed213b5c727be50", "content_id": "a5ceb5ea27d962c54f0010e0bd2643767637230c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3725, "license_type": "no_license", "max_line_length": 256, "num_lines": 73, "path": "/index.php", "repo_name": "FRC-1721/SteamScout", "src_encoding": "UTF-8", "text": "<?php\n\n\n include \"base.php\";\n?>\n\n<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n <meta name=\"description\" content=\"SteamScout\">\n <meta name=\"author\" content=\"Brennan Macaig, FRC-1721\">\n\n <title>SteamScout - Log In</title>\n\n <!-- Bootstrap 4.0.0-alpha.6 core CSS -->\n <link href=\"https://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css\" rel=\"stylesheet\">\n\n <!-- Custom Style -->\n <link href=\"css/index.css\">\n </head>\n <body>\n <?php\n if (!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Email'])) {\n echo \"<script> window.location.replace('/scouting/')</script>\";\n }\n ?>\n <div class=\"container\">\n <form method=\"post\" action=\"index.php\" name=\"loginform\" class=\"form-signin\">\n <fieldset>\n <h2 class=\"form-signin-heading\">Please sign in</h2>\n <label for=\"username\" class=\"sr-only\">Username</label>\n <input type=\"username\" id=\"username\" class=\"form-control\" placeholder=\"Username\" name=\"username\" required autofocus>\n <label for=\"password\" class=\"sr-only\">Password</label>\n <input type=\"password\" id=\"password\" class=\"form-control\" placeholder=\"P@ssword1\" name=\"password\" required>\n <button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">Sign in</button>\n </fieldset>\n </form>\n <?php\n // Check the database to see if this person exists.\n if(!empty($_POST['username']) && !empty($_POST['password'])) {\n $username = mysql_real_escape_string($_POST['username']);\n $password = md5(mysql_real_escape_string($_POST['password']));\n\n // MySQL Query for the database.\n $checklogin = mysql_query(\"SELECT * FROM users WHERE Username = '\".$username.\"' AND Password = '\".$password.\"'\");\n\n // Hurrah! You're logged in, I think.\n if(mysql_num_rows($checklogin) == 1) {\n $row = mysql_fetch_array($checklogin);\n $email = $row['EmailAddress'];\n\n // Stored information in the session. The persons username, and their email. This is so we can adress them by email/username if needed.\n $_SESSION['Username'] = $username;\n $_SESSION['EmailAddress'] = $email;\n $_SESSION['LoggedIn'] = 1;\n\n echo \"<div class='alert alert-success' role='alert'><p><strong>All good!</strong> Logging you in now... please wait.</div>\";\n echo \"<script> window.location.replace('/scouting/index.php')</script>\";\n }\n else {\n echo \"<div class='alert alert-danger' role='alert'><p><strong>Uh oh.</strong> I can't log you in. Please, try re-typing your username and password. If you continue to see this message, contact the system administrator(s).</div>\";\n }\n }\n ?>\n </div>\n <!-- Bootstrap Core JS -->\n <script src=\"https://code.jquery.com/jquery-3.1.1.slim.min.js\" integrity=\"sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n\" crossorigin=\"anonymous\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js\" integrity=\"sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb\" crossorigin=\"anonymous\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js\" integrity=\"sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn\" crossorigin=\"anonymous\"></script>\n </body>\n</html>\n" } ]
7
fflurcodes/rock-paper-scissors
https://github.com/fflurcodes/rock-paper-scissors
5f75a46d04f00a2bed954e95315707199149ca24
0a09ad642133474b8d3e48ecd5642d1b84694d2e
0bb067312ae66dd1ceb6bdb43515b4196fc3e7da
refs/heads/master
2022-02-14T21:11:49.494672
2017-01-14T01:09:40
2017-01-14T01:09:40
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7981651425361633, "alphanum_fraction": 0.8027523159980774, "avg_line_length": 30.14285659790039, "blob_id": "4d8bb4d7d7bc09378039ebe6f76b2499b4e39162", "content_id": "214f044095ccfae6a8fc4d329c5f9746918a85b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 218, "license_type": "no_license", "max_line_length": 65, "num_lines": 7, "path": "/README.md", "repo_name": "fflurcodes/rock-paper-scissors", "src_encoding": "UTF-8", "text": "# rock-paper-scissors\nJust for learning purposes\nattempt at rock paper scissors in python, can play multiple games\n\ntwo modes, 1 player vs the computer and player vs player\n\nnext update will be adding Lizard and Spock\n" }, { "alpha_fraction": 0.6685006618499756, "alphanum_fraction": 0.6685006618499756, "avg_line_length": 30.565217971801758, "blob_id": "7b7fa6986e406637bc7193f68631646b6ac23d0f", "content_id": "a60132b6f0cb2cd8fd8d2b1ebf5ee38f7d08224f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 727, "license_type": "no_license", "max_line_length": 63, "num_lines": 23, "path": "/rockpaperscissors/aifunction.py", "repo_name": "fflurcodes/rock-paper-scissors", "src_encoding": "UTF-8", "text": "#rock paper scissors ai function\nimport random\n\ndef test_logic(playerOne, playerTwo):\n\t\n\tif playerOne.casefold() == playerTwo.casefold(): print('Draw')\n\telif playerOne.casefold() == 'rock':\n\t\tif playerTwo.casefold() == 'scissors':\n\t\t\tprint('Player One wins')\n\t\telif playerTwo.casefold() == 'paper':\n\t\t\tprint('Player Two wins')\n\telif playerOne.casefold() == 'paper':\t\t\n\t\tif playerTwo.casefold() == 'rock':\n\t\t\tprint('Player One wins')\n\t\telif playerTwo.casefold() == 'scissors':\n\t\t\tprint('Player Two wins')\n\telif playerOne.casefold() == 'scissors':\t\t\n\t\tif playerTwo.casefold() == 'rock':\n\t\t\tprint('Player Two wins')\n\t\telif playerTwo.casefold() == 'paper':\n\t\t\tprint('Player One wins')\n\telse:\n\t\tprint('Unknown Weapon, Try again.')\n\n" }, { "alpha_fraction": 0.6873822808265686, "alphanum_fraction": 0.6930320262908936, "avg_line_length": 38.37036895751953, "blob_id": "72c004f1dee37cad32e71f4ca16e5f31b09f411b", "content_id": "f5dd9dfea2c89f5f2a443e36ef017e03c21e8227", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1062, "license_type": "no_license", "max_line_length": 81, "num_lines": 27, "path": "/rockpaperscissors/rps.py", "repo_name": "fflurcodes/rock-paper-scissors", "src_encoding": "UTF-8", "text": "#Rock Paper Scissors\nimport random\nimport aifunction\nwList = ['rock', 'paper', 'scissors']\nplayerNum = input('Please input number of players(max 2): ')\n\nwhile True: \n\tusr_command = input('Would you like to continue or quit?(Type c or q): ')\n\tif usr_command.casefold() == 'q':\n\t\tprint('Thanks for Playing')\n\t\tbreak\n\telif usr_command.casefold() != 'q' and usr_command.casefold() != 'c':\n\t\tprint('Incorrect , Try again')\n\tif playerNum == '2':\n\t\tplayerOne = input('Player One - Choose your weapon: rock, paper or scissors: ')\n\t\tplayerTwo = input('Player Two - Choose your weapon: rock, paper or scissors: ')\n\t\taifunction.test_logic(playerOne, playerTwo)\n\n\telif playerNum == '1':\n\t\tplayerOne = input('Player One - Choose your weapon: rock, paper or scissors: ')\n\t\tplayerTwo = random.choice(wList)\n\t\tprint('The Computer chose ' + playerTwo + ' as their Weapon')\n\t\taifunction.test_logic(playerOne, playerTwo)\n\t\t\n\telif playerNum != '1' and playerNum != '2':\n\t\tprint('Incorrect number of players, Try again')\n\t\tplayerNum = input('Please input number of players(max 2): ')" } ]
3
ITRANCS/ITRANCS.github.io
https://github.com/ITRANCS/ITRANCS.github.io
fd691bf9ad706c22f0872d65dc15ae2cb1df4566
d0f1ff82a6abea3093395ec893e4dab83637ed5c
d03844342ac81ddc8d745662ee0ccb48e203d9d0
refs/heads/master
2023-07-07T19:31:04.558444
2021-08-15T18:56:33
2021-08-15T18:56:33
395,533,402
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4820031225681305, "alphanum_fraction": 0.4960876405239105, "avg_line_length": 16.74193572998047, "blob_id": "b7365ab17abfec57ccf8aa966fa1bf5bedbcab2e", "content_id": "ee50b1f504af5b1192bd96460c8ea4912003a8df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 639, "license_type": "no_license", "max_line_length": 37, "num_lines": 31, "path": "/dataset/dependence/depend_5003 - 副本.py", "repo_name": "ITRANCS/ITRANCS.github.io", "src_encoding": "UTF-8", "text": "import json\r\nimport geoip2.database\r\nfrom iso3166 import countries\r\n\r\nclist = []\r\n\r\nwith open(\"sn.json\",'r') as load_f:\r\n res2 = json.load(load_f)\r\n\r\nfor src in res2:\r\n if src not in clist:\r\n clist.append(src)\r\n for des in res2[src]:\r\n if des not in clist:\r\n clist.append(des)\r\n\r\ndic = {}\r\nrev = {}\r\nfor c in clist:\r\n try:\r\n iso = countries.get(c).alpha3\r\n except:\r\n continue\r\n dic[c] = iso\r\n rev[iso] = c\r\n\r\nwith open('dic.json','w') as f:\r\n json.dump(dic,f)\r\n\r\nwith open('rev.json','w') as f:\r\n json.dump(rev,f)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.4096989929676056, "alphanum_fraction": 0.4364548623561859, "avg_line_length": 14, "blob_id": "21382e39f6d6a39b80ea91325f9223188bfdf40f", "content_id": "362c16a2083cd8567f8202e3ce391da58f9c1fa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 598, "license_type": "no_license", "max_line_length": 32, "num_lines": 33, "path": "/dataset/dependence/split.py", "repo_name": "ITRANCS/ITRANCS.github.io", "src_encoding": "UTF-8", "text": "import json\r\n\r\n\r\nwith open('stv.json','r') as f:\r\n stv = json.load(f)\r\n\r\nkeys = list(stv.keys())\r\n\r\nnum = int(len(keys)/3)\r\n\r\ni = 0\r\n\r\nstv1 = {}\r\nstv2 = {}\r\nstv3 = {}\r\n\r\nfor key in stv:\r\n if i < num:\r\n stv1[key] = stv[key]\r\n elif i >=num and i < 2*num:\r\n stv2[key] = stv[key]\r\n else:\r\n stv3[key] = stv[key]\r\n i+=1\r\n\r\nwith open('stv1.json','w') as f:\r\n json.dump(stv1,f)\r\n\r\nwith open('stv2.json','w') as f:\r\n json.dump(stv2,f)\r\n\r\nwith open('stv3.json','w') as f:\r\n json.dump(stv3,f)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.6321839094161987, "alphanum_fraction": 0.6321839094161987, "avg_line_length": 27, "blob_id": "303e13d9507f92968d3c4a57a91bb69e62daac9f", "content_id": "b6f9d9ea87771d98a79d90413282d6adb4d4df88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 87, "license_type": "no_license", "max_line_length": 46, "num_lines": 3, "path": "/improvement/python/test.py", "repo_name": "ITRANCS/ITRANCS.github.io", "src_encoding": "UTF-8", "text": "@app.route('/insertInvertory',methods=['GET'])\r\ndef test():\r\n print('hello world')\r\n" }, { "alpha_fraction": 0.5220264196395874, "alphanum_fraction": 0.549559473991394, "avg_line_length": 28.266666412353516, "blob_id": "ea2b7a629ed31625088f9ec0e77d205eff084284", "content_id": "6cb733d2e2937aeb86b190e0ab0e6a964d467672", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 908, "license_type": "no_license", "max_line_length": 67, "num_lines": 30, "path": "/dataset/critical/critical_5002.py", "repo_name": "ITRANCS/ITRANCS.github.io", "src_encoding": "UTF-8", "text": "import json\r\nimport geoip2.database\r\nfrom iso3166 import countries\r\nnamedic = ['degree','betweenness','closeness','eigenvector','flow']\r\n\r\n\r\nfor name in namedic:\r\n file = open('2019_critical_node_rank_'+name+'.txt','r')\r\n dic = {}\r\n maxvalue = -1\r\n minvalue = 10000000\r\n for line in file:\r\n parts = line.strip().split(' ')\r\n dic[parts[0]] = float(parts[1])\r\n if float(parts[1]) > maxvalue:\r\n maxvalue = float(parts[1])\r\n elif float(parts[1]) < minvalue:\r\n minvalue = float(parts[1])\r\n file.close()\r\n for key in dic:\r\n dic[key] = (dic[key]-minvalue)/(maxvalue-minvalue)\r\n data = []\r\n for key in dic:\r\n try:\r\n isocode = countries.get(key).alpha3\r\n except:\r\n continue\r\n data.append({'code':isocode,'value':dic[key]})\r\n with open(name+'.json','w') as f:\r\n json.dump(data,f)\r\n" }, { "alpha_fraction": 0.39137738943099976, "alphanum_fraction": 0.41937288641929626, "avg_line_length": 34.48979568481445, "blob_id": "e37cd68d78ee036efd4c7a9fa0702ab92757f194", "content_id": "6a53eb1bfa16223a00829fc9e6425b443b5f7740", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1786, "license_type": "no_license", "max_line_length": 110, "num_lines": 49, "path": "/assets/js/search.js", "repo_name": "ITRANCS/ITRANCS.github.io", "src_encoding": "UTF-8", "text": "function searchb(){\r\n\t\t\t\t\tdocument.getElementById(\"searchbarDialog\").showModal(); \r\n\t\t\t\t}\r\n\t\t\t\tfunction routeb(){\r\n\t\t\t\t\tdocument.getElementById(\"routeDialog\").showModal();\r\n\t\t\t\t}\r\n\t\t\t\tfunction search(){\r\n\t\t\t\t\tdocument.getElementById(\"searchbarDialog\").close();\r\n\t\t\t\t\tvar name=document.getElementById('text');\r\n\t\t\t\t\t$.ajax({\r\n\t url: 'http://127.0.0.1:5000/search',\r\n\t data:{\r\n\t name: name.value\r\n\t },\r\n\t dataType: 'JSON',\r\n\t type: 'GET',\r\n\t success: function(data){\r\n\t \tif(data['type'] == 'ip2geo')\r\n\t \t{\r\n\t \t\tvar lat = data['lat']\r\n\t \t\tvar lng = data['lng']\r\n\t \t\tvar popup = new mapboxgl.Popup({ offset: 25 }).setText(\r\n\t\t\t\t\t\t\tname.value\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\tvar marker = new mapboxgl.Marker()\r\n\t\t\t\t\t\t\t .setLngLat([lng, lat])\r\n\t\t\t\t\t\t\t .setPopup(popup)\r\n\t\t\t\t\t\t\t .addTo(map);\r\n\t\t\t\t\t\t\tmap.flyTo({center:[lng, lat],zoom:11})\r\n\t\t\t\t\t\t\t// map.setZoom(11)\r\n\t \t}\r\n\t \telse if(data['type'] == 'as2geo')\r\n\t \t{\r\n\t \t\tvar colors=new Array(\"#83AF9B\",\"#FE4365\",\"#F4D000\",\"#65934A\",\"#1E293D\",\"#4E1D4C\",\"#3FB1CE\")\r\n\t \t\tcol = colors[randomNum(0,6)]\r\n\t \t\tfor(var k in data['res'])\r\n\t \t\t{\r\n\t \t\t\tvar popup = new mapboxgl.Popup({ offset: 25 }).setText(\r\n\t\t\t\t\t\t\t\t\tname.value+': '+data['res'][k][2].toString()+' IP address'\r\n\t\t\t\t\t\t\t\t\t);\r\n\t \t\t\tvar marker = new mapboxgl.Marker({color:col})\r\n\t\t\t\t\t\t\t\t .setLngLat([data['res'][k][1], data['res'][k][0]])\r\n\t\t\t\t\t\t\t\t .setPopup(popup)\r\n\t\t\t\t\t\t\t\t .addTo(map);\r\n\t \t\t}\r\n\t \t}\r\n\t }\r\n\t });\r\n\t\t\t\t}" }, { "alpha_fraction": 0.5041666626930237, "alphanum_fraction": 0.5208333134651184, "avg_line_length": 33.13414764404297, "blob_id": "8ca6de97aa4922312aabafae0708f3fddaffd8dd", "content_id": "023ad8745780bf29da95ddb0cff619baa3282429", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 7216, "license_type": "no_license", "max_line_length": 339, "num_lines": 164, "path": "/analysis/geography/farness_centrality.html", "repo_name": "ITRANCS/ITRANCS.github.io", "src_encoding": "UTF-8", "text": "<!DOCTYPE HTML>\r\n<!--\r\n\tTXT by HTML5 UP\r\n\thtml5up.net | @ajlkn\r\n\tFree for personal and commercial use under the CCA 3.0 license (html5up.net/license)\r\n-->\r\n<html>\r\n\t<head>\r\n\t\t<title>基于距离中心性的关键节点识别</title>\r\n\t\t<meta charset=\"utf-8\" />\r\n\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\" />\r\n\t\t<link rel=\"stylesheet\" href=\"../../assets/css/main.css\" />\r\n\t</head>\r\n\t<body class=\"is-preload\">\r\n\t\t<div id=\"page-wrapper\">\r\n\r\n\t\t\t<!-- Header -->\r\n\t\t\t\t<header id=\"header\">\r\n\t\t\t\t\t<div class=\"logo container\">\r\n\t\t\t\t\t\t<div>\r\n\t\t\t\t\t\t\t<h1><a href=\"../../index.html\" id=\"logo\">ITRANCS: </a></h1>\r\n\t\t\t\t\t\t\t<p>Internet Topology and Routing Analysis for National Cyber Security</p>\r\n\t\t\t\t\t\t</div>\r\n\t\t\t\t\t</div>\r\n\t\t\t\t</header>\r\n\r\n\r\n\t\t\t<!-- Nav -->\r\n\t\t\t\t<nav id=\"nav\">\r\n\t\t\t\t\t<ul>\r\n\t\t\t\t\t\t<li><a href=\"../../index.html\">主页</a></li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"#\">资源</a>\r\n\t\t\t\t\t\t\t<ul>\r\n\t\t\t\t\t\t\t\t<li><a href=\"../../resource/lg_resource.html\">探针资源</a></li>\r\n\t\t\t\t\t\t\t\t<li><a href=\"../../resource/data_resource.html\">数据资源</a></li>\r\n\t\t\t\t\t\t\t\t<li><a href=\"../../resource/geolocation_resource.html\">地理定位资源</a></li>\r\n\t\t\t\t\t\t\t</ul>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"#\">数据改进</a>\r\n\t\t\t\t\t\t\t<ul>\r\n\t\t\t\t\t\t\t\t<li><a href=\"../../improvement/routing_inference.html\">全球互联网路由态势感知平台</a></li>\r\n\t\t\t\t\t\t\t</ul>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li class=\"current\">\r\n\t\t\t\t\t\t\t<a href=\"#\">互联网拓扑路由分析</a>\r\n\t\t\t\t\t\t\t<ul>\r\n\t\t\t\t\t\t\t\t<li><a href=\"../logic_analysis.html\">逻辑空间分析</a></li>\r\n\t\t\t\t\t\t\t\t<li><a href=\"../geography_analysis.html\">地理空间分析</a></li>\r\n\t\t\t\t\t\t\t</ul>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"#\">工具</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"#\">关于</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t</ul>\r\n\t\t\t\t</nav>\r\n\r\n\t\t\t<!-- Main -->\r\n\t\t\t\t<section id=\"main\">\r\n\t\t\t\t\t<div class=\"container\">\r\n\t\t\t\t\t\t<div class=\"row\">\r\n\t\t\t\t\t\t\t<div class=\"col-12\">\r\n\t\t\t\t\t\t\t\t<div class=\"content\">\r\n\r\n\t\t\t\t\t\t\t\t\t<!-- Content -->\r\n\r\n\t\t\t\t\t\t\t\t\t\t<article class=\"box page-content\">\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t<header>\r\n\t\t\t\t\t\t\t\t\t\t\t\t<h2>基于距离中心性的关键节点识别</h2>\r\n\t\t\t\t\t\t\t\t\t\t\t\t<ul class=\"meta\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t<li class=\"icon fa-clock\">2021-02-06</li>\r\n\t\t\t\t\t\t\t\t\t\t\t\t</ul>\r\n\t\t\t\t\t\t\t\t\t\t\t</header>\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t<section>\r\n\t\t\t\t\t\t\t\t\t\t\t\t<p style=\"margin-bottom:0px\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t在连通图中,一个节点越靠近中心,它离其他所有结点的距离越近。在逻辑分析的研究中,我们已经使用了接近中心性这一概念来衡量节点与其他节点之间的接近程度。不过接近中心性的定义缺乏实际意义,我们不妨将接近中心性的定义公式取倒数,就变成了下面的公式:\r\n\t\t\t\t\t\t\t\t\t\t\t\t</p>\r\n\t\t\t\t\t\t\t\t\t\t\t\t<div align=\"center\"><img src=\"img/formula5.png\" style=\"margin-top:0px; margin-bottom:0px; width: 30%; height: 30%\" align=\"middle\" alt=\"\" /></div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t<p>\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t其中` | V | `代表图中的节点总数,`d(s,t)`代表从节点`s`到节点`t`之间的距离。实际上就是一个节点到其他所有节点的平均路径长度,我们称之为距离中心性。一个节点的距离中心性越大,它就越远离网络的中心。其中`d(s,t)`这一距离概念随着我们所研究的内容而变化,当我们研究国家级别的距离中心性时,这里的距离是国家级别的路径长度;当我们研究大洲级别的距离中心性时,这里的距离是洲际路径的长度。地理路径相同的IP路径可能会有多条,如果我们对于地理路径相同的IP路径只选取一条进行研究,我们称之为普通的距离中心性。如果地理相同的IP路径按照其出现的次数进行计数,则我们称之为加权的距离中心性,因为每条地理路径被按照这条路径的流量频率进行了加权。\r\n\t\t\t\t\t\t\t\t\t\t\t\t</p>\r\n\t\t\t\t\t\t\t\t\t\t\t\t<table align=\"center\"><tr>\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t<td>\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<img src=\"img/Figure_19.png\" style=\"margin-top:0px; margin-bottom:0px; width: 100%; height: 20%\" align=\"middle\" alt=\"\" />\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<h3 align=\"middle\">距离中心性</h3>\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t<td>\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<img src=\"img/Figure_20.png\" style=\"margin-top:0px; margin-bottom:0px; width: 100%; height: 20%\" align=\"middle\" alt=\"\" />\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<h3 align=\"middle\">加权距离中心性</h3>\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t\t\t\t\t\t</tr></table>\r\n\t\t\t\t\t\t\t\t\t\t\t\t<p style=\"margin-bottom:0px\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t上图展示了每个大洲的距离中心性。无论是否加权,北美洲都在远离网络中心。\r\n\t\t\t\t\t\t\t\t\t\t\t\t</p>\r\n\t\t\t\t\t\t\t\t\t\t\t\t<table align=\"center\"><tr>\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t<td>\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<img src=\"img/Figure_21.png\" style=\"margin-top:0px; margin-bottom:0px; width: 100%; height: 20%\" align=\"middle\" alt=\"\" />\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<h3 align=\"middle\">距离中心性</h3>\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t<td>\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<img src=\"img/Figure_22.png\" style=\"margin-top:0px; margin-bottom:0px; width: 100%; height: 20%\" align=\"middle\" alt=\"\" />\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<h3 align=\"middle\">加权距离中心性</h3>\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t\t\t\t\t\t</tr></table>\r\n\t\t\t\t\t\t\t\t\t\t\t\t<p style=\"margin-bottom:0px\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t上图展示了距离中心性最低的四十个国家的距离中心性。在这里我们没有考虑路径数量较少的国家以避免测量偏差带来的影响。我们可以看出距离中心性在这几年没有明显的变化。\r\n\t\t\t\t\t\t\t\t\t\t\t\t</p>\r\n\t\t\t\t\t\t\t\t\t\t\t\t<div align=\"center\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t<img src=\"img/table5.png\" style=\"margin-top:0px; margin-bottom:0px; width: 50%; height: 50%\" align=\"middle\" alt=\"\" />\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t<h3>距离中心性最低的十个国家</h3>\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t<img src=\"img/table6.png\" style=\"margin-top:0px; margin-bottom:0px; width: 50%; height: 50%\" align=\"middle\" alt=\"\" />\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t<h3>加权距离中心性最小的十个国家</h3>\r\n\t\t\t\t\t\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t<p style=\"margin-bottom:0px\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t从上表可以发现,在非加权的距离中心性较小的国家中结果比较分散,而在加权的距离中心性较小的国家中,美国在三年的统计中都出现在了排行榜中。\r\n\t\t\t\t\t\t\t\t\t\t\t\t</p>\r\n\t\t\t\t\t\t\t\t\t\t\t</section>\r\n\r\n\t\t\t\t\t\t\t\t\t\t</article>\r\n\r\n\t\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t\t\r\n\r\n\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t</div>\r\n\t\t\t\t\t</div>\r\n\t\t\t\t</section>\r\n\r\n\t\t\t<!-- Footer -->\r\n\t\t\t\t<footer id=\"footer\">\r\n\t\t\t\t\t<div class=\"container\">\r\n\t\t\t\t\t\t\r\n\r\n\t\t\t\t\t\t<!-- Copyright -->\r\n\t\t\t\t\t\t\t<div id=\"copyright\">\r\n\t\t\t\t\t\t\t\t<ul class=\"menu\">\r\n\t\t\t\t\t\t\t\t\t<li>&copy; Untitled. All rights reserved</li><li>Design: <a href=\"http://html5up.net\">HTML5 UP</a></li>\r\n\t\t\t\t\t\t\t\t</ul>\r\n\t\t\t\t\t\t\t</div>\r\n\r\n\t\t\t\t\t</div>\r\n\t\t\t\t</footer>\r\n\r\n\t\t</div>\r\n\r\n\t\t<!-- Scripts -->\r\n\t\t\t<script src=\"../../assets/js/jquery.min.js\"></script>\r\n\t\t\t<script src=\"../../assets/js/jquery.dropotron.min.js\"></script>\r\n\t\t\t<script src=\"../../assets/js/jquery.scrolly.min.js\"></script>\r\n\t\t\t<script src=\"../../assets/js/browser.min.js\"></script>\r\n\t\t\t<script src=\"../../assets/js/breakpoints.min.js\"></script>\r\n\t\t\t<script src=\"../../assets/js/util.js\"></script>\r\n\t\t\t<script src=\"../../assets/js/main.js\"></script>\r\n\t\t\t<script type=\"text/javascript\" src=\"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=AM_HTMLorMML-full\"></script>\r\n\r\n\t</body>\r\n</html>" }, { "alpha_fraction": 0.48876404762268066, "alphanum_fraction": 0.48876404762268066, "avg_line_length": 15.290322303771973, "blob_id": "7696b0166e049045f500f0738d1de1dc968e77b8", "content_id": "301c2ff8758089508d2efa43a8e210ba584a072f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 534, "license_type": "no_license", "max_line_length": 50, "num_lines": 31, "path": "/assets/js/critical.js", "repo_name": "ITRANCS/ITRANCS.github.io", "src_encoding": "UTF-8", "text": "var buttonsplay = false\r\n\t\t\t\tfunction critical(){\r\n\t\t\t\t\tif(buttonsplay==true)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tbuttonsplay = false\r\n\t\t\t\t\t\tvar bs = document.getElementById(\"buttons\");\r\n \t\t\t\tbs.style.display=\"none\";\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tbuttonsplay = true\r\n\t\t\t\t\t\tvar bs = document.getElementById(\"buttons\");\r\n \t\t\t\tbs.style.display=\"block\";\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tfunction degree()\r\n\t\t\t\t{\r\n\r\n\t\t\t\t}\r\n\t\t\t\tfunction closeness()\r\n\t\t\t\t{\r\n\r\n\t\t\t\t}\r\n\t\t\t\tfunction eigenvector()\r\n\t\t\t\t{\r\n\r\n\t\t\t\t}\r\n\t\t\t\tfunction betweenness()\r\n\t\t\t\t{\r\n\r\n\t\t\t\t}" }, { "alpha_fraction": 0.46397942304611206, "alphanum_fraction": 0.4931389391422272, "avg_line_length": 21.826086044311523, "blob_id": "5ebf55f2fbc0cd36ede98c24a835d088178fe823", "content_id": "2fc337127d42fbe373ac326ce47f1960fa4ae23e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1166, "license_type": "no_license", "max_line_length": 60, "num_lines": 46, "path": "/dataset/dependence/depend_5003.py", "repo_name": "ITRANCS/ITRANCS.github.io", "src_encoding": "UTF-8", "text": "import json\r\nimport geoip2.database\r\nfrom iso3166 import countries\r\n \r\nwith open(\"stv.json\",'r') as load_f:\r\n res1 = json.load(load_f)\r\nwith open(\"sn.json\",'r') as load_f:\r\n res2 = json.load(load_f)\r\nsn2 = {}\r\nfor src in res2:\r\n try:\r\n iso = countries.get(src).alpha3\r\n except:\r\n continue\r\n data = []\r\n for c in res2[src]:\r\n try:\r\n isocode = countries.get(c).alpha3\r\n except:\r\n continue\r\n data.append({'code':isocode,'value':res2[src][c]})\r\n sn2[iso] = data\r\nstv2 = {}\r\nfor key in res1:\r\n c1,c2 = key.split('-')\r\n try:\r\n iso1 = countries.get(c1).alpha3\r\n except:\r\n continue\r\n try:\r\n iso2 = countries.get(c2).alpha3\r\n except:\r\n continue\r\n for c in res1[key]:\r\n try:\r\n isocode = countries.get(c).alpha3\r\n except:\r\n continue\r\n data.append({'code':isocode,'value':res1[key][c]}) \r\n stv2[iso1+'-'+iso2] = data\r\n\r\nwith open('sn2.json','w') as f:\r\n json.dump(sn2,f)\r\n\r\nwith open('stv2.json','w') as f:\r\n json.dump(stv2,f)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.4251321256160736, "alphanum_fraction": 0.43335291743278503, "avg_line_length": 32.905738830566406, "blob_id": "98509a221878bfccccf05313e4c172dff0a8f083", "content_id": "747e38fee42c2d3430969f29bcda102145cfae49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 8551, "license_type": "no_license", "max_line_length": 121, "num_lines": 244, "path": "/assets/js/route.js", "repo_name": "ITRANCS/ITRANCS.github.io", "src_encoding": "UTF-8", "text": "var isPlay = true\r\n\t\t\t\tvar steps = 0\r\n\t\t\t\tvar counter = 0\r\n\t\t\t\tvar newRouteGeoJson = {}\r\n\t\t var point = {\r\n\t\t\t\t\t\t\t\t'type': 'FeatureCollection',\r\n\t\t\t\t\t\t\t\t'features': [\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t'type': 'Feature',\r\n\t\t\t\t\t\t\t\t'properties': {},\r\n\t\t\t\t\t\t\t\t'geometry': {\r\n\t\t\t\t\t\t\t\t'type': 'Point',\r\n\t\t\t\t\t\t\t\t'coordinates': []\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t]\r\n\t\t\t\t\t\t\t};\r\n\t\t\t\tfunction animate() {\r\n\t\t\t\t\tvar start =\r\n\t\t\t\t\tnewRouteGeoJson.features[0].geometry.coordinates[\r\n\t\t\t\t\tcounter >= steps ? counter - 1 : counter\r\n\t\t\t\t\t];\r\n\t\t\t\t\tvar end =\r\n\t\t\t\t\tnewRouteGeoJson.features[0].geometry.coordinates[\r\n\t\t\t\t\tcounter >= steps ? counter : counter + 1\r\n\t\t\t\t\t];\r\n\t\t\t\t\tif (!start || !end) return;\r\n\t\t\t\t\t \r\n\t\t\t\t\t// Update point geometry to a new position based on counter denoting\r\n\t\t\t\t\t// the index to access the arc\r\n\t\t\t\t\tpoint.features[0].geometry.coordinates =\r\n\t\t\t\t\tnewRouteGeoJson.features[0].geometry.coordinates[counter];\r\n\t\t\t\t\t \r\n\t\t\t\t\t// Calculate the bearing to ensure the icon is rotated to match the route arc\r\n\t\t\t\t\t// The bearing is calculated between the current point and the next point, except\r\n\t\t\t\t\t// at the end of the arc, which uses the previous point and the current point\r\n\t\t\t\t\tpoint.features[0].properties.bearing = turf.bearing(\r\n\t\t\t\t\tturf.point(start),\r\n\t\t\t\t\tturf.point(end)\r\n\t\t\t\t\t);\r\n\t\t\t\t\t \r\n\t\t\t\t\t// Update the source with this new data\r\n\t\t\t\t\tmap.getSource('point').setData(point);\r\n\t\t\t\t\t \r\n\t\t\t\t\t// Request the next frame of animation as long as the end has not been reached\r\n\t\t\t\t\tif (counter < steps) {\r\n\t\t\t\t\trequestAnimationFrame(animate);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t \r\n\t\t\t\t\tcounter = counter + 1;\r\n\t\t\t\t}\r\n\r\n\t\t function lineMore(from, to, distance, splitLength, units) {\r\n\t\t var step = parseInt(distance / splitLength)\r\n\t\t var leftLength = distance - step * splitLength\r\n\t\t var rings = []\r\n\t\t var route = turf.linestring([from.geometry.coordinates, to.geometry.coordinates])\r\n\t\t for (let i = 1; i <= step; i++) {\r\n\t\t let nlength = i * splitLength\r\n\t\t let pnt = turf.along(route, nlength, units);\r\n\t\t rings.push(pnt.geometry.coordinates)\r\n\t\t }\r\n\t\t if (leftLength > 0) {\r\n\t\t rings.push(to.geometry.coordinates)\r\n\t\t }\r\n\t\t return rings\r\n\t\t }\r\n\r\n\t\t function resetRoute(route, nstep, units) {\r\n\t\t var newroute = {\r\n\t\t 'type': 'FeatureCollection',\r\n\t\t\t\t 'features': [\r\n\t\t\t\t {\r\n\t\t\t\t 'type': 'Feature',\r\n\t\t\t\t 'geometry': {\r\n\t\t\t\t 'type': 'LineString',\r\n\t\t\t\t 'coordinates': []\r\n\t\t\t\t }\r\n\t\t\t\t }\r\n\t\t\t\t ]\r\n\t\t }\r\n\t\t var lineDistance = turf.lineDistance(route);\r\n\t\t var nDistance = lineDistance / nstep;\r\n\t\t var aLength = route.geometry.coordinates.length;\r\n\t\t for (let i = 0; i < aLength - 1; i++) {\r\n\t\t var from = turf.point(route.geometry.coordinates[i]);\r\n\t\t var to = turf.point(route.geometry.coordinates[i + 1]);\r\n\t\t let lDistance = turf.distance(from, to, units);\r\n\t\t if (i == 0) {\r\n\t\t newroute.features[0].geometry.coordinates.push(route.geometry.coordinates[0])\r\n\t\t }\r\n\t\t if (lDistance > nDistance) {\r\n\t\t let rings = lineMore(from, to, lDistance, nDistance, units)\r\n\t\t newroute.features[0].geometry.coordinates = newroute.features[0].geometry.coordinates.concat(rings)\r\n\t\t } else {\r\n\t\t newroute.features[0].geometry.coordinates.push(route.geometry.coordinates[i + 1])\r\n\t\t }\r\n\t\t }\r\n\t\t return newroute\r\n\t\t }\r\n\t\t function play(){\r\n\t\t \t// Reset the counter\r\n\t\t\t\t\tcounter = 0;\r\n\t\t\t\t\t\t\t \r\n\t\t\t\t\t// Restart the animation\r\n\t\t\t\t\tanimate(counter);\r\n\t\t }\r\n\t\t\t\tfunction route(){\r\n\t\t\t\t\tdocument.getElementById(\"routeDialog\").close();\r\n\t\t\t\t\tvar src=document.getElementById('src');\r\n\t\t\t\t\tvar des=document.getElementById('des');\r\n\t\t\t\t\t$.ajax({\r\n\t url: 'http://127.0.0.1:5001/route',\r\n\t data:{\r\n\t src: src.value,\r\n\t des: des.value\r\n\t },\r\n\t dataType: 'JSON',\r\n\t type: 'GET',\r\n\t success: function(data){\r\n\t \tif(data['status'] == 'success')\r\n\t \t{\r\n\t \t\t\r\n\t \t\tvar routeGeoJson = data['geojson']\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t // A single point that animates along the route.\r\n\t\t\t\t\t\t\t// Coordinates are initially set to origin.\r\n\t\t\t\t\t\t\tmap.addLayer({\r\n\t\t\t\t 'id': 'routeLayer',\r\n\t\t\t\t 'type': 'line',\r\n\t\t\t\t 'source': {\r\n\t\t\t\t 'type': 'geojson',\r\n\t\t\t\t 'lineMetrics': true,\r\n\t\t\t\t 'data': data['geojson']\r\n\t\t\t\t },\r\n\t\t\t\t 'paint': {\r\n\t\t\t\t 'line-width': 7,\r\n\t\t\t\t 'line-opacity': 1,\r\n\t\t\t\t 'line-color': '#009EFF',\r\n\t\t\t\t }\r\n\t\t\t\t });\r\n\t\t\t\t\t\t\tmap.addLayer({\r\n\t\t\t\t 'id': 'arrowLayer',\r\n\t\t\t\t 'type': 'symbol',\r\n\t\t\t\t 'source': {\r\n\t\t\t\t 'type': 'geojson',\r\n\t\t\t\t 'data': data['geojson'] //轨迹geojson格式数据\r\n\t\t\t\t },\r\n\t\t\t\t 'layout': {\r\n\t\t\t\t 'symbol-placement': 'line',\r\n\t\t\t\t 'symbol-spacing': 50, // 图标间隔,默认为250\r\n\t\t\t\t 'icon-image': 'arrowIcon', //箭头图标\r\n\t\t\t\t 'icon-size': 0.5\r\n\t\t\t\t }\r\n\t\t\t\t });\r\n\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tmap.addSource('point', {\r\n\t\t\t\t\t\t\t'type': 'geojson',\r\n\t\t\t\t\t\t\t'data': point\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t \r\n\t\t\t\t\t\t\tmap.addLayer({\r\n\t\t\t\t\t\t\t'id': 'point',\r\n\t\t\t\t\t\t\t'source': 'point',\r\n\t\t\t\t\t\t\t'type': 'symbol',\r\n\t\t\t\t\t\t\t'layout': {\r\n\t\t\t\t\t\t\t'icon-image': 'pulsing-dot'\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t \r\n\t\t\t\t \r\n\t\t\t\t\t\t\tnewRouteGeoJson = resetRoute(data['geojson'].features[0], 1000, 'kilometers')\r\n\r\n\t\t\t\t\t\t\tmap.getSource('routeLayer').setData(newRouteGeoJson);\r\n\t\t\t\t\t\t\tmap.getSource('arrowLayer').setData(newRouteGeoJson);\r\n\t\t\t\t\t\t\t\r\n\r\n\r\n\t\t\t\t\t\t\tpoint.features[0].geometry.coordinates = data['geojson'].features[0].geometry.coordinates[0];\r\n\t\t\t\t\t\t\tsteps = newRouteGeoJson.features[0].geometry.coordinates.length\r\n\t\t\t\t\t\t\t \r\n\t\t\t\t\t\t\t// Update the source layer\r\n\t\t\t\t\t\t\tmap.getSource('point').setData(point); \r\n\r\n\t\t\t\t if('aslist' in data)\r\n\t\t\t\t {\r\n\t\t\t\t \tfor(var k in data['aslist'])\r\n\t\t\t\t \t{\r\n\t\t\t\t \t\tvar coor = data['geojson'].features[0].geometry.coordinates\r\n\t\t\t\t \t\tvar lat = coor[k][1]\r\n\t\t\t \t\tvar lng = coor[k][0]\r\n\t\t\t \t\tvar popup = new mapboxgl.Popup({ offset: 25 }).setText(\r\n\t\t\t\t\t\t\t\t\tdata['aslist'][k]\r\n\t\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\t\t\tvar marker = new mapboxgl.Marker()\r\n\t\t\t\t\t\t\t\t\t .setLngLat([lng, lat])\r\n\t\t\t\t\t\t\t\t\t .setPopup(popup)\r\n\t\t\t\t\t\t\t\t\t .addTo(map);\r\n\t\t\t\t \t}\r\n\t\t\t\t }\r\n\t\t\t\t \r\n\r\n\t\t\t\t if('iplist' in data)\r\n\t\t\t\t {\r\n\t\t\t\t \tfor(var k in data['iplist'])\r\n\t\t\t\t \t{\r\n\t\t\t\t \t\tvar coor = data['geojson'].features[0].geometry.coordinates\r\n\t\t\t\t \t\tvar lat = coor[k][1]\r\n\t\t\t \t\tvar lng = coor[k][0]\r\n\t\t\t \t\tvar popup = new mapboxgl.Popup({ offset: 25 }).setText(\r\n\t\t\t\t\t\t\t\t\tdata['iplist'][k]\r\n\t\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\t\t\tvar marker = new mapboxgl.Marker()\r\n\t\t\t\t\t\t\t\t\t .setLngLat([lng, lat])\r\n\t\t\t\t\t\t\t\t\t .setPopup(popup)\r\n\t\t\t\t\t\t\t\t\t .addTo(map);\r\n\t\t\t\t \t}\r\n\t\t\t\t }\r\n\r\n\t\t\t\t var bs = document.getElementById(\"zoom\");\r\n \t\t\t\t\tbs.style.display=\"block\";\r\n\r\n\r\n\t // \t\tvar lat = data['lat']\r\n\t // \t\tvar lng = data['lng']\r\n\t // \t\tvar popup = new mapboxgl.Popup({ offset: 25 }).setText(\r\n\t\t\t\t\t\t\t// name.value\r\n\t\t\t\t\t\t\t// );\r\n\t\t\t\t\t\t\t// var marker = new mapboxgl.Marker()\r\n\t\t\t\t\t\t\t// .setLngLat([lng, lat])\r\n\t\t\t\t\t\t\t// .setPopup(popup)\r\n\t\t\t\t\t\t\t// .addTo(map);\r\n\t\t\t\t\t\t\t// map.flyTo({center:[lng, lat],zoom:11})\r\n\t\t\t\t\t\t\t// map.setZoom(11)\r\n\t \t}\r\n\t \telse if(data['status'] == 'failed')\r\n\t \t{\r\n\t \t\talert('failed!')\r\n\t \t}\r\n\t \t\r\n\t }\r\n\t });\r\n\t\t\t\t}" }, { "alpha_fraction": 0.7894737124443054, "alphanum_fraction": 0.7894737124443054, "avg_line_length": 19, "blob_id": "ef1a66d778e5b9c8d25ef01bd1ec47b79f75a5d8", "content_id": "1c885e23c4a6f738f65e9c13283706212ce0f4f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 19, "license_type": "no_license", "max_line_length": 19, "num_lines": 1, "path": "/README.md", "repo_name": "ITRANCS/ITRANCS.github.io", "src_encoding": "UTF-8", "text": "# ITRANCS.github.io" } ]
10
vsinha/BookMixer
https://github.com/vsinha/BookMixer
97f6ac33b0edf1922125193e3d51c9d9adf0022f
ee284edc5b6b486bdfd4818e7069374e39860a38
4514b5aaad6c92a5419f959932d778522a65a910
refs/heads/master
2021-01-22T11:47:04.278313
2014-05-07T17:54:42
2014-05-07T17:54:42
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7368420958518982, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 18, "blob_id": "4e2df27841e3c9c1dad14d46f7184a8df9b7fd09", "content_id": "2e6ec5d94a9fc05487ea63ac4db47634a4161c31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 19, "license_type": "no_license", "max_line_length": 18, "num_lines": 1, "path": "/settings.gradle", "repo_name": "vsinha/BookMixer", "src_encoding": "UTF-8", "text": "include ':bookmix'\n" }, { "alpha_fraction": 0.6588693857192993, "alphanum_fraction": 0.6705653071403503, "avg_line_length": 27.55555534362793, "blob_id": "7fbde55bfc5848e593e764233c68de359d4d53dc", "content_id": "5ebc3be098e229558f45e26382bd91544178ba8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 513, "license_type": "no_license", "max_line_length": 106, "num_lines": 18, "path": "/bookmix/src/main/java/com/cs252/bookmixer/bookmix/Markov.java", "repo_name": "vsinha/BookMixer", "src_encoding": "UTF-8", "text": "package com.cs252.bookmixer.bookmix;\n\nimport java.util.Dictionary;\nimport java.util.ArrayList;\nimport java.util.Random;\nimport java.util.Arrays;\nimport java.util.*;\n\npublic class Markov{\n public static void main(String[] args){\n MarkovGen testGen = new MarkovGen();\n testGen.addDatum(\"ask not what your country can do for you ask what you can do for your country\");\n testGen.printDict();\n for(String s:testGen.nextNWords(100)){\n System.out.print(s+\" \");\n }\n }\n}" }, { "alpha_fraction": 0.563488781452179, "alphanum_fraction": 0.5671786069869995, "avg_line_length": 36.77177810668945, "blob_id": "79a5ec64e6ee8889dbdac7732f942c6c2cc75f40", "content_id": "b2b006845e2f956fda68437a4a1946f45d2bc7b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 21681, "license_type": "no_license", "max_line_length": 124, "num_lines": 574, "path": "/bookmix/src/main/java/com/cs252/bookmixer/bookmix/MainActivity.java", "repo_name": "vsinha/BookMixer", "src_encoding": "UTF-8", "text": "package com.cs252.bookmixer.bookmix;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.net.URLConnection;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport android.app.ProgressDialog;\nimport android.content.Context;\nimport android.os.AsyncTask;\nimport android.os.Build;\nimport android.os.PowerManager;\nimport android.support.v7.app.ActionBarActivity;\nimport android.support.v7.app.ActionBar;\nimport android.support.v4.app.Fragment;\nimport android.support.v4.app.FragmentManager;\nimport android.support.v4.app.FragmentTransaction;\nimport android.support.v4.app.FragmentPagerAdapter;\nimport android.os.Bundle;\nimport android.support.v4.view.ViewPager;\nimport android.util.Log;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View.OnClickListener;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.CheckBox;\nimport android.widget.CompoundButton;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\npublic class MainActivity extends ActionBarActivity implements ActionBar.TabListener {\n\n SectionsPagerAdapter mSectionsPagerAdapter;\n ViewPager mViewPager;\n\n DatabaseAdapter db;\n\n BookAdapter bookAdapter;\n ArrayList<Book> selectedItems;\n ListView listView;\n TextView outputTextView;\n Button generateButton;\n ProgressDialog progressDialog;\n MarkovGen markovGen;\n\n private static final String TAG = \"MainActivity\"; // for debugging\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n // init the db\n db = new DatabaseAdapter(this);\n db.resetDB(); // uncomment for db debugging\n db.createDatabase(); // copies if necessary, does nothing otherwise\n db.open();\n\n // instantiate progressBar\n progressDialog = new ProgressDialog(this);\n progressDialog.setMessage(\"A message\");\n progressDialog.setIndeterminate(true);\n progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n progressDialog.setCancelable(true);\n\n selectedItems = new ArrayList<Book>();\n\n // Set up the action bar.\n final ActionBar actionBar = getSupportActionBar();\n actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);\n\n // Create the adapter that will return a fragment for each of the three\n // primary sections of the activity.\n mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());\n\n // Set up the ViewPager with the sections adapter.\n mViewPager = (ViewPager) findViewById(R.id.pager);\n mViewPager.setAdapter(mSectionsPagerAdapter);\n\n // When swiping between different sections, select the corresponding\n // tab. We can also use ActionBar.Tab#select() to do this if we have\n // a reference to the Tab.\n mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {\n @Override\n public void onPageSelected(int position) {\n actionBar.setSelectedNavigationItem(position);\n }\n });\n\n // For each of the sections in the app, add a tab to the action bar.\n for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {\n // Create a tab with text corresponding to the page title defined by\n // the adapter. Also specify this Activity object, which implements\n // the TabListener interface, as the callback (listener) for when\n // this tab is selected.\n actionBar.addTab(\n actionBar.newTab()\n .setText(mSectionsPagerAdapter.getPageTitle(i))\n .setTabListener(this));\n }\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n \n // Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n // Handle action bar item clicks here. The action bar will\n // automatically handle clicks on the Home/Up button, so long\n // as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if (id == R.id.action_settings) {\n return true;\n } else if (id == R.id.action_dbreset) {\n Toast.makeText(getApplicationContext(),\n \"Resetting the database...\", Toast.LENGTH_LONG).show();\n db.close();\n db.resetDB();\n db.createDatabase(); // copies if necessary, does nothing otherwise\n db.open();\n Toast.makeText(getApplicationContext(),\n \"Finished.\", Toast.LENGTH_LONG).show();\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n @Override\n public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {\n Log.d(TAG, \"selected: \" + tab.getText());\n\n if (tab.getText().equals(getString(R.string.title_section2))) {\n\n selectedItems = bookAdapter.getSelectedItems();\n\n // update the textview to reflect what's selected\n StringBuilder resultText = new StringBuilder();\n resultText.append(\"Selected Items: \\n\\n\");\n for (Book b : selectedItems) {\n resultText.append(b.toString());\n resultText.append(\"\\n\");\n }\n\n outputTextView.setText(resultText.toString());\n }\n\n // When the given tab is selected, switch to the corresponding page in the ViewPager.\n mViewPager.setCurrentItem(tab.getPosition());\n }\n\n @Override\n public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {\n Log.d(TAG, \"unselected: \" + tab.getText());\n }\n\n @Override\n public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {\n }\n\n\n public class SectionsPagerAdapter extends FragmentPagerAdapter {\n\n public SectionsPagerAdapter(FragmentManager fm) {\n super(fm);\n }\n\n @Override\n public Fragment getItem(int position) {\n // getItem is called to instantiate the fragment for the given page.\n if (position == 0) {\n return new BookSelectFragment();\n } else if (position == 1) {\n return new MashupFragment();\n } else {\n return null;\n }\n }\n\n @Override\n public int getCount() { // number of total pages.\n return 2;\n }\n\n @Override\n public CharSequence getPageTitle(int position) {\n switch (position) {\n case 0:\n return getString(R.string.title_section1);\n case 1:\n return getString(R.string.title_section2);\n }\n return null; // ya dun goofed\n }\n }\n\n // fragment with listview to select books\n public class BookSelectFragment extends Fragment {\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n Log.d(TAG, \"Creating book select fragment\");\n View rootView = inflater.inflate(R.layout.fragment_bookselect, container, false);\n setListViewHandler(rootView);\n return rootView;\n }\n\n private void setListViewHandler(View view) {\n listView = (ListView) view.findViewById(R.id.bookList);\n\n // convert list of books into array[]\n List<Book> list = db.getAllBooks();\n\n // set adapter\n bookAdapter = new BookAdapter(super.getActivity(), R.layout.listcell, list);\n listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); // able to select multiples\n listView.setAdapter(bookAdapter);\n }\n }\n\n private class BookAdapter extends ArrayAdapter<Book> {\n private List<Book> books;\n public ArrayList<Boolean> checkedItems;\n Context context;\n\n\n public BookAdapter(Context context, int textViewResourceId, List<Book> books) {\n super(context, textViewResourceId, books);\n this.books = books;\n this.context = context;\n\n //initialize to all zeros\n checkedItems = new ArrayList<Boolean>(Collections.nCopies(books.size(), false));\n }\n\n public ArrayList<Book> getSelectedItems() {\n ArrayList<Book> selectedItems = new ArrayList<Book>();\n for (int i = 0; i < books.size(); i++) {\n if (checkedItems.get(i)) { // is selected\n selectedItems.add(books.get(i));\n }\n }\n return selectedItems;\n }\n\n @Override\n public View getView(final int position, View convertView, ViewGroup parent) {\n ViewHolder holder;\n\n if (convertView == null) { // create a new one\n LayoutInflater inflater = (LayoutInflater) getContext()\n .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n convertView = inflater.inflate(R.layout.listcell, null);\n\n holder = new ViewHolder();\n holder.checkBox = (CheckBox) convertView.findViewById( R.id.checkbox );\n holder.title = (TextView) convertView.findViewById(R.id.title_text);\n holder.author = (TextView) convertView.findViewById(R.id.author_text);\n holder.cellView = convertView.findViewById(R.layout.listcell);\n\n holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton compoundButton, boolean b) {\n int position = (Integer) compoundButton.getTag();\n checkedItems.set(position, compoundButton.isChecked());\n }\n });\n\n convertView.setTag(holder);\n convertView.setTag(R.id.title_text, holder.title);\n convertView.setTag(R.id.author_text, holder.author);\n convertView.setTag(R.id.checkbox, holder.checkBox);\n convertView.setTag(R.layout.listcell, holder.cellView);\n\n } else { // recycle an old one\n holder = (ViewHolder) convertView.getTag();\n }\n\n holder.checkBox.setTag(position);\n\n Book b = books.get(position);\n\n holder.title.setText(b.get_title());\n holder.author.setText(b.get_author());\n holder.checkBox.setChecked( checkedItems.get( position ) );\n\n return convertView;\n }\n\n @Override\n public int getCount() {\n return books.size();\n }\n\n @Override\n public Book getItem(int position) {\n return books.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return 0;\n }\n }\n\n static class ViewHolder {\n TextView title;\n TextView author;\n CheckBox checkBox;\n View cellView;\n }\n\n private class DownloadTextTask extends AsyncTask<Book, Integer, Book> {\n static final String TAG = \"DownloadTextTask: \";\n //Toast toast = new Toast(getApplicationContext());\n boolean inChargeOfProgress = false;\n\n Book originalBook;\n\n private Context context;\n private PowerManager.WakeLock mWakeLock;\n\n public DownloadTextTask(Context context) {\n this.context = context;\n }\n\n @Override\n protected Book doInBackground(Book ... books) {\n originalBook = books[0];\n\n InputStream input = null;\n HttpURLConnection connection = null;\n String downloadedText;\n Book bookWithText;\n\n try {\n Log.d(TAG, \"attempting dl from url: \" + books[0].getURL());\n URL url = new URL(books[0].getURL());\n connection = (HttpURLConnection) url.openConnection();\n populateDesktopHttpHeaders(connection);\n connection.connect();\n\n // expect HTTP 200 OK, so we don't mistakenly save error report\n // instead of the file\n if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {\n Log.d(TAG, \"Server returned HTTP \" + connection.getResponseCode()\n + \" \" + connection.getResponseMessage());\n }\n\n // actually download the file\n input = connection.getInputStream();\n BufferedReader br = new BufferedReader(new InputStreamReader(input));\n StringBuilder sb = new StringBuilder();\n\n String line;\n long total = 0;\n long fileSize = books[0].getFilesize();\n System.out.print(\"writing to buffered reader\");\n\n while (true) {\n line = br.readLine();\n if (line == null) {\n break;\n }\n\n // publish progress...\n total += line.length();\n if (fileSize > 0) {// only if total length is known\n publishProgress((int) (total * 100 / fileSize));\n }\n sb.append(line+\" \");\n }\n br.close(); // done with buffered reader\n\n // put the text in the book\n Log.d(TAG, \"writing to output string\");\n downloadedText = sb.toString();\n bookWithText = books[0];\n int startPos=downloadedText.indexOf(\"START OF THIS PROJECT GUTENBERG\");\n if (startPos==-1) startPos=downloadedText.indexOf(\"START OF THE PROJECT GUTENBERG\");\n int endPos = downloadedText.indexOf(\"END OF THIS PROJECT GUTENBERG\");\n if (endPos==-1) endPos=downloadedText.indexOf(\"START OF THE PROJECT GUTENBERG\");\n if(startPos!=-1 && endPos!=-1){\n bookWithText.set_text(downloadedText.substring(startPos,endPos));\n } else{\n System.out.println(\"Warning! Failed to trim. Start: \"+startPos+\" End: \"+endPos);\n bookWithText.set_text(downloadedText);\n }\n markovGen.addDatum(downloadedText.substring(startPos,endPos));\n\n } catch (Exception e) {\n e.printStackTrace();\n return null; // :(\n } finally { // clean up the connection\n Log.d(TAG, \"executing 'finally'\");\n try {\n if (input != null) {\n Log.d(TAG, \"closing input\");\n input.close();\n }\n } catch (IOException i) {\n i.printStackTrace();\n }\n if (connection != null) {\n Log.d(TAG, \"disconnecting connection\");\n connection.disconnect();\n }\n }\n\n Log.d(TAG, \"updating DB with new book\");\n db.updateBook(bookWithText);\n\n Log.d(TAG, \"returning from downloader\");\n return bookWithText;\n }\n\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n Toast.makeText(context,\"Downloading\", Toast.LENGTH_LONG).show();\n\n //Log.d(TAG, \"Showing progress bar\");\n if (!progressDialog.isShowing()) {\n inChargeOfProgress = true;\n progressDialog.show();\n progressDialog.setMessage(\"Downloading\");\n }\n }\n\n @Override\n protected void onProgressUpdate(Integer... progress) {\n super.onProgressUpdate(progress);\n // if we get here, length is known, now set indeterminate to false\n if (!progressDialog.isShowing()) {\n Log.d(TAG, \"taking control of progress\");\n inChargeOfProgress = true;\n progressDialog.show();\n progressDialog.setMessage(\"Downloading \" + originalBook.get_title());\n }\n\n if (inChargeOfProgress) {\n progressDialog.setIndeterminate(false);\n progressDialog.setMax(100);\n progressDialog.setProgress(progress[0]);\n }\n }\n\n @Override\n protected void onPostExecute(Book result) {\n Log.d(TAG, \"doing postExecute\");\n\n //mWakeLock.release();\n if (inChargeOfProgress) {\n progressDialog.dismiss();\n inChargeOfProgress = false;\n }\n\n if (result == null) {\n // null because AsyncTask hasn't done its task\n Toast.makeText(context,\"Download error\", Toast.LENGTH_LONG).show();\n\n } else {\n Log.v(TAG, \"File downloaded\");\n outputTextView.setText(result.toString());\n Toast.makeText(context,\"File downloaded\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n\n // fragment for generating the mashups\n public class MashupFragment extends Fragment {\n\n private void setMashupButtonHanlder(View view) {\n Button mashup_button = (Button) view.findViewById(R.id.mashup_button);\n mashup_button.setOnClickListener(new OnClickListener() {\n @Override\n public void onClick(View view) {\n StringBuilder markovString = new StringBuilder();\n for (String s : markovGen.nextNSentences(10)) {\n markovString.append(s);\n markovString.append(\" \");\n }\n outputTextView.setText(markovString.toString());\n }\n });\n }\n\n // handler for the generate button\n // we download text from gutenberg here\n private void setGenerateButtonHandler(View view) {\n generateButton = (Button) view.findViewById(R.id.generate_button);\n generateButton.setOnClickListener(new OnClickListener() {\n @Override\n public void onClick(View view) {\n Log.d(TAG, \"Mashing up selected books\");\n\n markovGen = new MarkovGen();\n\n // first, download books if necessary\n for (Book book : selectedItems) {\n Log.d(TAG, \"Selected: \" + book.toString()\n + \" isDownloaded? \" + book.is_downloaded());\n\n if (!book.is_downloaded()) { // then download it!\n Log.d(TAG, \"Downloading: \" + book.toString());\n\n Context context = getApplicationContext();\n\n // multi-thread if possible\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {\n Log.d(TAG, \"such multithreading wow\");\n new DownloadTextTask(context)\n .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, book);\n } else {\n try {\n new DownloadTextTask(context).execute(book).get();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n } else { // book is downloaded\n Toast.makeText(getApplicationContext(),\"Generating Markov Chains\",\n Toast.LENGTH_LONG).show();\n markovGen.addDatum(book.get_text());\n }\n }\n }\n });\n }\n\n private void setTextViewAdapter(View view) {\n outputTextView = (TextView) view.findViewById(R.id.result_text);\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n Log.d(TAG, \"Creating mashup fragment\");\n View rootView = inflater.inflate(R.layout.fragment_mashup, container, false);\n\n markovGen = new MarkovGen();\n\n setTextViewAdapter(rootView);\n setGenerateButtonHandler(rootView);\n setMashupButtonHanlder(rootView);\n\n return rootView;\n }\n }\n\n private static void populateDesktopHttpHeaders(URLConnection urlCon) {\n // add custom header in order to be easily detected\n urlCon.setRequestProperty(\"User-Agent\", \"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0\");\n urlCon.setRequestProperty(\"Accept-Language\",\n \"el-gr,el;q=0.8,en-us;q=0.5,en;q=0.3\");\n urlCon.setRequestProperty(\"Accept-Charset\",\n \"ISO-8859-7,utf-8;q=0.7,*;q=0.7\");\n }\n}\n" }, { "alpha_fraction": 0.6232662200927734, "alphanum_fraction": 0.6469798684120178, "avg_line_length": 32.35820770263672, "blob_id": "4631b1e636927178bbf2e83f8a1c2b59b538a4ae", "content_id": "d7f356a0c81448017d7eabf2da22bc27d99086bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2235, "license_type": "no_license", "max_line_length": 176, "num_lines": 67, "path": "/bookmix/src/main/assets/GenerateGutenbergDB.py", "repo_name": "vsinha/BookMixer", "src_encoding": "UTF-8", "text": "import sqlite3 as lite\nimport time\nimport urllib\nimport re\n\nproxies={\"http\":\"http://118.26.57.14:80\"}\nf=open(\"gutenberg.txt\")\nrawInput=f.read()\nsplitByLine=rawInput.split('\\n')\n\nnumbers=[line.split()[0] for line in splitByLine]\n\ntitles=[\" \".join(line.split(\" by \")[0].split()[1:]).replace('\\'','\\'\\'') for line in splitByLine]\n\nauthors=[]\nfor line in splitByLine:\n if(len(line.split(\" by \")) !=2):\n authors.append(\"Unknown\")\n else:\n authors.append(\" \".join(line.split(\" by \")[1].split()[:-1]))\n\nlengths=[]\nfor n,booknum in enumerate(numbers):\n #time.sleep(2)\n f=urllib.urlopen(\"http://onlinebooks.library.upenn.edu/webbin/gutbook/lookup?num=\"+str(booknum))\n text=f.read()\n lengthMatch=re.search(\"Text \\([0-9]+\\.?[0-9]+[MKmk]\\)\",text)\n if(lengthMatch==None):\n lengths.append(1000000)\n continue\n lengthText=lengthMatch.group(0).split()[1]\n lengthMagnitude=lengthText[-2]\n length=float(lengthText[1:-2])\n if(lengthMagnitude=='K'):\n length*=1000\n if(lengthMagnitude=='M'):\n length*=1000000\n lengths.append(length)\n print lengths[n],\n f.close()\n\nurls=[]\nfor booknum in numbers:\n url=\"http://mirror.csclub.uwaterloo.ca/gutenberg\"\n for digit in str(booknum)[:-1]:\n url+='/'+digit\n url+='/'+str(booknum)+'/'+str(booknum)+\".txt\"\n urls.append(url)\n print url\n#urls=[\"http://www.gutenberg.org/cache/epub/\"+str(booknum)+\"/pg\"+str(booknum)+\".txt\" for booknum in numbers]\ncon=None\ncon=lite.connect(\"booksManager.db\")\ncur=con.cursor()\ncur.execute('SELECT SQLITE_VERSION()')\ndata=cur.fetchone()\nprint \"version: \"+str(data)\n\ncur.execute(\"DROP TABLE Books\")\n \ncur.execute(\"CREATE TABLE Books( KEY_ID INTEGER PRIMARY KEY, KEY_TITLE VARCHAR, KEY_AUTHOR VARCHAR, KEY_URL VARCHAR, KEY_DOWNLOADED BIT, KEY_FILESIZE INTEGER, KEY_TEXT TEXT )\")\nfor n in range(100):\n command=\"INSERT INTO Books VALUES(\"+str(n)+\",'\"+str(titles[n])+\"','\"+str(authors[n])+\"','\"+str(urls[n])+\"',\"+\"0,\"+str(lengths[n])+\",'empty_text')\"\n #command=\"INSERT INTO Books VALUES(1,'Declaration of Independence', 'Various', 'FillerURL', 0, '\"+ open(\"usdeclar.txt\").read().replace(\"'\",\"''\") +\"')\"\n print \"Command: \"+command\n cur.execute(command)\ncon.commit()\ncon.close()\n" } ]
4
inkarar/Predictive-Analysis-App
https://github.com/inkarar/Predictive-Analysis-App
03f878d6f8dbe7e2b6a46288990b6257f2dc60fe
1b715d67e21a33fb223f0eb29e28904e1393c627
4141675629c286f3d8a168340842e9dae0548139
refs/heads/main
2023-06-02T14:56:52.846212
2021-06-25T06:23:37
2021-06-25T06:23:37
379,165,645
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8399999737739563, "alphanum_fraction": 0.8399999737739563, "avg_line_length": 25, "blob_id": "f2780957bea56237a1b344a0c92b7300fcbbd65b", "content_id": "e9e0db4bcd4ea11acfd9f83560ecb071e6f17ccd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 25, "license_type": "no_license", "max_line_length": 25, "num_lines": 1, "path": "/README.md", "repo_name": "inkarar/Predictive-Analysis-App", "src_encoding": "UTF-8", "text": "# Predictive-Analysis-App" }, { "alpha_fraction": 0.4457831382751465, "alphanum_fraction": 0.6746987700462341, "avg_line_length": 15.399999618530273, "blob_id": "64fd04633672194e9d3db9b37f24d26e1628d2b7", "content_id": "aff7079710dc45f4bfa54bd882e55b868303c4f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 83, "license_type": "no_license", "max_line_length": 20, "num_lines": 5, "path": "/requirements.txt", "repo_name": "inkarar/Predictive-Analysis-App", "src_encoding": "UTF-8", "text": "streamlit==0.81.1\nnumpy==1.19.5\npandas==1.2.1\nscikit-learn==0.24.2\nplotly==4.14.3\n\n" }, { "alpha_fraction": 0.5840616822242737, "alphanum_fraction": 0.5910882353782654, "avg_line_length": 35.403846740722656, "blob_id": "e9da535f99a7c3b95e20b85959198eab41929bb4", "content_id": "686518f31262efc5efec07e5c1e1e172e1a26a03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5835, "license_type": "no_license", "max_line_length": 162, "num_lines": 156, "path": "/app.py", "repo_name": "inkarar/Predictive-Analysis-App", "src_encoding": "UTF-8", "text": "# Importing the libraries\r\nimport numpy as np\r\nimport pandas as pd\r\nimport plotly.express as px\r\nimport base64\r\nimport streamlit as st\r\n\r\nst.set_page_config(page_title=\"Predictive Analysis App\",layout='wide')\r\n\r\nLOGO_IMAGE = \"Codebios_Logo.png\"\r\n\r\nst.markdown(\r\n \"\"\"\r\n <style>\r\n .container {\r\n display: flex;\r\n }\r\n .logo-text {\r\n font-weight:400 !important;\r\n font-size:20px !important;\r\n color: #f9a01b !important;\r\n padding-top: 50px !important;\r\n }\r\n .logo-img {\r\n float:left;\r\n }\r\n </style>\r\n \"\"\",\r\n unsafe_allow_html=True\r\n)\r\n\r\nst.markdown(\r\n f\"\"\"\r\n <div class=\"container\">\r\n <img class=\"logo-img\" src=\"data:image/png;base64,{base64.b64encode(open(LOGO_IMAGE, \"rb\").read()).decode()}\">\r\n </div>\r\n \"\"\",\r\n unsafe_allow_html=True\r\n)\r\n\r\nhide_streamlit_style = \"\"\"\r\n <style>\r\n #MainMenu {visibility: hidden;}\r\n footer {visibility: hidden;}\r\n </style>\r\n \"\"\"\r\nst.markdown(hide_streamlit_style, unsafe_allow_html=True)\r\n\r\n\r\nst.write('''\r\n# Predictive Analysis App\r\n''')\r\n\r\ntry:\r\n uploaded_file = st.file_uploader(\"Please Upload your .csv file\", type=\"csv\")\r\n\r\n if uploaded_file:\r\n dataset = pd.read_csv(uploaded_file, engine='python')\r\n\r\n view = st.selectbox('Do you want to see the uploaded csv file?',('yes','no'))\r\n\r\n if view == 'yes':\r\n st.table(dataset.head())\r\n\r\n\r\n xaxis = st.selectbox('Which of the following variables you want to display on the X-axis?',list(dataset.columns))\r\n yaxis = st.selectbox('Which of the following variables you want to display on the Y-axis?',list(dataset.columns))\r\n st.write(f'''\r\n ## Plotting '{yaxis}' vs '{xaxis}'\r\n ''')\r\n fig2 = px.line(x=dataset[xaxis],y=dataset[yaxis], labels={'x':f\"{xaxis}\", 'y':f\"{yaxis}\"})\r\n st.plotly_chart(fig2, use_container_width=True, sharing='streamlit')\r\n\r\n\r\n st.write('''\r\n ### Select all the variables you want to exclude from the analysis\r\n ''')\r\n var = st.multiselect('Which of the following variables you want to exclude?',list(dataset.columns))\r\n\r\n if var:\r\n dataset = dataset.drop(var,axis=1)\r\n else:\r\n pass\r\n\r\n st.write('''\r\n ### Select the target variable for which you want to predict values\r\n ''')\r\n target = st.selectbox('Which of the following variables is the target/dependent variable?',list(dataset.columns))\r\n\r\n yes = st.selectbox('Does your data have a Date column?',('no','yes'))\r\n\r\n if yes == 'yes':\r\n date = st.selectbox('Which of the following variables is the DateTime Variable?',list(dataset.columns))\r\n import datetime as dt\r\n dataset[date] = dataset[date].apply(lambda x: dt.datetime.strptime(x,\"%Y-%m-%d\"))\r\n dataset[date] = dataset[date].apply(lambda x: dt.datetime.timestamp(x)) #apply(lambda x: timestamp(x))\r\n\r\n X = dataset.drop(target,axis=1)\r\n y = dataset[target]\r\n\r\n # Encoding categorical data\r\n from sklearn.compose import ColumnTransformer\r\n from sklearn.preprocessing import OneHotEncoder\r\n from sklearn.metrics import mean_squared_error, r2_score\r\n\r\n st.write('''\r\n ### Select the categorical variables for data preprocessing\r\n ''')\r\n cat = st.multiselect('Which of the following variables are categorical variable? Leave blank if None',list(dataset.columns))\r\n category = [dataset.columns.get_loc(c) for c in cat if c in dataset]\r\n\r\n ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), category)], remainder='passthrough')\r\n X = np.array(ct.fit_transform(X))\r\n\r\n # Splitting the dataset into the Training set and Test set\r\n from sklearn.model_selection import train_test_split\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\r\n\r\n # Training the Multiple Linear Regression model on the Training set\r\n from sklearn.linear_model import LinearRegression\r\n regressor = LinearRegression()\r\n regressor.fit(X_train, y_train)\r\n\r\n # Predicting the Test set results\r\n y_pred = regressor.predict(X_test)\r\n \r\n st.write(f'''\r\n ## Predicted and Actual values of Target Variable - {target}\r\n ''')\r\n #st.line_chart(pd.DataFrame(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1),columns=['predicted', 'actual']))\r\n chart = pd.DataFrame(np.concatenate((np.array(y_pred).reshape(len(y_pred),1), np.array(y_test).reshape(len(y_test),1)),1),columns=['predicted', 'actual'])\r\n fig1 = px.line(chart, x = chart.index, y = ['predicted','actual'], labels={'x':\"Data Index\", 'y':f\"{target}\"})\r\n st.plotly_chart(fig1, use_container_width=True, sharing='streamlit')\r\n\r\n st.write('''\r\n ## Mean Squared Error and R2 score from Regression Analysis:\r\n ''')\r\n st.write(\"MSE: \", mean_squared_error(np.array(y_test).reshape(len(y_test),1), np.array(y_pred).reshape(len(y_pred),1)))\r\n st.write(\"R2 score: \", r2_score(np.array(y_test).reshape(len(y_test),1), np.array(y_pred).reshape(len(y_pred),1)))\r\n\r\n st.write('-------------------------------------------------------')\r\n\r\nexcept:\r\n st.write('''\r\n ## Please upload a csv file, select appropriate options from dropdown menu and check if your selected options makes sense\r\n ''')\r\n\r\n\r\nst.markdown(\r\n f\"\"\"\r\n <div class=\"container\">\r\n <p>&copy; Copyright All Rights Reserved. <a href=\"https://codebios.com/\" target=\"_blank\">Codebios Technology.</a></p>\r\n </div>\r\n \"\"\",\r\n unsafe_allow_html=True\r\n)\r\n" } ]
3
ajf014/AdvancedSQL_HW
https://github.com/ajf014/AdvancedSQL_HW
aa5a9f6f85b022e0d6ea2380603912705e51981e
95ebd3bc6564613f32d8a3d9be53251e3b87ad86
77304a3958f90685fc535258ec37334d05f0b427
refs/heads/master
2020-05-26T07:26:13.034485
2019-05-23T03:01:10
2019-05-23T03:01:10
188,150,366
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6076458692550659, "alphanum_fraction": 0.6177062392234802, "avg_line_length": 28.245098114013672, "blob_id": "b713e33ac943cb061968779da26417aba95f4a67", "content_id": "c471c1cde464cfa82a961e06896a02d926fa9a52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2982, "license_type": "no_license", "max_line_length": 120, "num_lines": 102, "path": "/HW.py", "repo_name": "ajf014/AdvancedSQL_HW", "src_encoding": "UTF-8", "text": "import numpy as np\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\nimport datetime as dt\nimport numpy as np\nimport pandas as pd\n\nfrom flask import Flask, jsonify\n\n\n#################################################\n# Database Setup\n#################################################\nengine = create_engine(\"sqlite:///hawaii.sqlite\")\n\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)\n\n# Save reference to the table\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n# Create our session (link) from Python to the DB\nsession = Session(engine)\n\n#################################################\n# Flask Setup\n#################################################\napp = Flask(__name__)\n\[email protected](\"/\")\ndef welcome():\n return (\n f\"Welcome to the Hawaii Climate Analysis API!<br/>\"\n f\"Available Routes:<br/>\"\n f\"/api/v1.0/precipitation<br/>\"\n f\"/api/v1.0/stations<br/>\"\n f\"/api/v1.0/tobs<br/>\"\n f\"/api/v1.0/temp/start<br/>\"\n f\"/api/v1.0/temp/start/end<br/>\"\n )\n\[email protected](\"/api/v1.0/precipitation\")\ndef precipitation():\n date = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n results = session.query(Measurement.date, Measurement.prcp).filter(Measurement.date >= date).all()\n precip = {date: prcp for date, prcp in results}\n\n return jsonify(precip)\n\n\[email protected](\"/api/v1.0/stations\")\ndef stations():\n results = session.query(Station.station, Station.name, Station.latitude, Station.longitude, Station.elevation).all()\n station_list = []\n for station, name, latitude, longitude, elevation in results:\n station_dict = {}\n station_dict[\"station\"] = station\n station_dict[\"name\"] = name\n station_dict[\"latitude\"] = latitude\n station_dict[\"longitude\"] = longitude\n station_dict[\"elevation\"] = elevation\n station_list.append(station_dict)\n\n return jsonify(station_list)\n\n\[email protected](\"/api/v1.0/tobs\")\ndef tobs():\n results = session.query(Measurement.date, Measurement.tobs).all()\n tobs_list = []\n for date, tobs in results:\n tobs_dict = {}\n tobs_dict[\"date\"] = date\n tobs_dict[\"tobs\"] = tobs\n tobs_list.append(tobs_dict)\n\n return jsonify(tobs_list)\n\[email protected](\"/api/v1.0/<start>\")\[email protected](\"/api/v1.0/<start>/<end>\")\ndef stats(start=None, end=None): \n sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]\n if not end: \n results = session.query(*sel).filter(Measurement.date >= start).all()\n temps = list(np.ravel(results))\n return jsonify(temps)\n \n results = session.query(*sel).filter(Measurement.date >= start).filter(Measurement.date <= end).all()\n temps = list(np.ravel(results))\n\n \n return jsonify(temps)\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)" }, { "alpha_fraction": 0.782608687877655, "alphanum_fraction": 0.782608687877655, "avg_line_length": 33.5, "blob_id": "7cc50523e5103fe5ac79ccf961a8c40861eecbf2", "content_id": "09543ac4848653a269cae2e15eaad29e3afb1089", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 69, "license_type": "no_license", "max_line_length": 51, "num_lines": 2, "path": "/README.md", "repo_name": "ajf014/AdvancedSQL_HW", "src_encoding": "UTF-8", "text": "# AdvancedSQL_HW\nThis is the Surf's Up advanced sql homework folder.\n" } ]
2
smartgang/KViewer
https://github.com/smartgang/KViewer
7a43677a6a746c147b65baf670a685137a5c19a0
cb584e302f886069913cf37527e05a7c00be7e23
1f9c1d86aff5dc0286ef3ef971f452f4eb31c01b
refs/heads/master
2020-03-27T06:29:33.884660
2018-10-16T15:52:07
2018-10-16T15:52:07
146,110,644
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5686032176017761, "alphanum_fraction": 0.5755253434181213, "avg_line_length": 36.453704833984375, "blob_id": "4f02c6170905ee8454f094a32bb4e37259496473", "content_id": "03a1d522a9dd9a6ebb0e89adbd3304ae490ee9c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8498, "license_type": "no_license", "max_line_length": 108, "num_lines": 216, "path": "/ChildGraph.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom Indexer import *\nimport pyqtgraph as pg\nimport pandas as pd\n\n\nclass ChildGraph(QWidget):\n\n main_child_plt_changed = pyqtSignal(name='main_child_plt_changed')\n\n def __init__(self, child=True):\n super(ChildGraph, self).__init__()\n self.child = child\n self.frame_layout = QVBoxLayout(self)\n self.para_setting_btn = QPushButton(\"参数设置\")\n self.para_setting_btn.setFixedWidth(100)\n self.indexer_label = QLabel(self)\n self.vLine = None\n self.frame_layout.addLayout(self.header_layout())\n self.raw_data = None\n self.open_list = []\n self.high_list = [] # 当子图为主图是(child=Fasle), 用来保留raw_data的high和low信息,用于计算Y轴范围\n self.low_list = []\n self.close_list = []\n self.time_list = []\n self.plt = None\n self.indexer_class = None\n self.indexer_name = ''\n self.indexer_widget = None\n\n def set_raw_data(self, raw_data):\n # 外部调用,在主图获取到数据后传入数据\n # 获取到数据同时加载plt,如果是主图则加载K线ohlc\n self.raw_data = raw_data\n if not self.child:\n self.open_list = self.raw_data['open'].tolist()\n self.high_list = self.raw_data['high'].tolist()\n self.low_list = self.raw_data['low'].tolist()\n self.close_list = self.raw_data['close'].tolist()\n self.time_list = self.raw_data['strtime'].tolist()\n self._setup_plt()\n\n def _setup_candlestick(self):\n # 为主图加载K线\n csitem = CandlestickItem(self.raw_data)\n axis = DateAxis(date_strings=self.time_list, orientation='bottom')\n return csitem, axis\n\n def _setup_plt(self):\n if self.plt:\n self.plt.close()\n if not self.child:\n # 为主图加载K线\n item, axis = self._setup_candlestick()\n self.plt = pg.PlotWidget(axisItems={'bottom': axis})\n self.plt.addItem(item, )\n self.plt.showGrid(x=True, y=True)\n self.main_child_plt_changed.emit()\n else:\n self.plt = pg.PlotWidget()\n self.plt.showGrid(x=True, y=True)\n self.vLine = pg.InfiniteLine(angle=90, movable=False)\n self.plt.addItem(self.vLine)\n self.frame_layout.addWidget(self.plt)\n\n def header_layout(self):\n hbox = QHBoxLayout(self)\n self.para_setting_btn.clicked.connect(self.set_indexer_parameter)\n hbox.addWidget(self.indexer_label)\n hbox.addWidget(self.para_setting_btn)\n return hbox\n\n def set_indexer_label(self, xpos):\n # 设置指标标签的值,同时更新竖线位置\n if self.indexer_class:\n if xpos >= self.indexer_class.value_num:\n return\n value_str = self.indexer_class.get_indexer_value_text(xpos)\n if not self.child:\n # 主图要加上ohlc数据\n open = self.open_list[xpos]\n close = self.close_list[xpos]\n if open > close:\n c = 'green'\n elif open < close:\n c = 'red'\n else:\n c = 'black'\n value_str += \\\n \" <span style='color: %s'>open=%0.1f,high=%0.1f,low=%0.1f,close=%0.1f</span>,%s\" % (\n c, open, self.high_list[xpos], self.low_list[xpos], close, self.time_list[xpos])\n self.indexer_label.setText(value_str)\n self.vLine.setPos(xpos)\n\n def set_indexer_parameter(self):\n # 用户设置指标参数接口,弹出指标设置对话框供用户设置\n # 已设置的指标加载已有参数,其余指标均加载默认参数\n all_indexer_para_dic = get_all_indexer_para_dic()\n current_indexer_name = 'MA'\n if self.indexer_class:\n all_indexer_para_dic[self.indexer_name] = self.indexer_class.get_para_dic()\n current_indexer_name = self.indexer_class.indexer_name\n self.indexer_widget = IndexerWidget(all_indexer_para_dic, current_indexer_name)\n self.indexer_widget.signal_para_changed.connect(self.indexer_parameter_changed)\n self.indexer_widget.show()\n\n def indexer_parameter_changed(self, selected_indexer, para_dic):\n # 接收用户设置的新参数,并更新显示\n if selected_indexer == self.indexer_name:\n # 所选指标与已有指标相同,则更新参数\n self.indexer_class.update_parameter(para_dic[selected_indexer])\n else:\n # 所选指标与已有指标不同,则加载新指标\n if self.indexer_class:\n #self.plt.clear()\n self._setup_plt()\n indexer_class = indexer_mapping_dic[selected_indexer](self.raw_data, self.plt)\n indexer_class.set_para_dic(para_dic[selected_indexer])\n indexer_class.calculate_indexer_value()\n indexer_class.draw_indexer()\n self.indexer_class = indexer_class\n self.indexer_name = selected_indexer\n self.update_visual_range(200, 400)\n self.set_indexer_label(200)\n\n def update_visual_range(self, start_pos, end_pos):\n if self.plt and self.indexer_class:\n # Y轴自适应\n value_n = self.indexer_class.value_num\n start_pos = max(0, start_pos)\n start_pos = min(start_pos, value_n)\n end_pos = max(1, end_pos)\n end_pos = min(end_pos, value_n)\n if not self.child:\n minY = min(self.low_list[start_pos:end_pos])\n maxY = max(self.high_list[start_pos:end_pos])\n else:\n minY = 999999\n maxY = 0\n indexer_max_value, indexer_min_value = self.indexer_class.get_polar_value(start_pos, end_pos)\n minY = min(minY, indexer_min_value)\n maxY = max(maxY, indexer_max_value)\n self.plt.setYRange(minY, maxY)\n self.plt.setXRange(start_pos, end_pos, padding=0)\n\n\nclass DateAxis(pg.AxisItem):\n def __init__(self, date_strings, orientation):\n pg.AxisItem.__init__(self, orientation)\n self.date_strings = date_strings\n self.len = len(self.date_strings)\n\n def tickStrings(self, values, scale, spacing):\n strns = []\n for x in values:\n x1 = int(x)\n if 0 <= x1 < self.len:\n strns.append(self.date_strings[x1])\n else:\n strns.append('')\n return strns\n\n\n## Create a subclass of GraphicsObject.\n## The only required methods are paint() and boundingRect()\n## (see QGraphicsItem documentation)\nclass CandlestickItem(pg.GraphicsObject):\n def __init__(self, data):\n pg.GraphicsObject.__init__(self)\n t = range(data.shape[0])\n open = data.open.tolist()\n high = data.high.tolist()\n low = data.low.tolist()\n close = data.close.tolist()\n\n self.data = zip(t, open, close, low, high)\n ## data must have fields: time, open, close, min, max\n self.generatePicture()\n\n def generatePicture(self):\n ## pre-computing a QPicture object allows paint() to run much more quickly,\n ## rather than re-drawing the shapes every time.\n self.picture = QPicture()\n p = QPainter(self.picture)\n p.setPen(pg.mkPen('w'))\n w = (self.data[1][0] - self.data[0][0]) / 3.\n for (t, open, close, min, max) in self.data:\n p.drawLine(QPointF(t, min), QPointF(t, max))\n if open > close:\n p.setBrush(pg.mkBrush('g'))\n else:\n p.setBrush(pg.mkBrush('r'))\n p.drawRect(QRectF(t - w, open, w * 2, close - open))\n p.end()\n\n def paint(self, p, *args):\n p.drawPicture(0, 0, self.picture)\n\n def boundingRect(self):\n ## boundingRect _must_ indicate the entire area that will be drawn on\n ## or else we will get artifacts and possibly crashing.\n ## (in this case, QPicture does all the work of computing the bouning rect for us)\n return QRectF(self.picture.boundingRect())\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n demo = ChildGraph(False)\n # demo.update_visual_range(200, 300)\n demo.set_raw_data(1)\n demo.show()\n sys.exit(app.exec_())\n" }, { "alpha_fraction": 0.6409478187561035, "alphanum_fraction": 0.6804046630859375, "avg_line_length": 58.80573272705078, "blob_id": "b9ea097f571c635cebf17f98d01f33bf4733981f", "content_id": "3acdc1e5523145a17641d02c051b441e6ead50d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18860, "license_type": "no_license", "max_line_length": 108, "num_lines": 314, "path": "/kviewer1.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'kviewer.ui'\n#\n# Created by: PyQt5 UI code generator 5.6\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(800, 600)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())\n self.centralwidget.setSizePolicy(sizePolicy)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.centralwidget)\n self.verticalLayout_2.setObjectName(\"verticalLayout_2\")\n self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)\n self.tabWidget.setObjectName(\"tabWidget\")\n self.tab_para = QtWidgets.QWidget()\n self.tab_para.setObjectName(\"tab_para\")\n self.groupBox_3 = QtWidgets.QGroupBox(self.tab_para)\n self.groupBox_3.setGeometry(QtCore.QRect(400, 110, 361, 121))\n self.groupBox_3.setObjectName(\"groupBox_3\")\n self.label = QtWidgets.QLabel(self.groupBox_3)\n self.label.setGeometry(QtCore.QRect(30, 60, 41, 16))\n self.label.setObjectName(\"label\")\n self.lineEdit_macd_short = QtWidgets.QLineEdit(self.groupBox_3)\n self.lineEdit_macd_short.setEnabled(False)\n self.lineEdit_macd_short.setGeometry(QtCore.QRect(80, 60, 41, 20))\n self.lineEdit_macd_short.setObjectName(\"lineEdit_macd_short\")\n self.label_2 = QtWidgets.QLabel(self.groupBox_3)\n self.label_2.setGeometry(QtCore.QRect(150, 60, 31, 16))\n self.label_2.setObjectName(\"label_2\")\n self.lineEdit_macd_long = QtWidgets.QLineEdit(self.groupBox_3)\n self.lineEdit_macd_long.setEnabled(False)\n self.lineEdit_macd_long.setGeometry(QtCore.QRect(190, 60, 41, 20))\n self.lineEdit_macd_long.setObjectName(\"lineEdit_macd_long\")\n self.label_3 = QtWidgets.QLabel(self.groupBox_3)\n self.label_3.setGeometry(QtCore.QRect(260, 60, 21, 16))\n self.label_3.setObjectName(\"label_3\")\n self.lineEdit_macd_m = QtWidgets.QLineEdit(self.groupBox_3)\n self.lineEdit_macd_m.setEnabled(False)\n self.lineEdit_macd_m.setGeometry(QtCore.QRect(280, 60, 41, 20))\n self.lineEdit_macd_m.setObjectName(\"lineEdit_macd_m\")\n self.checkBox_macd = QtWidgets.QCheckBox(self.groupBox_3)\n self.checkBox_macd.setGeometry(QtCore.QRect(30, 30, 71, 16))\n self.checkBox_macd.setObjectName(\"checkBox_macd\")\n self.groupBox_2 = QtWidgets.QGroupBox(self.tab_para)\n self.groupBox_2.setGeometry(QtCore.QRect(20, 110, 371, 121))\n self.groupBox_2.setObjectName(\"groupBox_2\")\n self.gridLayoutWidget = QtWidgets.QWidget(self.groupBox_2)\n self.gridLayoutWidget.setGeometry(QtCore.QRect(10, 40, 351, 80))\n self.gridLayoutWidget.setObjectName(\"gridLayoutWidget\")\n self.gridLayout_2 = QtWidgets.QGridLayout(self.gridLayoutWidget)\n self.gridLayout_2.setContentsMargins(0, 0, 0, 0)\n self.gridLayout_2.setObjectName(\"gridLayout_2\")\n self.label_5 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_5.setObjectName(\"label_5\")\n self.gridLayout_2.addWidget(self.label_5, 0, 0, 1, 1)\n self.label_7 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_7.setObjectName(\"label_7\")\n self.gridLayout_2.addWidget(self.label_7, 0, 4, 1, 1)\n self.lineEdit_ma_n3 = QtWidgets.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n3.setEnabled(False)\n self.lineEdit_ma_n3.setObjectName(\"lineEdit_ma_n3\")\n self.gridLayout_2.addWidget(self.lineEdit_ma_n3, 0, 5, 1, 1)\n self.lineEdit_ma_n2 = QtWidgets.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n2.setEnabled(False)\n self.lineEdit_ma_n2.setObjectName(\"lineEdit_ma_n2\")\n self.gridLayout_2.addWidget(self.lineEdit_ma_n2, 0, 3, 1, 1)\n self.label_6 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_6.setObjectName(\"label_6\")\n self.gridLayout_2.addWidget(self.label_6, 0, 2, 1, 1)\n self.lineEdit_ma_n1 = QtWidgets.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n1.setEnabled(False)\n self.lineEdit_ma_n1.setObjectName(\"lineEdit_ma_n1\")\n self.gridLayout_2.addWidget(self.lineEdit_ma_n1, 0, 1, 1, 1)\n self.label_8 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_8.setObjectName(\"label_8\")\n self.gridLayout_2.addWidget(self.label_8, 1, 0, 1, 1)\n self.lineEdit_ma_n4 = QtWidgets.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n4.setEnabled(False)\n self.lineEdit_ma_n4.setObjectName(\"lineEdit_ma_n4\")\n self.gridLayout_2.addWidget(self.lineEdit_ma_n4, 1, 1, 1, 1)\n self.label_9 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_9.setObjectName(\"label_9\")\n self.gridLayout_2.addWidget(self.label_9, 1, 2, 1, 1)\n self.lineEdit_ma_n5 = QtWidgets.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n5.setEnabled(False)\n self.lineEdit_ma_n5.setObjectName(\"lineEdit_ma_n5\")\n self.gridLayout_2.addWidget(self.lineEdit_ma_n5, 1, 3, 1, 1)\n self.label_10 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_10.setObjectName(\"label_10\")\n self.gridLayout_2.addWidget(self.label_10, 1, 4, 1, 1)\n self.comboBox_ma = QtWidgets.QComboBox(self.gridLayoutWidget)\n self.comboBox_ma.setEnabled(False)\n self.comboBox_ma.setObjectName(\"comboBox_ma\")\n self.comboBox_ma.addItem(\"\")\n self.comboBox_ma.addItem(\"\")\n self.gridLayout_2.addWidget(self.comboBox_ma, 1, 5, 1, 1)\n self.checkBox_ma = QtWidgets.QCheckBox(self.groupBox_2)\n self.checkBox_ma.setGeometry(QtCore.QRect(20, 20, 71, 16))\n self.checkBox_ma.setChecked(False)\n self.checkBox_ma.setObjectName(\"checkBox_ma\")\n self.groupBox_5 = QtWidgets.QGroupBox(self.tab_para)\n self.groupBox_5.setGeometry(QtCore.QRect(400, 10, 361, 91))\n self.groupBox_5.setObjectName(\"groupBox_5\")\n self.pushButton_opr_file = QtWidgets.QPushButton(self.groupBox_5)\n self.pushButton_opr_file.setGeometry(QtCore.QRect(30, 40, 75, 23))\n self.pushButton_opr_file.setObjectName(\"pushButton_opr_file\")\n self.label_opr = QtWidgets.QLabel(self.groupBox_5)\n self.label_opr.setGeometry(QtCore.QRect(130, 40, 54, 12))\n self.label_opr.setObjectName(\"label_opr\")\n self.groupBox_4 = QtWidgets.QGroupBox(self.tab_para)\n self.groupBox_4.setGeometry(QtCore.QRect(20, 10, 371, 90))\n self.groupBox_4.setObjectName(\"groupBox_4\")\n self.gridLayoutWidget_2 = QtWidgets.QWidget(self.groupBox_4)\n self.gridLayoutWidget_2.setGeometry(QtCore.QRect(9, 20, 351, 61))\n self.gridLayoutWidget_2.setObjectName(\"gridLayoutWidget_2\")\n self.gridLayout_3 = QtWidgets.QGridLayout(self.gridLayoutWidget_2)\n self.gridLayout_3.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)\n self.gridLayout_3.setContentsMargins(0, 0, 0, 0)\n self.gridLayout_3.setObjectName(\"gridLayout_3\")\n self.lineEdit_contract = QtWidgets.QLineEdit(self.gridLayoutWidget_2)\n self.lineEdit_contract.setObjectName(\"lineEdit_contract\")\n self.gridLayout_3.addWidget(self.lineEdit_contract, 0, 2, 1, 1)\n self.label_4 = QtWidgets.QLabel(self.gridLayoutWidget_2)\n self.label_4.setObjectName(\"label_4\")\n self.gridLayout_3.addWidget(self.label_4, 0, 3, 1, 1)\n self.label_12 = QtWidgets.QLabel(self.gridLayoutWidget_2)\n self.label_12.setObjectName(\"label_12\")\n self.gridLayout_3.addWidget(self.label_12, 0, 0, 1, 1)\n self.comboBox_bar = QtWidgets.QComboBox(self.gridLayoutWidget_2)\n self.comboBox_bar.setObjectName(\"comboBox_bar\")\n self.comboBox_bar.addItem(\"\")\n self.comboBox_bar.addItem(\"\")\n self.comboBox_bar.addItem(\"\")\n self.comboBox_bar.addItem(\"\")\n self.comboBox_bar.addItem(\"\")\n self.comboBox_bar.addItem(\"\")\n self.comboBox_bar.addItem(\"\")\n self.gridLayout_3.addWidget(self.comboBox_bar, 0, 4, 1, 1)\n self.label_13 = QtWidgets.QLabel(self.gridLayoutWidget_2)\n self.label_13.setObjectName(\"label_13\")\n self.gridLayout_3.addWidget(self.label_13, 1, 0, 1, 1)\n self.label_14 = QtWidgets.QLabel(self.gridLayoutWidget_2)\n self.label_14.setObjectName(\"label_14\")\n self.gridLayout_3.addWidget(self.label_14, 1, 3, 1, 1)\n self.dateEdit_end = QtWidgets.QDateEdit(self.gridLayoutWidget_2)\n self.dateEdit_end.setDateTime(QtCore.QDateTime(QtCore.QDate(2018, 6, 30), QtCore.QTime(0, 0, 0)))\n self.dateEdit_end.setObjectName(\"dateEdit_end\")\n self.gridLayout_3.addWidget(self.dateEdit_end, 1, 4, 1, 1)\n self.dateEdit_start = QtWidgets.QDateEdit(self.gridLayoutWidget_2)\n self.dateEdit_start.setObjectName(\"dateEdit_start\")\n self.gridLayout_3.addWidget(self.dateEdit_start, 1, 2, 1, 1)\n self.pushButton_set_para = QtWidgets.QPushButton(self.tab_para)\n self.pushButton_set_para.setGeometry(QtCore.QRect(360, 360, 75, 23))\n self.pushButton_set_para.setObjectName(\"pushButton_set_para\")\n self.groupBox_6 = QtWidgets.QGroupBox(self.tab_para)\n self.groupBox_6.setGeometry(QtCore.QRect(20, 240, 371, 80))\n self.groupBox_6.setObjectName(\"groupBox_6\")\n self.lineEdit_kdj_n = QtWidgets.QLineEdit(self.groupBox_6)\n self.lineEdit_kdj_n.setEnabled(False)\n self.lineEdit_kdj_n.setGeometry(QtCore.QRect(40, 50, 51, 20))\n self.lineEdit_kdj_n.setObjectName(\"lineEdit_kdj_n\")\n self.lineEdit_kdj_m1 = QtWidgets.QLineEdit(self.groupBox_6)\n self.lineEdit_kdj_m1.setEnabled(False)\n self.lineEdit_kdj_m1.setGeometry(QtCore.QRect(160, 50, 51, 20))\n self.lineEdit_kdj_m1.setObjectName(\"lineEdit_kdj_m1\")\n self.lineEdit_kdj_m2 = QtWidgets.QLineEdit(self.groupBox_6)\n self.lineEdit_kdj_m2.setEnabled(False)\n self.lineEdit_kdj_m2.setGeometry(QtCore.QRect(270, 50, 51, 20))\n self.lineEdit_kdj_m2.setObjectName(\"lineEdit_kdj_m2\")\n self.label_11 = QtWidgets.QLabel(self.groupBox_6)\n self.label_11.setGeometry(QtCore.QRect(20, 50, 21, 16))\n self.label_11.setObjectName(\"label_11\")\n self.label_15 = QtWidgets.QLabel(self.groupBox_6)\n self.label_15.setGeometry(QtCore.QRect(140, 50, 21, 16))\n self.label_15.setObjectName(\"label_15\")\n self.label_16 = QtWidgets.QLabel(self.groupBox_6)\n self.label_16.setGeometry(QtCore.QRect(250, 50, 21, 16))\n self.label_16.setObjectName(\"label_16\")\n self.checkBox_kdj = QtWidgets.QCheckBox(self.groupBox_6)\n self.checkBox_kdj.setGeometry(QtCore.QRect(20, 20, 71, 16))\n self.checkBox_kdj.setObjectName(\"checkBox_kdj\")\n self.groupBox_7 = QtWidgets.QGroupBox(self.tab_para)\n self.groupBox_7.setGeometry(QtCore.QRect(400, 240, 361, 81))\n self.groupBox_7.setObjectName(\"groupBox_7\")\n self.lineEdit_dmi_n = QtWidgets.QLineEdit(self.groupBox_7)\n self.lineEdit_dmi_n.setEnabled(False)\n self.lineEdit_dmi_n.setGeometry(QtCore.QRect(70, 50, 41, 20))\n self.lineEdit_dmi_n.setObjectName(\"lineEdit_dmi_n\")\n self.lineEdit_dmi_m = QtWidgets.QLineEdit(self.groupBox_7)\n self.lineEdit_dmi_m.setEnabled(False)\n self.lineEdit_dmi_m.setGeometry(QtCore.QRect(190, 50, 41, 20))\n self.lineEdit_dmi_m.setObjectName(\"lineEdit_dmi_m\")\n self.label_17 = QtWidgets.QLabel(self.groupBox_7)\n self.label_17.setGeometry(QtCore.QRect(40, 50, 31, 16))\n self.label_17.setObjectName(\"label_17\")\n self.label_18 = QtWidgets.QLabel(self.groupBox_7)\n self.label_18.setGeometry(QtCore.QRect(170, 50, 21, 16))\n self.label_18.setObjectName(\"label_18\")\n self.checkBox_dmi = QtWidgets.QCheckBox(self.groupBox_7)\n self.checkBox_dmi.setGeometry(QtCore.QRect(30, 30, 71, 16))\n self.checkBox_dmi.setObjectName(\"checkBox_dmi\")\n self.tabWidget.addTab(self.tab_para, \"\")\n self.tab_plot = QtWidgets.QWidget()\n self.tab_plot.setObjectName(\"tab_plot\")\n self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.tab_plot)\n self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)\n self.verticalLayout_3.setObjectName(\"verticalLayout_3\")\n self.verticalLayout = QtWidgets.QVBoxLayout()\n self.verticalLayout.setContentsMargins(-1, -1, -1, 0)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.horizontalLayout_plot_field = QtWidgets.QHBoxLayout()\n self.horizontalLayout_plot_field.setObjectName(\"horizontalLayout_plot_field\")\n self.label_para = QtWidgets.QLabel(self.tab_plot)\n self.label_para.setFrameShape(QtWidgets.QFrame.Box)\n self.label_para.setObjectName(\"label_para\")\n self.horizontalLayout_plot_field.addWidget(self.label_para)\n self.label_point = QtWidgets.QLabel(self.tab_plot)\n self.label_point.setFrameShape(QtWidgets.QFrame.Box)\n self.label_point.setObjectName(\"label_point\")\n self.horizontalLayout_plot_field.addWidget(self.label_point)\n self.label_file = QtWidgets.QLabel(self.tab_plot)\n self.label_file.setFrameShape(QtWidgets.QFrame.Box)\n self.label_file.setObjectName(\"label_file\")\n self.horizontalLayout_plot_field.addWidget(self.label_file)\n self.verticalLayout.addLayout(self.horizontalLayout_plot_field)\n self.verticalLayout_3.addLayout(self.verticalLayout)\n self.tabWidget.addTab(self.tab_plot, \"\")\n self.verticalLayout_2.addWidget(self.tabWidget)\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n self.tabWidget.setCurrentIndex(0)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n self.groupBox_3.setTitle(_translate(\"MainWindow\", \"MACD参数\"))\n self.label.setText(_translate(\"MainWindow\", \"Short\"))\n self.lineEdit_macd_short.setText(_translate(\"MainWindow\", \"12\"))\n self.label_2.setText(_translate(\"MainWindow\", \"Long\"))\n self.lineEdit_macd_long.setText(_translate(\"MainWindow\", \"26\"))\n self.label_3.setText(_translate(\"MainWindow\", \"M\"))\n self.lineEdit_macd_m.setText(_translate(\"MainWindow\", \"9\"))\n self.checkBox_macd.setText(_translate(\"MainWindow\", \"MACD\"))\n self.groupBox_2.setTitle(_translate(\"MainWindow\", \"MA参数\"))\n self.label_5.setText(_translate(\"MainWindow\", \"N1\"))\n self.label_7.setText(_translate(\"MainWindow\", \"N3\"))\n self.lineEdit_ma_n3.setText(_translate(\"MainWindow\", \"20\"))\n self.lineEdit_ma_n2.setText(_translate(\"MainWindow\", \"10\"))\n self.label_6.setText(_translate(\"MainWindow\", \"N2\"))\n self.lineEdit_ma_n1.setText(_translate(\"MainWindow\", \"5\"))\n self.label_8.setText(_translate(\"MainWindow\", \"N4\"))\n self.lineEdit_ma_n4.setText(_translate(\"MainWindow\", \"30\"))\n self.label_9.setText(_translate(\"MainWindow\", \"N5\"))\n self.lineEdit_ma_n5.setText(_translate(\"MainWindow\", \"50\"))\n self.label_10.setText(_translate(\"MainWindow\", \"算法\"))\n self.comboBox_ma.setItemText(0, _translate(\"MainWindow\", \"MA\"))\n self.comboBox_ma.setItemText(1, _translate(\"MainWindow\", \"EMA\"))\n self.checkBox_ma.setText(_translate(\"MainWindow\", \"MA\"))\n self.groupBox_5.setTitle(_translate(\"MainWindow\", \"回测文件\"))\n self.pushButton_opr_file.setText(_translate(\"MainWindow\", \"打开\"))\n self.label_opr.setText(_translate(\"MainWindow\", \"TextLabel\"))\n self.groupBox_4.setTitle(_translate(\"MainWindow\", \"公共参数\"))\n self.lineEdit_contract.setText(_translate(\"MainWindow\", \"RB1810\"))\n self.label_4.setText(_translate(\"MainWindow\", \"周期\"))\n self.label_12.setText(_translate(\"MainWindow\", \"合约\"))\n self.comboBox_bar.setItemText(0, _translate(\"MainWindow\", \"3600\"))\n self.comboBox_bar.setItemText(1, _translate(\"MainWindow\", \"1800\"))\n self.comboBox_bar.setItemText(2, _translate(\"MainWindow\", \"900\"))\n self.comboBox_bar.setItemText(3, _translate(\"MainWindow\", \"600\"))\n self.comboBox_bar.setItemText(4, _translate(\"MainWindow\", \"300\"))\n self.comboBox_bar.setItemText(5, _translate(\"MainWindow\", \"60\"))\n self.comboBox_bar.setItemText(6, _translate(\"MainWindow\", \"0\"))\n self.label_13.setText(_translate(\"MainWindow\", \"开始时间\"))\n self.label_14.setText(_translate(\"MainWindow\", \"结束时间\"))\n self.pushButton_set_para.setText(_translate(\"MainWindow\", \"画图\"))\n self.groupBox_6.setTitle(_translate(\"MainWindow\", \"KDJ参数\"))\n self.lineEdit_kdj_n.setText(_translate(\"MainWindow\", \"9\"))\n self.lineEdit_kdj_m1.setText(_translate(\"MainWindow\", \"3\"))\n self.lineEdit_kdj_m2.setText(_translate(\"MainWindow\", \"3\"))\n self.label_11.setText(_translate(\"MainWindow\", \"N\"))\n self.label_15.setText(_translate(\"MainWindow\", \"M1\"))\n self.label_16.setText(_translate(\"MainWindow\", \"M2\"))\n self.checkBox_kdj.setText(_translate(\"MainWindow\", \"KDJ\"))\n self.groupBox_7.setTitle(_translate(\"MainWindow\", \"DMI参数\"))\n self.lineEdit_dmi_n.setText(_translate(\"MainWindow\", \"14\"))\n self.lineEdit_dmi_m.setText(_translate(\"MainWindow\", \"6\"))\n self.label_17.setText(_translate(\"MainWindow\", \"N\"))\n self.label_18.setText(_translate(\"MainWindow\", \"M\"))\n self.checkBox_dmi.setText(_translate(\"MainWindow\", \"DMI\"))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_para), _translate(\"MainWindow\", \"参数设置\"))\n self.label_para.setText(_translate(\"MainWindow\", \"TextLabel\"))\n self.label_point.setText(_translate(\"MainWindow\", \"TextLabel\"))\n self.label_file.setText(_translate(\"MainWindow\", \"TextLabel\"))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_plot), _translate(\"MainWindow\", \"行情\"))\n\n" }, { "alpha_fraction": 0.4893767833709717, "alphanum_fraction": 0.49433428049087524, "avg_line_length": 23.34482765197754, "blob_id": "ee684268e2f38233b194c4e37f4ab8fb11ae231a", "content_id": "c45e3aa9ae0d3e7564f66d5742b3ec597a0aee75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3128, "license_type": "no_license", "max_line_length": 99, "num_lines": 116, "path": "/indexer.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n指标类,用于管理指标相内容:\n1.参数,包括参数控件的内容\n para_name:参数名列表\n para_dic: 参数字典,键为参数名,值为参数值\n para_widgets_dic: 参数按键字典, 键为参数名,值为控件名\n2.数据\n data_dic:数据字典,键为参数名,值为数据\n3.画图\n plt:主图控件\n plt_dic:子图控件字典,键为参数名,值为子图控件\n\n\"\"\"\nclass IndexerBase(object):\n\n color_list = ['w', 'y', 'c', 'r', 'g']\n\n def __init__(self, plt, ):\n self.is_avtived = True\n self.plt = plt\n self.para_name = []\n self.para_dic = {}\n self.para_widgets_dic = {}\n\n self.data_dic = {}\n\n self.plt_dic = {}\n\n pass\n\n def draw(self):\n pass\n\n def reflesh(self):\n pass\n\n def set_data(self):\n pass\n\n def set_all_para(self):\n for k, v in self.para_widgets_dic.items():\n p = self.set_para(v)\n if p:\n self.para_dic[k] = p\n else:\n self.para_dic[k] = 0\n self.set_data()\n\n def set_para(self, lindEdit_widgets):\n t = lindEdit_widgets.text()\n if t:\n try:\n p=int(t)\n return p\n except:\n print (u\"请检查输入内容,只接受数字\")\n return None\n\n def get_indexer_value_text(self, pos):\n # 根据传入的位置返回一个指标值的字符串\n t = \"\"\n i = 0\n for pname in self.para_name:\n c = self.color_list[i]\n t += \"<span style='color: %s'>%s=%0.3f </span>\" % (c, pname, self.data_dic[pname][pos])\n i += 1\n return t\n\nclass Indexer_MA(IndexerBase):\n\n def __init__(self, plt, rawdata, para_widgets_list):\n super(IndexerBase, self).__init__()\n self.plt = plt\n self.is_avtived = True\n self.plt = plt\n self.para_name = []\n self.para_dic = {}\n self.para_widgets_dic = {}\n\n self.data_dic = {}\n\n self.plt_dic = {}\n\n self.para_name = ['N1', 'N2', 'N3', 'N4', 'N5']\n\n # 获取原始数据\n self.series_close = rawdata['close']\n\n # 获取参数\n for i in range(len(para_widgets_list)):\n para_name = self.para_name[i]\n pwidget = para_widgets_list[i]\n self.para_widgets_dic[para_name] = pwidget\n self.set_all_para()\n\n # 准备数据\n self.set_data()\n\n pass\n\n def draw(self):\n if self.is_avtived:\n for i in range(len(self.para_name)):\n pname = self.para_name[i]\n if pname in self.para_dic.keys():\n self.plt_dic[pname]=self.plt.plot(name=pname,pen=self.color_list[i])\n self.plt_dic[pname].setData(self.data_dic[pname])\n\n def reflesh(self):\n for k, d in self.data_dic.items():\n self.plt_dic[k].setData(d)\n\n def set_data(self,):\n for k, d in self.para_dic.items():\n self.data_dic[k] = self.series_close.rolling(d).mean()\n" }, { "alpha_fraction": 0.6806819438934326, "alphanum_fraction": 0.7079861760139465, "avg_line_length": 59, "blob_id": "07b462f13d517fac620d69240f319c456e399206", "content_id": "13fb2a7c8772bcbca23479f804747cade8113772", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7865, "license_type": "no_license", "max_line_length": 128, "num_lines": 130, "path": "/complex2.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#from PySide import QtCore, QtGui\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(803, 600)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)\n self.tabWidget.setGeometry(QtCore.QRect(0, 0, 801, 551))\n self.tabWidget.setObjectName(\"tabWidget\")\n self.tab = QtWidgets.QWidget()\n self.tab.setObjectName(\"tab\")\n self.tabWidget_2 = QtWidgets.QTabWidget(self.tab)\n self.tabWidget_2.setGeometry(QtCore.QRect(0, 0, 801, 531))\n self.tabWidget_2.setObjectName(\"tabWidget_2\")\n self.tab_3 = QtWidgets.QWidget()\n self.tab_3.setObjectName(\"tab_3\")\n self.treeWidget = QtWidgets.QTreeWidget(self.tab_3)\n self.treeWidget.setGeometry(QtCore.QRect(0, 0, 791, 501))\n self.treeWidget.setObjectName(\"treeWidget\")\n item_0 = QtWidgets.QTreeWidgetItem(self.treeWidget)\n item_1 = QtWidgets.QTreeWidgetItem(item_0)\n self.tabWidget_2.addTab(self.tab_3, \"\")\n self.tab_4 = QtWidgets.QWidget()\n self.tab_4.setObjectName(\"tab_4\")\n self.verticalLayoutWidget = QtWidgets.QWidget(self.tab_4)\n self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 791, 501))\n self.verticalLayoutWidget.setObjectName(\"verticalLayoutWidget\")\n self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)\n self.verticalLayout.setContentsMargins(0, 0, 0, 0)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.dateEdit = QtWidgets.QDateEdit(self.verticalLayoutWidget)\n self.dateEdit.setObjectName(\"dateEdit\")\n self.verticalLayout.addWidget(self.dateEdit)\n self.calendarWidget = QtWidgets.QCalendarWidget(self.verticalLayoutWidget)\n self.calendarWidget.setObjectName(\"calendarWidget\")\n self.verticalLayout.addWidget(self.calendarWidget)\n self.tabWidget_2.addTab(self.tab_4, \"\")\n self.tabWidget.addTab(self.tab, \"\")\n self.tab_2 = QtWidgets.QWidget()\n self.tab_2.setObjectName(\"tab_2\")\n self.groupBox = QtWidgets.QGroupBox(self.tab_2)\n self.groupBox.setGeometry(QtCore.QRect(20, 10, 73, 92))\n self.groupBox.setObjectName(\"groupBox\")\n self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.groupBox)\n self.verticalLayout_2.setObjectName(\"verticalLayout_2\")\n self.radioButton = QtWidgets.QRadioButton(self.groupBox)\n self.radioButton.setObjectName(\"radioButton\")\n self.verticalLayout_2.addWidget(self.radioButton)\n self.radioButton_2 = QtWidgets.QRadioButton(self.groupBox)\n self.radioButton_2.setObjectName(\"radioButton_2\")\n self.verticalLayout_2.addWidget(self.radioButton_2)\n self.radioButton_3 = QtWidgets.QRadioButton(self.groupBox)\n self.radioButton_3.setObjectName(\"radioButton_3\")\n self.verticalLayout_2.addWidget(self.radioButton_3)\n self.groupBox_2 = QtWidgets.QGroupBox(self.tab_2)\n self.groupBox_2.setGeometry(QtCore.QRect(440, 30, 321, 151))\n self.groupBox_2.setObjectName(\"groupBox_2\")\n self.widget = QtWidgets.QWidget(self.groupBox_2)\n self.widget.setGeometry(QtCore.QRect(60, 30, 172, 102))\n self.widget.setObjectName(\"widget\")\n self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)\n self.horizontalLayout.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.dial = QtWidgets.QDial(self.widget)\n self.dial.setObjectName(\"dial\")\n self.horizontalLayout.addWidget(self.dial)\n self.lcdNumber = QtWidgets.QLCDNumber(self.widget)\n self.lcdNumber.setObjectName(\"lcdNumber\")\n self.horizontalLayout.addWidget(self.lcdNumber)\n self.fontComboBox = QtWidgets.QFontComboBox(self.tab_2)\n self.fontComboBox.setGeometry(QtCore.QRect(60, 230, 381, 22))\n self.fontComboBox.setObjectName(\"fontComboBox\")\n self.label = QtWidgets.QLabel(self.tab_2)\n self.label.setGeometry(QtCore.QRect(60, 290, 381, 71))\n self.label.setScaledContents(False)\n self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setWordWrap(False)\n self.label.setObjectName(\"label\")\n self.progressBar = QtWidgets.QProgressBar(self.tab_2)\n self.progressBar.setGeometry(QtCore.QRect(60, 480, 661, 23))\n self.progressBar.setProperty(\"value\", 24)\n self.progressBar.setObjectName(\"progressBar\")\n self.tabWidget.addTab(self.tab_2, \"\")\n self.tab_5 = QtWidgets.QWidget()\n self.tab_5.setObjectName(\"tab_5\")\n self.verticalLayoutWidget_2 = QtWidgets.QWidget(self.tab_5)\n self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(-1, -1, 791, 531))\n self.verticalLayoutWidget_2.setObjectName(\"verticalLayoutWidget_2\")\n self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget_2)\n self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)\n self.verticalLayout_3.setObjectName(\"verticalLayout_3\")\n self.tabWidget.addTab(self.tab_5, \"\")\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 803, 23))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n self.tabWidget.setCurrentIndex(1)\n self.tabWidget_2.setCurrentIndex(1)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(QtWidgets.QApplication.translate(\"MainWindow\", \"MainWindow\"))\n self.treeWidget.headerItem().setText(0, QtWidgets.QApplication.translate(\"MainWindow\", u\"第一列\"))\n self.treeWidget.headerItem().setText(1, QtWidgets.QApplication.translate(\"MainWindow\", \"New Column\"))\n __sortingEnabled = self.treeWidget.isSortingEnabled()\n self.treeWidget.setSortingEnabled(False)\n self.treeWidget.topLevelItem(0).setText(0, QtWidgets.QApplication.translate(\"MainWindow\", u\"子条目一\"))\n self.treeWidget.topLevelItem(0).child(0).setText(0, QtWidgets.QApplication.translate(\"MainWindow\", u\"子条目一一\"))\n self.treeWidget.setSortingEnabled(__sortingEnabled)\n self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_3), QtWidgets.QApplication.translate(\"MainWindow\", u\"树\"))\n self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_4), QtWidgets.QApplication.translate(\"MainWindow\", u\"日历\"))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QtWidgets.QApplication.translate(\"MainWindow\", \"Tab 1\"))\n self.groupBox.setTitle(QtWidgets.QApplication.translate(\"MainWindow\", u\"功能选择\"))\n self.radioButton.setText(QtWidgets.QApplication.translate(\"MainWindow\", u\"默认\"))\n self.radioButton_2.setText(QtWidgets.QApplication.translate(\"MainWindow\", u\"重置\"))\n self.radioButton_3.setText(QtWidgets.QApplication.translate(\"MainWindow\", u\"选项3\"))\n self.groupBox_2.setTitle(QtWidgets.QApplication.translate(\"MainWindow\", u\"移动刻度盘\"))\n self.label.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"TextLabel\"))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), QtWidgets.QApplication.translate(\"MainWindow\", \"Tab 2\"))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_5), QtWidgets.QApplication.translate(\"MainWindow\", \"绘图\"))\n\n" }, { "alpha_fraction": 0.5655339956283569, "alphanum_fraction": 0.5819174647331238, "avg_line_length": 32.7508544921875, "blob_id": "8411097e24747c7d6ffe50fd869f4262ef02a253", "content_id": "ac3a3caa277fa2bbb6949ea92f79656eca23856f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10182, "license_type": "no_license", "max_line_length": 115, "num_lines": 293, "path": "/complexExample.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport complex2\nfrom PyQt5 import QtCore, QtWidgets, QtGui\nimport sys\nimport time\nimport pyqtgraph as pg\nimport pandas as pd\nimport tushare as ts\nimport datetime\nfrom matplotlib.pylab import date2num\n\n\nclass MainWindow(object):\n def __init__(self):\n app = QtWidgets.QApplication(sys.argv)\n MainWindow = QtWidgets.QMainWindow()\n self.ui = complex2.Ui_MainWindow()\n self.ui.setupUi(MainWindow)\n\n self.update_date()\n self.update_calendar()\n self.set_lcd()\n self.set_dial()\n\n #self.zero_progress()\n #self.click_radio3()\n self.update_progressbar()\n\n self.set_font()\n\n # 数据要解好,供多个用,这样才省事\n #hist_data = ts.get_hist_data('600519', start='2010-05-01', end='2017-11-04')\n #hist_data.to_csv('hist_data.csv')\n hist_data = pd.read_csv('hist_data.csv')\n self.t = range(hist_data.shape[0])\n self.open = hist_data.open.tolist()\n self.high = hist_data.high.tolist()\n self.low = hist_data.low.tolist()\n self.close = hist_data.close.tolist()\n packdate = zip(self.t,self.open, self.close, self.low, self.high)\n ma5 = hist_data.close.rolling(5).mean().tolist()\n self.plt1 = self.chart(hist_data['date'].tolist(),packdate)\n self.plt2 = self.chart2(self.t, self.close)\n self.plt1.plot(ma5)\n\n # 下面第2个图的范围设置框\n self.region = pg.LinearRegionItem()\n self.region.setZValue(10)\n self.region.sigRegionChanged.connect(self.update_plt1)\n\n self.plt1.sigRangeChanged.connect(self.updateRegion)\n\n self.region.setRegion([0, 100])\n # Add the LinearRegionItem to the ViewBox, but tell the ViewBox to exclude this\n # item when doing auto-range calculations.\n self.plt2.addItem(self.region, ignoreBounds=True)\n\n self.ui.verticalLayout_3.addWidget(self.plt1)\n self.ui.verticalLayout_3.addWidget(self.plt2)\n MainWindow.show()\n sys.exit(app.exec_())\n\n def update_date(self):\n self.ui.dateEdit.setDate(self.ui.calendarWidget.selectedDate())\n\n def update_calendar(self):\n self.ui.calendarWidget.selectionChanged.connect(self.update_date)\n\n def set_lcd(self):\n self.ui.lcdNumber.display(self.ui.dial.value())\n\n def set_dial(self):\n self.ui.dial.valueChanged['int'].connect(self.set_lcd)\n\n #按钮2重置进度栏\n def zero_progress(self):\n self.ui.radioButton_2.clicked.connect(self.ui.progressBar.reset)\n\n def update_progress(self):\n value = self.ui.lcdNumber.value()\n self.ui.progressBar.setValue(value)\n\n def click_radio3(self):\n self.ui.radioButton_3.clicked.connect(self.update_progress)\n\n def set_font(self):\n self.ui.fontComboBox.activated['QString'].connect(self.ui.label.setText)\n\n def progressBar_counter(self, start_value=0):\n self.run_thread = RunThread(parent=None, counter_start=start_value)\n self.run_thread.start()\n self.run_thread.counter_value.connect(self.set_progressbar)\n\n def set_progressbar(self, counter):\n if not self.stop_progress:\n self.ui.progressBar.setValue(counter)\n\n # 多进程的方式控制progressBar\n # RunThread会一直计时,并发出int类型的信号\n # start_progressbar开始时,会先取得progressbar的值,然后再往下数,这样ui上看起来progressbar是连着上一次中断的位置往下的\n # 实际上点stop的时候,RunThread进程已经结束,重新开始时是新的线程了\n def update_progressbar(self):\n self.ui.radioButton.clicked.connect(self.start_progressbar)\n self.ui.radioButton_2.clicked.connect(self.stop_progressbar)\n self.ui.radioButton_3.clicked.connect(self.reset_progressbar)\n self.progress_value = 0\n self.stop_progress = False\n\n def start_progressbar(self):\n self.stop_progress = False\n self.progress_value = self.ui.progressBar.value()\n self.progressBar_counter(self.progress_value)\n\n def stop_progressbar(self):\n self.stop_progress = True\n try:\n self.run_thread.stop()\n except:\n pass\n\n def reset_progressbar(self):\n self.progress_value = 0\n self.ui.progressBar.reset()\n #self.stop_progress = False\n self.stop_progressbar()\n\n def chart(self,date_list, data_list):\n \"\"\"\n data_list = []\n i = 0\n for dates, row in hist_data.iterrows():\n #date_time = datetime.datetime.strptime(dates, \"%Y-%m-%d\")\n #t = date2num(date_time)\n open, high, close, low = row[:4]\n datas = (i, open, close, low, high)\n i+=1\n data_list.append(datas)\n # axis_dic = dict(enumerate(axis))\n #print (data_list)\n \"\"\"\n item = CandlestickItem(data_list)\n axis = DateAxis(date_strings=date_list, orientation='bottom')\n plt = pg.PlotWidget(axisItems={'bottom': axis})\n #plt = pg.PlotWidget()\n plt.addItem(item, )\n # plt.setXRange()\n plt.showGrid(x=True, y=True)\n return plt\n\n def chart2(self,x,y):\n #y = hist_data['close'].tolist()\n #x_datas =hist_data.index.tolist()\n #x=range(len(y))\n #for x1 in x_datas:\n # date_time = datetime.datetime.strptime(x1, \"%Y-%m-%d\")\n # x.append(date2num(date_time))\n # axis_dic = dict(enumerate(axis))\n #print (close_list)\n plt = pg.PlotWidget()\n plt.addLegend() # 加上图标\n plt.plot(x=x,y=y, pen=\"w\", name='close')\n #plt.addItem(item, )\n # plt.setXRange()\n #plt.showGrid(x=True, y=True)\n return plt\n\n def update_plt1(self):\n self.region.setZValue(10)\n minX, maxX = self.region.getRegion()\n\n #Y轴自适应\n int_minY = max(0,int(minX))\n int_maxY = max(1, int(maxX))\n minY = min(self.low[int_minY:int_maxY]) - 5\n maxY = max(self.high[int_minY:int_maxY]) +5\n self.plt1.setYRange(minY, maxY)\n\n self.plt1.setXRange(minX, maxX, padding=0)\n\n\n def updateRegion(self,window, viewRange):\n rgn = viewRange[0]\n self.region.setRegion(rgn)\n\nclass RunThread(QtCore.QThread):\n # 定义一个信号,内容为int\n counter_value = QtCore.pyqtSignal(int)\n\n def __init__(self, parent=None, counter_start=0):\n super(RunThread, self).__init__(parent)\n self.counter = counter_start\n self.is_running = True\n\n def run(self):\n while self.counter < 100 and self.is_running == True:\n time.sleep(0.1)\n self.counter += 1\n print (self.counter)\n self.counter_value.emit(self.counter) # 发出信号\n\n def stop(self):\n self.is_running = False\n print (\"线程停止中...\")\n self.terminate()\n\nclass DateAxis(pg.AxisItem):\n\n def __init__(self, date_strings, orientation):\n pg.AxisItem.__init__(self,orientation)\n self.date_strings = date_strings\n self.len = len(self.date_strings)\n def tickStrings(self, values, scale, spacing):\n \"\"\"\n strns = []\n rng = max(values) - min(values)\n # if rng < 120:\n # return pg.AxisItem.tickStrings(self, values, scale, spacing)\n if rng < 3600 * 24:\n string = '%H:%M:%S'\n label1 = '%b %d -'\n label2 = ' %b %d, %Y'\n elif rng >= 3600 * 24 and rng < 3600 * 24 * 30:\n string = '%d'\n label1 = '%b - '\n label2 = '%b, %Y'\n elif rng >= 3600 * 24 * 30 and rng < 3600 * 24 * 30 * 24:\n string = '%b'\n label1 = '%Y -'\n label2 = ' %Y'\n elif rng >= 3600 * 24 * 30 * 24:\n string = '%Y'\n label1 = ''\n label2 = ''\n for x in values:\n try:\n strns.append(time.strftime(string, time.localtime(x)))\n except ValueError: ## Windows can't handle dates before 1970\n strns.append('')\n try:\n label = time.strftime(label1, time.localtime(min(values))) + time.strftime(label2,\n time.localtime(max(values)))\n except ValueError:\n label = ''\n # self.setLabel(text=label)\n return strns\n \"\"\"\n #print values\n strns = []\n for x in values:\n x1 = int(x)\n if 0 <= x1 < self.len:\n strns.append(self.date_strings[x1])\n else:\n strns.append('')\n return strns\n\n## Create a subclass of GraphicsObject.\n## The only required methods are paint() and boundingRect()\n## (see QGraphicsItem documentation)\nclass CandlestickItem(pg.GraphicsObject):\n def __init__(self, data):\n pg.GraphicsObject.__init__(self)\n self.data = data ## data must have fields: time, open, close, min, max\n self.generatePicture()\n\n def generatePicture(self):\n ## pre-computing a QPicture object allows paint() to run much more quickly,\n ## rather than re-drawing the shapes every time.\n self.picture = QtGui.QPicture()\n p = QtGui.QPainter(self.picture)\n p.setPen(pg.mkPen('w'))\n w = (self.data[1][0] - self.data[0][0]) / 3.\n for (t, open, close, min, max) in self.data:\n p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))\n if open > close:\n p.setBrush(pg.mkBrush('r'))\n else:\n p.setBrush(pg.mkBrush('g'))\n p.drawRect(QtCore.QRectF(t - w, open, w * 2, close - open))\n p.end()\n\n def paint(self, p, *args):\n p.drawPicture(0, 0, self.picture)\n\n def boundingRect(self):\n ## boundingRect _must_ indicate the entire area that will be drawn on\n ## or else we will get artifacts and possibly crashing.\n ## (in this case, QPicture does all the work of computing the bouning rect for us)\n return QtCore.QRectF(self.picture.boundingRect())\n\nif __name__=='__main__':\n MainWindow()" }, { "alpha_fraction": 0.6704545617103577, "alphanum_fraction": 0.6912878751754761, "avg_line_length": 28.38888931274414, "blob_id": "cc8e094f855d33e69dbdca56d14ba65bc4e94162", "content_id": "f955ac377eff31fc87e68435b84bfa4f07ff4675", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 540, "license_type": "no_license", "max_line_length": 68, "num_lines": 18, "path": "/decouple_window.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport nullWindow\nfrom PyQt5 import QtCore, QtWidgets, QtGui\n\nif __name__=='__main__':\n import sys\n app = QtWidgets.QApplication(sys.argv)\n MainWindow = QtWidgets.QMainWindow()\n ui = nullWindow.Ui_MainWindow()\n ui.setupUi(MainWindow)\n\n ui.tableWidget.setItem(0,0,QtWidgets.QTableWidgetItem(u'数据1'))\n ui.tableWidget.setItem(1, 1, QtWidgets.QTableWidgetItem(u'数据2'))\n ui.tableWidget.setItem(2, 2, QtWidgets.QTableWidgetItem(u'数据3'))\n\n MainWindow.show()\n sys.exit(app.exec_())" }, { "alpha_fraction": 0.5329869985580444, "alphanum_fraction": 0.5527272820472717, "avg_line_length": 32.18965530395508, "blob_id": "826e418e2929ecda1e1e0994dc53627c76288319", "content_id": "13922de1de41a8bee071f94f281725c948f872c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1975, "license_type": "no_license", "max_line_length": 80, "num_lines": 58, "path": "/Indexer/HullRsi.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom IndexerBase import IndexerBase\nimport numpy as np\nimport talib\n\n\nclass HULL_RSI(IndexerBase):\n indexer_name = 'HULL_RSI'\n indexer_name_list = ['RSI']\n default_para_dic = {\n 'N1': 5,\n 'M1': 5,\n 'M2': 9,\n 'N': 8\n }\n\n def __init__(self, raw_data, plt):\n super(HULL_RSI, self).__init__(raw_data, plt)\n self.indexer_name_list = ['RSI'] # MA的指标名和参数名都跟参数有关,所以要随参数进行设置\n self.indexer_color_dic = {\n 'RSI': 'blue'\n }\n\n def calculate_indexer_value(self):\n n1 = self.para_dic['N1']\n m1 = self.para_dic['M1']\n m2 = self.para_dic['M2']\n n = self.para_dic['N']\n close_array = np.array(self.raw_data['close'].values, dtype='float')\n n = float(n)\n rsi_data = talib.RSI(close_array, n1)\n rsi_ema1 = talib.EMA(rsi_data, m1)\n rsi_ema2 = talib.EMA(rsi_ema1, m2)\n rsi_new = rsi_ema1 - rsi_ema2\n n_2 = round(n / 2, 0)\n n_squr = round(np.sqrt(n), 0)\n wma1 = talib.MA(rsi_new, n, matype=2)\n wma2 = talib.MA(rsi_new, n_2, matype=2)\n x = wma2 * 2 - wma1\n hull_ma = talib.MA(x, n_squr, matype=2)\n self.indexer_value_dic['RSI'] = hull_ma\n\n def draw_indexer(self):\n i = 0\n for indexer_name, values in self.indexer_value_dic.items():\n c = self.indexer_color_dic[indexer_name][0]\n self.plt_dic[indexer_name] = self.plt.plot(name=indexer_name, pen=c)\n self.plt_dic[indexer_name].setData(values)\n i += 1\n\n def re_draw_indexer(self):\n for pname, values in self.indexer_value_dic.items():\n self.plt_dic[pname].setData(values)\n\n def get_polar_value(self,start_pos, end_pos):\n max_v = max(self.indexer_value_dic['RSI'][start_pos:end_pos])\n min_v = min(self.indexer_value_dic['RSI'][start_pos:end_pos])\n return max_v, min_v\n" }, { "alpha_fraction": 0.4879906177520752, "alphanum_fraction": 0.5131810307502747, "avg_line_length": 39.64285659790039, "blob_id": "bbf023c9cf24340fbce49390d41c848b6f011f03", "content_id": "1b32ee20e4b260060dc3f0c23fa47f6bf93c7f00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3464, "license_type": "no_license", "max_line_length": 93, "num_lines": 84, "path": "/Indexer/DMI.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom IndexerBase import IndexerBase\nimport numpy as np\nimport pandas as pd\n\nclass DMI(IndexerBase):\n indexer_name = 'DMI'\n indexer_name_list = ['PDI', 'MDI', 'ADX', 'ADXR']\n default_para_dic = {\n 'N': 14,\n 'M': 6,\n }\n\n def __init__(self, raw_data, plt):\n super(DMI, self).__init__(raw_data, plt)\n self.indexer_name_list = ['PDI', 'MDI', 'ADX', 'ADXR'] # MA的指标名和参数名都跟参数有关,所以要随参数进行设置\n self.indexer_color_dic = {\n 'PDI': 'blue',\n 'MDI': 'magenta',\n 'ADX': 'cyan',\n 'ADXR': 'green'\n }\n\n def calculate_indexer_value(self):\n n = self.para_dic['N']\n m = self.para_dic['M']\n high = self.raw_data.high\n print ('high')\n low = self.raw_data.low\n close = self.raw_data.close\n closeshift1 = close.shift(1).fillna(0)\n c = high - low\n d = high - closeshift1\n df1 = pd.DataFrame({'c': c, 'd': d})\n df1['A'] = df1.max(axis=1)\n df1.drop('c', axis=1, inplace=True)\n df1.drop('d', axis=1, inplace=True)\n df1['B'] = np.abs(low - closeshift1)\n df1['C'] = df1.max(axis=1)\n df1['TR'] = df1['C'].rolling(n).sum()\n HD = high - high.shift(1).fillna(0)\n LD = low.shift(1).fillna(0) - low\n df1['HD'] = HD\n df1['LD'] = LD\n df2 = pd.DataFrame({'HD': HD, 'LD': LD})\n df2['DMP_1'] = df2[(df2['HD'] > df2['LD']) & (df2['HD'] > 0)]['HD']\n df2['DMM_1'] = df2[(df2['LD'] > df2['HD']) & (df2['LD'] > 0)]['LD']\n df2 = df2.fillna(0)\n df1['DMP'] = df2['DMP_1'].rolling(n).sum()\n df1['DMM'] = df2['DMM_1'].rolling(n).sum()\n del df2\n df1['PDI'] = df1['DMP'] * 100 / df1['TR']\n df1['MDI'] = df1['DMM'] * 100 / df1['TR']\n adx = np.abs(df1['MDI'] - df1['PDI']) / (df1['MDI'] + df1['PDI']) * 100\n print (\"pre adx\")\n df1['ADX'] = adx.rolling(m).mean()\n df1['ADXR'] = (df1['ADX'] + df1['ADX'].shift(m).fillna(0)) / 2\n self.indexer_value_dic['PDI'] = df1['PDI'].tolist()\n self.indexer_value_dic['MDI'] = df1['MDI'].tolist()\n self.indexer_value_dic['ADX'] = df1['ADX'].tolist()\n self.indexer_value_dic['ADXR'] = df1['ADXR'].tolist()\n\n def draw_indexer(self):\n i = 0\n for indexer_name, values in self.indexer_value_dic.items():\n c = self.indexer_color_dic[indexer_name][0]\n self.plt_dic[indexer_name] = self.plt.plot(name=indexer_name, pen=c)\n self.plt_dic[indexer_name].setData(values)\n i += 1\n\n def re_draw_indexer(self):\n for pname, values in self.indexer_value_dic.items():\n self.plt_dic[pname].setData(values)\n\n def get_polar_value(self,start_pos, end_pos):\n max_v = max(max(self.indexer_value_dic['PDI'][start_pos:end_pos]),\n max(self.indexer_value_dic['MDI'][start_pos:end_pos]),\n max(self.indexer_value_dic['ADX'][start_pos:end_pos]),\n max(self.indexer_value_dic['ADXR'][start_pos:end_pos]))\n min_v = min(min(self.indexer_value_dic['PDI'][start_pos:end_pos]),\n min(self.indexer_value_dic['MDI'][start_pos:end_pos]),\n min(self.indexer_value_dic['ADX'][start_pos:end_pos]),\n min(self.indexer_value_dic['ADXR'][start_pos:end_pos]))\n return max_v, min_v\n" }, { "alpha_fraction": 0.6822230219841003, "alphanum_fraction": 0.7115544676780701, "avg_line_length": 60.45985412597656, "blob_id": "80d40e570d0e89b5e0313a3c519724f789495fbb", "content_id": "10f461c66bc57497b1c337d64b36eb7d4eaa9b0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8485, "license_type": "no_license", "max_line_length": 161, "num_lines": 137, "path": "/complex.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'complex.ui'\n#\n# Created: Sat Jul 14 20:48:01 2018\n# by: pyside-uic 0.2.15 running on PySide 1.2.4\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PySide import QtCore, QtGui\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(803, 600)\n self.centralwidget = QtGui.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.tabWidget = QtGui.QTabWidget(self.centralwidget)\n self.tabWidget.setGeometry(QtCore.QRect(0, 0, 801, 551))\n self.tabWidget.setObjectName(\"tabWidget\")\n self.tab = QtGui.QWidget()\n self.tab.setObjectName(\"tab\")\n self.tabWidget_2 = QtGui.QTabWidget(self.tab)\n self.tabWidget_2.setGeometry(QtCore.QRect(0, 0, 801, 531))\n self.tabWidget_2.setObjectName(\"tabWidget_2\")\n self.tab_3 = QtGui.QWidget()\n self.tab_3.setObjectName(\"tab_3\")\n self.treeWidget = QtGui.QTreeWidget(self.tab_3)\n self.treeWidget.setGeometry(QtCore.QRect(0, 0, 791, 501))\n self.treeWidget.setObjectName(\"treeWidget\")\n item_0 = QtGui.QTreeWidgetItem(self.treeWidget)\n item_1 = QtGui.QTreeWidgetItem(item_0)\n self.tabWidget_2.addTab(self.tab_3, \"\")\n self.tab_4 = QtGui.QWidget()\n self.tab_4.setObjectName(\"tab_4\")\n self.verticalLayoutWidget = QtGui.QWidget(self.tab_4)\n self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 791, 501))\n self.verticalLayoutWidget.setObjectName(\"verticalLayoutWidget\")\n self.verticalLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget)\n self.verticalLayout.setContentsMargins(0, 0, 0, 0)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.dateEdit = QtGui.QDateEdit(self.verticalLayoutWidget)\n self.dateEdit.setObjectName(\"dateEdit\")\n self.verticalLayout.addWidget(self.dateEdit)\n self.calendarWidget = QtGui.QCalendarWidget(self.verticalLayoutWidget)\n self.calendarWidget.setObjectName(\"calendarWidget\")\n self.verticalLayout.addWidget(self.calendarWidget)\n self.tabWidget_2.addTab(self.tab_4, \"\")\n self.tabWidget.addTab(self.tab, \"\")\n self.tab_2 = QtGui.QWidget()\n self.tab_2.setObjectName(\"tab_2\")\n self.groupBox = QtGui.QGroupBox(self.tab_2)\n self.groupBox.setGeometry(QtCore.QRect(20, 10, 73, 92))\n self.groupBox.setObjectName(\"groupBox\")\n self.verticalLayout_2 = QtGui.QVBoxLayout(self.groupBox)\n self.verticalLayout_2.setObjectName(\"verticalLayout_2\")\n self.radioButton = QtGui.QRadioButton(self.groupBox)\n self.radioButton.setObjectName(\"radioButton\")\n self.verticalLayout_2.addWidget(self.radioButton)\n self.radioButton_2 = QtGui.QRadioButton(self.groupBox)\n self.radioButton_2.setObjectName(\"radioButton_2\")\n self.verticalLayout_2.addWidget(self.radioButton_2)\n self.radioButton_3 = QtGui.QRadioButton(self.groupBox)\n self.radioButton_3.setObjectName(\"radioButton_3\")\n self.verticalLayout_2.addWidget(self.radioButton_3)\n self.groupBox_2 = QtGui.QGroupBox(self.tab_2)\n self.groupBox_2.setGeometry(QtCore.QRect(440, 30, 321, 151))\n self.groupBox_2.setObjectName(\"groupBox_2\")\n self.layoutWidget = QtGui.QWidget(self.groupBox_2)\n self.layoutWidget.setGeometry(QtCore.QRect(60, 30, 172, 102))\n self.layoutWidget.setObjectName(\"layoutWidget\")\n self.horizontalLayout = QtGui.QHBoxLayout(self.layoutWidget)\n self.horizontalLayout.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.dial = QtGui.QDial(self.layoutWidget)\n self.dial.setObjectName(\"dial\")\n self.horizontalLayout.addWidget(self.dial)\n self.lcdNumber = QtGui.QLCDNumber(self.layoutWidget)\n self.lcdNumber.setObjectName(\"lcdNumber\")\n self.horizontalLayout.addWidget(self.lcdNumber)\n self.fontComboBox = QtGui.QFontComboBox(self.tab_2)\n self.fontComboBox.setGeometry(QtCore.QRect(60, 230, 381, 22))\n self.fontComboBox.setObjectName(\"fontComboBox\")\n self.label = QtGui.QLabel(self.tab_2)\n self.label.setGeometry(QtCore.QRect(60, 290, 381, 71))\n self.label.setScaledContents(False)\n self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setWordWrap(False)\n self.label.setObjectName(\"label\")\n self.progressBar = QtGui.QProgressBar(self.tab_2)\n self.progressBar.setGeometry(QtCore.QRect(60, 480, 661, 23))\n self.progressBar.setProperty(\"value\", 24)\n self.progressBar.setObjectName(\"progressBar\")\n self.tabWidget.addTab(self.tab_2, \"\")\n self.tab_5 = QtGui.QWidget()\n self.tab_5.setObjectName(\"tab_5\")\n self.verticalLayoutWidget_2 = QtGui.QWidget(self.tab_5)\n self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(-1, -1, 791, 531))\n self.verticalLayoutWidget_2.setObjectName(\"verticalLayoutWidget_2\")\n self.verticalLayout_3 = QtGui.QVBoxLayout(self.verticalLayoutWidget_2)\n self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)\n self.verticalLayout_3.setObjectName(\"verticalLayout_3\")\n self.tabWidget.addTab(self.tab_5, \"\")\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtGui.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 803, 23))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtGui.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n self.tabWidget.setCurrentIndex(2)\n self.tabWidget_2.setCurrentIndex(1)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(QtGui.QApplication.translate(\"MainWindow\", \"MainWindow\", None, QtGui.QApplication.UnicodeUTF8))\n self.treeWidget.headerItem().setText(0, QtGui.QApplication.translate(\"MainWindow\", \"第一列\", None, QtGui.QApplication.UnicodeUTF8))\n self.treeWidget.headerItem().setText(1, QtGui.QApplication.translate(\"MainWindow\", \"New Column\", None, QtGui.QApplication.UnicodeUTF8))\n __sortingEnabled = self.treeWidget.isSortingEnabled()\n self.treeWidget.setSortingEnabled(False)\n self.treeWidget.topLevelItem(0).setText(0, QtGui.QApplication.translate(\"MainWindow\", \"子条目一\", None, QtGui.QApplication.UnicodeUTF8))\n self.treeWidget.topLevelItem(0).child(0).setText(0, QtGui.QApplication.translate(\"MainWindow\", \"子条目一一\", None, QtGui.QApplication.UnicodeUTF8))\n self.treeWidget.setSortingEnabled(__sortingEnabled)\n self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_3), QtGui.QApplication.translate(\"MainWindow\", \"树\", None, QtGui.QApplication.UnicodeUTF8))\n self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_4), QtGui.QApplication.translate(\"MainWindow\", \"日历\", None, QtGui.QApplication.UnicodeUTF8))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QtGui.QApplication.translate(\"MainWindow\", \"Tab 1\", None, QtGui.QApplication.UnicodeUTF8))\n self.groupBox.setTitle(QtGui.QApplication.translate(\"MainWindow\", \"功能选择\", None, QtGui.QApplication.UnicodeUTF8))\n self.radioButton.setText(QtGui.QApplication.translate(\"MainWindow\", \"默认\", None, QtGui.QApplication.UnicodeUTF8))\n self.radioButton_2.setText(QtGui.QApplication.translate(\"MainWindow\", \"重置\", None, QtGui.QApplication.UnicodeUTF8))\n self.radioButton_3.setText(QtGui.QApplication.translate(\"MainWindow\", \"选项3\", None, QtGui.QApplication.UnicodeUTF8))\n self.groupBox_2.setTitle(QtGui.QApplication.translate(\"MainWindow\", \"移动刻度盘\", None, QtGui.QApplication.UnicodeUTF8))\n self.label.setText(QtGui.QApplication.translate(\"MainWindow\", \"TextLabel\", None, QtGui.QApplication.UnicodeUTF8))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), QtGui.QApplication.translate(\"MainWindow\", \"Tab 2\", None, QtGui.QApplication.UnicodeUTF8))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_5), QtGui.QApplication.translate(\"MainWindow\", \"绘图\", None, QtGui.QApplication.UnicodeUTF8))\n\n" }, { "alpha_fraction": 0.5674102902412415, "alphanum_fraction": 0.5737148523330688, "avg_line_length": 41.081634521484375, "blob_id": "5d36b26b9770ad7d6ef515e080f58953bad2143b", "content_id": "2a6522603f1f246a5c715e800eef9223eb2f2a4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2112, "license_type": "no_license", "max_line_length": 105, "num_lines": 49, "path": "/Indexer/ATR.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom IndexerBase import IndexerBase\nimport numpy as np\n\nclass ATR(IndexerBase):\n indexer_name = 'ATR'\n indexer_name_list = ['ATR', 'TR']\n default_para_dic = {\n 'N': 26,\n }\n\n def __init__(self, raw_data, plt):\n super(ATR, self).__init__(raw_data, plt)\n self.indexer_name_list = ['ATR', 'TR'] # MA的指标名和参数名都跟参数有关,所以要随参数进行设置\n self.indexer_color_dic = {\n 'ATR': 'blue',\n 'TR': 'magenta'\n }\n\n def calculate_indexer_value(self):\n n = self.para_dic['N']\n closeshift1 = self.raw_data.close.shift(1).fillna(0)\n self.raw_data['c'] = self.raw_data.high - self.raw_data.low\n self.raw_data['d'] = np.abs(self.raw_data.high - closeshift1)\n self.raw_data['b'] = np.abs(self.raw_data.low - closeshift1)\n self.raw_data['TR'] = self.raw_data[['c', 'd', 'b']].max(axis=1)\n self.raw_data.loc[self.raw_data['open'] < self.raw_data['close'], 'TR'] = 0 - self.raw_data['TR']\n self.raw_data['ATR'] = np.abs(self.raw_data['TR'].rolling(window=n).mean())\n self.indexer_value_dic['TR'] = self.raw_data['TR'].tolist()\n self.indexer_value_dic['ATR'] = self.raw_data['ATR'].tolist()\n\n def draw_indexer(self):\n i = 0\n for indexer_name, values in self.indexer_value_dic.items():\n c = self.indexer_color_dic[indexer_name][0]\n self.plt_dic[indexer_name] = self.plt.plot(name=indexer_name, pen=c)\n self.plt_dic[indexer_name].setData(values)\n i += 1\n\n def re_draw_indexer(self):\n for pname, values in self.indexer_value_dic.items():\n self.plt_dic[pname].setData(values)\n\n def get_polar_value(self,start_pos, end_pos):\n max_v = max(max(self.indexer_value_dic['ATR'][start_pos:end_pos]),\n max(self.indexer_value_dic['TR'][start_pos:end_pos]))\n min_v = min(min(self.indexer_value_dic['ATR'][start_pos:end_pos]),\n min(self.indexer_value_dic['TR'][start_pos:end_pos]))\n return max_v, min_v\n" }, { "alpha_fraction": 0.5975558161735535, "alphanum_fraction": 0.6200108528137207, "avg_line_length": 37.45138931274414, "blob_id": "fb00456abfd9af238c8b63f921bdb897ff41858d", "content_id": "3e3b6a97a6b2e8983f6dd3ea445c881fead5c017", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17805, "license_type": "no_license", "max_line_length": 115, "num_lines": 432, "path": "/DataInterface/DataInterface.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport pandas as pd\nimport time\nimport os\n\n# 读取中文路径\nCollection_Path = unicode('D:\\\\002 MakeLive\\DataCollection\\\\', 'utf-8')\nPUBLIC_DATA_PATH = unicode('D:\\\\002 MakeLive\\DataCollection\\public data\\\\', 'utf-8')\nRAW_DATA_PATH = unicode('D:\\\\002 MakeLive\\DataCollection\\\\raw data\\\\', 'utf-8')\nTICKS_DATA_PATH = unicode('D:\\\\002 MakeLive\\DataCollection\\\\ticks data\\\\', 'utf-8')\nBAR_DATA_PATH = unicode('D:\\\\002 MakeLive\\DataCollection\\\\bar data\\\\', 'utf-8')\nVOLUME_DATA_PATH = unicode('D:\\\\002 MakeLive\\DataCollection\\\\volume data\\\\', 'utf-8')\n\nTICKS_DATA_START_DATE = '2017-8-17' # 包含了8-17日\nLAST_CONCAT_DATA = '2017-10-17' # 记录上次汇总数据的时间,不包含当天(要再加上一天,要不然后面truncate会不对)\n\nDATA_TYPE_PUBLIC=1\nDATA_TYPE_RAW=2\nDATA_TYPE_TICKS=3\n\n\ndef getTradedates(exchangeid='SHFE', startdate='2016-01-01', enddate='2017-12-30'):\n # 获取交易所的交易日\n # 原文件保存在public data文件夹中\n startutc = float(time.mktime(time.strptime(startdate + ' 00:00:00', \"%Y-%m-%d %H:%M:%S\")))\n endutc = float(time.mktime(time.strptime(enddate + ' 23:59:59', \"%Y-%m-%d %H:%M:%S\")))\n tradedatedf = pd.read_csv(PUBLIC_DATA_PATH + 'TradeDates.csv', index_col='exchange_id')\n df = tradedatedf.loc[(tradedatedf['utc_time'] >= startutc) & (tradedatedf['utc_time'] < endutc)]\n df = df.loc[exchangeid, :]\n df.reset_index(inplace=True)\n df.drop('Unnamed: 0', inplace=True, axis=1)\n return df\n\n\ndef generatDailyClose(dailyK):\n '''获取交易区间时间范围内的交易日和收盘价信息,生成dailyDf'''\n dailyK['date'] = dailyK['strtime'].str.slice(0, 10)\n closegrouped = dailyK['close'].groupby(dailyK['date'])\n utcgrouped = dailyK['utc_time'].groupby(dailyK['date'])\n dailyClose = pd.DataFrame(closegrouped.last())\n dailyClose['preclose'] = dailyClose['close'].shift(1).fillna(0)\n dailyClose['utc_time'] = utcgrouped.last()\n return dailyClose\n\n\n# ---------------------------------------------------------------------------------------------\ndef getBarData(symbol='SHFE.RB', K_MIN=60, starttime='2017-05-01 00:00:00', endtime='2018-01-01 00:00:00'):\n # 读取bar数据\n filename = BAR_DATA_PATH + symbol + '\\\\' + symbol + ' ' + str(K_MIN) + '.csv'\n df = pd.read_csv(filename)\n startutc = float(time.mktime(time.strptime(starttime, \"%Y-%m-%d %H:%M:%S\")))\n endutc = float(time.mktime(time.strptime(endtime, \"%Y-%m-%d %H:%M:%S\")))\n '''\n df.index=pd.to_datetime(df['utc_time'],unit='s')\n df = df.tz_localize(tz='PRC')\n df=df.truncate(before=startdate)\n '''\n df = df.loc[(df['utc_time'] > startutc) & (df['utc_time'] < endutc)]\n df['Unnamed: 0'] = range(0, df.shape[0])\n # df.drop('Unnamed: 0.1', inplace=True,axis=1)\n df.reset_index(drop=True, inplace=True)\n # print 'get data success '+symbol+str(K_MIN)+startdate\n return df\n\n\ndef getBarBySymbol(domain_symbol, symbol, bar_type, starttime=None, endtime=None):\n # 取单个主力合约的数据\n print (1)\n filename = BAR_DATA_PATH + domain_symbol + '\\\\' + symbol + ' ' + str(bar_type) + '.csv'\n print (filename)\n df = pd.read_csv(filename)\n print (2)\n print (starttime, endtime)\n if starttime:\n startutc = float(time.mktime(time.strptime(starttime, \"%Y-%m-%d %H:%M:%S\")))\n df = df.loc[df['utc_time'] >= startutc]\n if endtime:\n endutc = float(time.mktime(time.strptime(endtime, \"%Y-%m-%d %H:%M:%S\")))\n df = df.loc[df['utc_time'] <= endutc]\n df.reset_index(drop=True, inplace=True)\n return df\n\n\ndef getBarBySymbolList(domain_symbol, symbollist, bar_type, startdate=None, enddate=None, cols=None):\n # 取全部主力合约的数据,以dic的形式返回\n bardic = {}\n startutc = None\n endutc = None\n if startdate:\n # 过滤掉主力结束时间在开始时间之前的,只取主力结束时间在开始时间之后\n startutc = float(time.mktime(time.strptime(startdate + \" 00:00:00\", \"%Y-%m-%d %H:%M:%S\")))\n if enddate:\n # 过滤掉主力开始时间在结束时间之后的,只取主力开始时间在结束时间之前\n endutc = float(time.mktime(time.strptime(enddate + \" 23:59:59\", \"%Y-%m-%d %H:%M:%S\")))\n for symbol in symbollist:\n filename = BAR_DATA_PATH + domain_symbol + '\\\\' + symbol + ' ' + str(bar_type) + '.csv'\n if cols:\n bardf = pd.read_csv(filename)[cols]\n else:\n bardf = pd.read_csv(filename)\n if startutc:\n bardf = bardf.loc[bardf['utc_time'] >= startutc]\n if endutc:\n bardf = bardf.loc[bardf['utc_time'] <= endutc]\n bardic[symbol] = bardf.reset_index(drop=True)\n return bardic\n\ndef getBarDicAfterDomain(symbolinfo, bar_type,cols=None):\n # 取全部主力合约的数据,以dic的形式返回\n domain_symbol = symbolinfo.domain_symbol\n symbollist = symbolinfo.getSymbolList()\n bardic = {}\n startutc , endutc = symbolinfo.getUtcRange()\n for symbol in symbollist:\n domain_utc_start, domain_utc_end = symbolinfo.getSymbolDomainUtc(symbol)\n filename = BAR_DATA_PATH + domain_symbol + '\\\\' + symbol + ' ' + str(bar_type) + '.csv'\n if cols:\n bardf = pd.read_csv(filename)[cols]\n else:\n bardf = pd.read_csv(filename)\n bardf = bardf.loc[bardf['utc_time']>=domain_utc_start] # 只取主力时间之后的数据,以减少总的数据量\n if startutc:\n bardf = bardf.loc[bardf['utc_time'] >= startutc]\n if endutc:\n bardf = bardf.loc[bardf['utc_time'] <= endutc]\n bardic[symbol] = bardf\n return bardic\n\ndef getDomainbarByDomainSymbol(symbollist, bardic, symbolDomaindic):\n # 根据symbolDomaindic中每个合约的时间范围,从bardic中取数组合成主连数据\n # 默认双边的symbol是对得上的,不做检查\n domain_bar = pd.DataFrame()\n barlist = []\n #timestart = time.time()\n for symbol in symbollist:\n utcs = symbolDomaindic[symbol]\n bars = bardic[symbol]\n symbol_domain_start = utcs[0]\n symbol_domain_end = utcs[1]\n bar = bars.loc[(bars['utc_time'] >= symbol_domain_start) & (bars['utc_time'] <= symbol_domain_end)]\n #domain_bar = pd.concat([domain_bar, bar])\n #domain_bar = domain_bar.append(bar)\n barlist.append(bar)\n #timebar = time.time()\n #print (\"timebar %.3f\" % (timebar - timestart))\n domain_bar = pd.concat(barlist)\n #timeconcat = time.time()\n #print (\"timeconcat %.3f\" % (timeconcat - timebar))\n #domain_bar.sort_values('utc_time',inplace=True) # 本来有sort会妥当一点,不过sort比较耗时,就去掉了\n #timesort = time.time()\n #print (\"timesort %.3f\" % (timesort - timeconcat))\n domain_bar.reset_index(drop=True, inplace=True)\n #timeindex = time.time()\n #print (\"timeindex %.3f\" % (timeindex - timeconcat))\n return domain_bar\n\n\ndef getVolumeData(symbol='SHFE.RB', K_MIN=60, starttime='2017-05-01 00:00:00', endtime='2018-01-01 00:00:00'):\n # 读取bar数据\n filename = VOLUME_DATA_PATH + symbol + '\\\\' + symbol + ' ' + str(K_MIN) + '_volume.csv'\n df = pd.read_csv(filename)\n startutc = float(time.mktime(time.strptime(starttime, \"%Y-%m-%d %H:%M:%S\")))\n endutc = float(time.mktime(time.strptime(endtime, \"%Y-%m-%d %H:%M:%S\")))\n df = df.loc[(df['utc_time'] > startutc) & (df['utc_time'] < endutc)]\n df['Unnamed: 0'] = range(0, df.shape[0])\n # df.drop('Unnamed: 0.1', inplace=True,axis=1)\n df.reset_index(drop=True, inplace=True)\n # print 'get data success '+symbol+str(K_MIN)+startdate\n return df\n\n\ndef getTickDateBySymbolDate(domain_symbol='SHFE.RB', symbol='RB1810', date='2018-08-09'):\n file_name = BAR_DATA_PATH + \"%s\\\\TICK_%s\\\\Tick_Data_%s_%s.csv\" % (domain_symbol, symbol, symbol, date)\n tick_data = pd.read_csv(file_name)\n return tick_data\n\n'''\ndef getTickData(symbol='SHFE.RB',K_MIN=60,startdate='2017-05-01',enddate='2018-01-01'):\n\n filename=TICKS_DATA_PATH+symbol+'\\\\'+symbol+'ticks '+str(K_MIN)+'.csv'\n df=pd.read_csv(filename)\n starttime=startdate+\" 00:00:00\"\n endtime= enddate+\" 00:00:00\"\n startutc = float(time.mktime(time.strptime(starttime, \"%Y-%m-%d %H:%M:%S\")))\n endutc = float(time.mktime(time.strptime(endtime,\"%Y-%m-%d %H:%M:%S\")))\n df=df.loc[(df['utc_time']>startutc) & (df['utc_time']<endutc)]\n df['Unnamed: 0'] = range(0, df.shape[0])\n df.drop('Unnamed: 0.1.1',drop=True,inplace=True)\n df.reset_index(drop=True,inplace=True)\n #print 'get data success '+symbol+str(K_MIN)+startdate\n return df\n'''\n\n\ndef getTickByDate(symbol='SHFE.RB', tradedate='2017-08-07'):\n filename = TICKS_DATA_PATH + symbol + '\\\\' + symbol + tradedate + 'ticks.csv'\n df = pd.read_csv(filename)\n return df\n\n\ndef getContractSwaplist(symbol):\n datapath = Collection_Path + 'vitualContract\\\\'\n df = pd.read_csv(datapath + symbol + 'ContractSwap.csv')\n return df\n pass\n\n\n# ----------------------------------------------------------\ndef getCurrentPath():\n '''\n 返回当前文件所在路径\n :return:\n '''\n return os.path.abspath('.')\n\n\ndef getUpperPath(uppernume=1):\n '''\n 返回当前文件所在的上一级路径\n :return:\n '''\n p = '/'.join(['..'] * uppernume)\n return os.path.abspath(p)\n\n\n# -------------------------------------------------------------\ndef getPriceTick(symbol):\n '''\n 查询品种的最小价格变动\n :param symbol:\n :return:\n '''\n contract = pd.read_excel(PUBLIC_DATA_PATH + 'Contract.xlsx', index_col='Contract')\n return contract.ix[symbol, 'price_tick']\n\n\ndef getMultiplier(symbol):\n '''\n 查询品种的合约乘数\n :param symbol:\n :return:\n '''\n contract = pd.read_excel(PUBLIC_DATA_PATH + 'Contract.xlsx', index_col='Contract')\n return contract.ix[symbol, 'multiplier']\n\n\ndef getMarginRatio(symbol):\n '''\n 查询品种的保证金率\n :param symbol:\n :return:\n '''\n contract = pd.read_excel(PUBLIC_DATA_PATH + 'Contract.xlsx', index_col='Contract')\n return contract.ix[symbol, 'margin_ratio']\n\n\ndef getSlip(symbol):\n '''\n 查询品种配置的滑点\n :param symbol:\n :return:\n '''\n contract = pd.read_excel(PUBLIC_DATA_PATH + 'Contract.xlsx', index_col='Contract')\n return contract.ix[symbol, 'slip']\n\n\nclass SymbolInfo:\n POUNDGE_TYPE_HAND = u'hand'\n POUNDGE_TYPE_RATE = u'rate'\n\n '''合约信息类'''\n\n def __init__(self, domain_symbol, startdate=None, enddate=None):\n self.domain_symbol = domain_symbol\n contract = pd.read_excel(PUBLIC_DATA_PATH + 'domainMap.xlsx', index_col='symbol')\n contractMapDf = pd.read_csv(PUBLIC_DATA_PATH + 'contractMap.csv', index_col='symbol')\n self.start_utc = None\n self.end_utc = None\n self.contractMap = contractMapDf.loc[contractMapDf['domain_symbol'] == domain_symbol] # 取该主力合约编号对应的合约列表\n if startdate:\n # 过滤掉主力结束时间在开始时间之前的,只取主力结束时间在开始时间之后\n self.start_utc = float(time.mktime(time.strptime(startdate+ \" 00:00:00\", \"%Y-%m-%d %H:%M:%S\")))\n self.contractMap = self.contractMap.loc[self.contractMap['domain_end_utc'] > self.start_utc]\n if enddate:\n # 过滤掉主力开始时间在结束时间之后的,只取主力开始时间在结束时间之前\n self.end_utc = float(time.mktime(time.strptime(enddate + \" 23:59:59\", \"%Y-%m-%d %H:%M:%S\")))\n self.contractMap = self.contractMap.loc[self.contractMap['domain_start_utc'] < self.end_utc]\n\n self.contractMap = self.contractMap.sort_values('domain_start_utc') # 根据主力时间排序\n\n self.active = contract.ix[domain_symbol, 'active'] # 激活标志\n self.priceTick = contract.ix[domain_symbol, 'price_tick']\n self.multiplier = contract.ix[domain_symbol, 'multiplier']\n self.marginRatio = contract.ix[domain_symbol, 'margin_ratio']\n self.slip = contract.ix[domain_symbol, 'slip']\n self.poundageType = contract.ix[domain_symbol, 'poundage_type']\n self.poundageFee = contract.ix[domain_symbol, 'poundage_fee']\n self.poundageRate = contract.ix[domain_symbol, 'poundage_rate']\n\n def getPriceTick(self):\n return self.priceTick\n\n def getMultiplier(self):\n return self.multiplier\n\n def getMarginRatio(self):\n return self.marginRatio\n\n def getSlip(self):\n return self.slip\n\n def getPoundage(self):\n return self.poundageType, self.poundageFee, self.poundageRate\n\n def getSymbolList(self):\n return self.contractMap.index.tolist()\n\n def getSymbolDomainUtc(self, symbol):\n return self.contractMap.ix[symbol, 'domain_start_utc'], self.contractMap.ix[symbol, 'domain_end_utc']\n\n def getSymbolDomainTime(self, symbol):\n return self.contractMap.ix[symbol, 'domain_start_date'], self.contractMap.ix[symbol, 'domain_end_date']\n\n def getSymbolLifeDate(self, symbol):\n # 获取合约的生命周期时间\n return self.contractMap.ix[symbol, 'listed_date'], self.contractMap.ix[symbol, 'maturity_date']\n\n def getUtcRange(self):\n return self.start_utc, self.end_utc\n\n def getSymbolDomainDic(self):\n domainDic = {}\n symbolList = self.getSymbolList()\n for symbol in symbolList:\n s, e = self.getSymbolDomainUtc(symbol)\n domainDic[symbol] = [s, e]\n return domainDic\n\n def amendSymbolDomainDicByOpr(self, oprdf, closeutc_col='closeutc'):\n # 基于传入的oprdf修正symbolDomainDic,因为合约切换时,会有持仓未平仓导致上一合约实际生效时间超过其主力结束时间的现象,故要修改正symbolDomainDic\n # 注:可能会有些合适期间没有opr的情况,所以symbolList会比opr中的symbollist少\n oprgrouped = oprdf.groupby('symbol')\n symbol_last_utc_list = oprgrouped[closeutc_col].last()\n opr_symbol_list = symbol_last_utc_list.index.tolist()\n symbol_last_utc = None\n domainDic = {}\n symbolList = self.getSymbolList()\n for symbol in symbolList:\n s, e = self.getSymbolDomainUtc(symbol)\n if symbol_last_utc:\n s = symbol_last_utc + 1 # 如果上一个合约的最后一次操作超过其主力结束时间,则下一合约从其最后操作结束时间的下一秒开始算,规避取出两个合约同一个时间的数据的问题\n if symbol in opr_symbol_list:\n symbol_last_utc = symbol_last_utc_list[symbol]\n if symbol_last_utc and symbol_last_utc > e:\n e = symbol_last_utc\n else:\n symbol_last_utc = None\n domainDic[symbol] = [s, e]\n return domainDic\n\n def isActive(self):\n return self.active\n\n\nclass TickDataSupplier:\n\n def __init__(self, symbol, startdate, enddate):\n self.startdate = startdate\n self.enddate = enddate\n self.startdateutc = float(time.mktime(time.strptime(startdate + ' 00:00:00', \"%Y-%m-%d %H:%M:%S\")))\n self.enddateutc = float(time.mktime(time.strptime(enddate + ' 23:59:59', \"%Y-%m-%d %H:%M:%S\")))\n self.symbol = symbol\n self.exchange, self.secid = symbol.split('.', 1)\n self.datelist = getTradedates(self.exchange, self.startdate, self.enddate)['strtime']\n self.tickdatadf = pd.DataFrame()\n for d in self.datelist:\n print 'Collecting tick data:', d\n self.tickdatadf = pd.concat([self.tickdatadf, getTickByDate(self.symbol, d)])\n\n def getTickData(self, starttime, endtime):\n startutc = float(time.mktime(time.strptime(starttime, \"%Y-%m-%d %H:%M:%S\")))\n endutc = float(time.mktime(time.strptime(endtime, \"%Y-%m-%d %H:%M:%S\")))\n '''\n df.index=pd.to_datetime(df['utc_time'],unit='s')\n df = df.tz_localize(tz='PRC')\n df=df.truncate(before=startdate)\n '''\n df = self.tickdatadf.loc[(self.tickdatadf['utc_time'] > startutc) & (self.tickdatadf['utc_time'] < endutc)]\n df['Unnamed: 0'] = range(0, df.shape[0])\n # df.drop('Unnamed: 0.1.1', inplace=True, axis=1)\n df.reset_index(drop=True, inplace=True)\n return df\n\n def getTickDataByUtc(self, startutc, endutc):\n df = self.tickdatadf.loc[(self.tickdatadf['utc_time'] > startutc) & (self.tickdatadf['utc_time'] < endutc)]\n df['Unnamed: 0'] = range(0, df.shape[0])\n # df.drop('Unnamed: 0.1.1', inplace=True, axis=1)\n df.reset_index(drop=True, inplace=True)\n return df\n\n def getDateRange(self):\n return self.startdate, self.enddate\n\n def getDateUtcRange(self):\n return self.startdateutc, self.enddateutc\n\n def getSymbol(self):\n return self.symbol\n\n def getDateList(self):\n return self.datelist\n\ndef symbolInfoTest():\n domain_symbol = 'SHFE.RB'\n symbolinfo = SymbolInfo(domain_symbol)\n symbollist = symbolinfo.getSymbolList()\n print symbolinfo.getSymbolDomainDic()\n print symbolinfo.isActive()\n bardic = getBarBySymbolList(domain_symbol, symbollist, 3600)\n for symbol in symbollist:\n print bardic[symbol].head(5)\n\n\n# ========================================================================================\nif __name__ == '__main__':\n # df=getBarData(\"SHFE.RB\",K_MIN=600,starttime='2011-10-08 00:00:00',endtime='2013-03-20 00:00:00')\n # df=getTradedates('SHFE','2017-10-01','2017-12-12')\n # ticksupplier = TickDataSupplier('SHFE.RB', '2017-10-01', '2017-12-10')\n # df1 = ticksupplier.getTickData('2017-10-01 00:00:00', '2017-12-03 22:10:15')\n # print df1.head(10)\n # print df1.tail(10)\n symbolInfoTest()\n" }, { "alpha_fraction": 0.5844444632530212, "alphanum_fraction": 0.5881481766700745, "avg_line_length": 31.926828384399414, "blob_id": "730eb5131e77d06bc37ae28353c06eab8db3f515", "content_id": "98b1529f43e95d43bfd080c8b44de1dc40446e20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1400, "license_type": "no_license", "max_line_length": 80, "num_lines": 41, "path": "/Indexer/RSI.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom IndexerBase import IndexerBase\nimport numpy as np\nimport talib\n\n\nclass RSI(IndexerBase):\n indexer_name = 'RSI'\n indexer_name_list = ['RSI']\n default_para_dic = {\n 'N': 5,\n }\n\n def __init__(self, raw_data, plt):\n super(RSI, self).__init__(raw_data, plt)\n self.indexer_name_list = ['RSI'] # MA的指标名和参数名都跟参数有关,所以要随参数进行设置\n self.indexer_color_dic = {\n 'RSI': 'blue'\n }\n\n def calculate_indexer_value(self):\n n = self.para_dic['N']\n close_array = np.array(self.raw_data['close'].values, dtype='float')\n self.indexer_value_dic['RSI'] = talib.RSI(close_array, n)\n\n def draw_indexer(self):\n i = 0\n for indexer_name, values in self.indexer_value_dic.items():\n c = self.indexer_color_dic[indexer_name][0]\n self.plt_dic[indexer_name] = self.plt.plot(name=indexer_name, pen=c)\n self.plt_dic[indexer_name].setData(values)\n i += 1\n\n def re_draw_indexer(self):\n for pname, values in self.indexer_value_dic.items():\n self.plt_dic[pname].setData(values)\n\n def get_polar_value(self,start_pos, end_pos):\n max_v = max(self.indexer_value_dic['RSI'][start_pos:end_pos])\n min_v = min(self.indexer_value_dic['RSI'][start_pos:end_pos])\n return max_v, min_v\n" }, { "alpha_fraction": 0.7134376764297485, "alphanum_fraction": 0.7312466502189636, "avg_line_length": 55.1363639831543, "blob_id": "0e3cbe490642795e0849e8ddddcec3701205c941", "content_id": "de65cabf46553462afa48f0485dda4aea0a1754b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3706, "license_type": "no_license", "max_line_length": 149, "num_lines": 66, "path": "/untitled.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'untitled.ui'\n#\n# Created: Wed Jul 11 23:51:04 2018\n# by: pyside-uic 0.2.15 running on PySide 1.2.4\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(641, 405)\n self.centralwidget = QtGui.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.tableWidget = QtGui.QTableWidget(self.centralwidget)\n self.tableWidget.setRowCount(4)\n self.tableWidget.setColumnCount(6)\n self.tableWidget.setObjectName(\"tableWidget\")\n self.tableWidget.setColumnCount(6)\n self.tableWidget.setRowCount(4)\n item = QtGui.QTableWidgetItem()\n self.tableWidget.setVerticalHeaderItem(0, item)\n item = QtGui.QTableWidgetItem()\n self.tableWidget.setVerticalHeaderItem(1, item)\n item = QtGui.QTableWidgetItem()\n self.tableWidget.setHorizontalHeaderItem(0, item)\n item = QtGui.QTableWidgetItem()\n self.tableWidget.setHorizontalHeaderItem(1, item)\n item = QtGui.QTableWidgetItem()\n self.tableWidget.setHorizontalHeaderItem(2, item)\n self.verticalLayout.addWidget(self.tableWidget)\n self.horizontalLayout = QtGui.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.pushButton_2 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.horizontalLayout.addWidget(self.pushButton_2)\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setObjectName(\"pushButton\")\n self.horizontalLayout.addWidget(self.pushButton)\n self.verticalLayout.addLayout(self.horizontalLayout)\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtGui.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 641, 23))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtGui.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(QtGui.QApplication.translate(\"MainWindow\", \"MainWindow\", None, QtGui.QApplication.UnicodeUTF8))\n self.tableWidget.verticalHeaderItem(0).setText(QtGui.QApplication.translate(\"MainWindow\", \"1st row\", None, QtGui.QApplication.UnicodeUTF8))\n self.tableWidget.verticalHeaderItem(1).setText(QtGui.QApplication.translate(\"MainWindow\", \"2nd row\", None, QtGui.QApplication.UnicodeUTF8))\n self.tableWidget.horizontalHeaderItem(0).setText(QtGui.QApplication.translate(\"MainWindow\", \"1st col\", None, QtGui.QApplication.UnicodeUTF8))\n self.tableWidget.horizontalHeaderItem(1).setText(QtGui.QApplication.translate(\"MainWindow\", \"2nd col\", None, QtGui.QApplication.UnicodeUTF8))\n self.tableWidget.horizontalHeaderItem(2).setText(QtGui.QApplication.translate(\"MainWindow\", \"3rd col\", None, QtGui.QApplication.UnicodeUTF8))\n self.pushButton_2.setText(QtGui.QApplication.translate(\"MainWindow\", \"PushButton\", None, QtGui.QApplication.UnicodeUTF8))\n self.pushButton.setText(QtGui.QApplication.translate(\"MainWindow\", \"PushButton\", None, QtGui.QApplication.UnicodeUTF8))\n\n" }, { "alpha_fraction": 0.4968598783016205, "alphanum_fraction": 0.5295994877815247, "avg_line_length": 32.612457275390625, "blob_id": "7175935b844de44b76300df087adfd234814822b", "content_id": "f18c614e8d97f3c677f6cb22a23cd87b628996f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9917, "license_type": "no_license", "max_line_length": 115, "num_lines": 289, "path": "/kviewer_app.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport kviewer2\nfrom indexer import Indexer_MA\nimport parameter2\nfrom PyQt5 import QtCore, QtWidgets, QtGui\nimport sys\nimport time\nimport pyqtgraph as pg\nimport pandas as pd\n\nimport numpy as np\n#import tushare as ts\nimport datetime\nfrom matplotlib.pylab import date2num\n#import DATA_CONSTANTS as DC\n\n\"\"\"\n 'b': QtGui.QColor(0,0,255,255),\n 'g': QtGui.QColor(0,255,0,255),\n 'r': QtGui.QColor(255,0,0,255),\n 'c': QtGui.QColor(0,255,255,255),\n 'm': QtGui.QColor(255,0,255,255),\n 'y': QtGui.QColor(255,255,0,255),\n 'k': QtGui.QColor(0,0,0,255),\n 'w': QtGui.QColor(255,255,255,255),\n 'd': QtGui.QColor(150,150,150,255),\n 'l': QtGui.QColor(200,200,200,255),\n 's': QtGui.QColor(100,100,150,255),\"\"\"\ncolor_list = ['w', 'y', 'c','r','g']\n\nclass MainWindow(object):\n def __init__(self):\n app = QtWidgets.QApplication(sys.argv)\n MainWindow = QtWidgets.QMainWindow()\n self.ui = kviewer2.Ui_MainWindow()\n self.ui.setupUi(MainWindow)\n\n self.ma_para = []\n self.ma_data = []\n self.ma_plot_dic = {}\n # 准备数据\n\n hist_data = pd.read_excel('RB1810_2018-06-19_1m.xlsx')\n #hist_data = DC.getBarBySymbol('SHFE.RB', 'RB1805', 3600)\n self.t = range(hist_data.shape[0])\n self.date_list = hist_data['strtime'].tolist()\n self.open = hist_data.open.tolist()\n self.high = hist_data.high.tolist()\n self.low = hist_data.low.tolist()\n self.close = hist_data.close.tolist()\n self.prepare_indexer_para()\n\n packdate = zip(self.t,self.open, self.close, self.low, self.high)\n self.plt1 = self.chart(self.date_list,packdate)\n self.plt2 = self.chart2(self.t, self.close)\n self.plt1.addLegend()\n \"\"\"\n i=0\n for d in self.ma_para:\n pname='ma%d'%d\n self.ma_plot_dic[pname]=self.plt1.plot(name=pname,pen=color_list[i])\n i+=1\n self.prepare_indexer_data()\n \"\"\"\n self.ma_indexer = Indexer_MA(self.plt1, hist_data, [self.ui.lineEdit_ma_n1, self.ui.lineEdit_ma_n2,\n self.ui.lineEdit_ma_n3, self.ui.lineEdit_ma_n4,\n self.ui.lineEdit_ma_n5])\n self.ma_indexer.draw()\n #self.label = QtWidgets.QLabel()\n # 加入竖线\n self.vLine = pg.InfiniteLine(angle=90, movable=False)\n self.plt1.addItem(self.vLine, ignoreBounds=True)\n # self.vb = self.plt1.viewRect()\n\n # 下面第2个图的范围设置框\n self.region = pg.LinearRegionItem()\n self.region.setZValue(10)\n self.region.sigRegionChanged.connect(self.update_plt1)\n\n self.plt1.sigRangeChanged.connect(self.updateRegion)\n\n self.region.setRegion([0, 100])\n self.plt2.addItem(self.region, ignoreBounds=True)\n\n #self.ui.verticalLayout.addWidget(self.label)\n self.ui.verticalLayout.addWidget(self.plt1)\n self.ui.verticalLayout.addWidget(self.plt2)\n proxy = pg.SignalProxy(self.plt1.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)\n MainWindow.show()\n sys.exit(app.exec_())\n\n def prepare_indexer_para(self):\n # 准备指标参数\n \"\"\"\n self.ma_para = {\n 'N1': 5,\n 'N2': 10,\n 'N3': 15,\n 'N4': 30,\n 'N5': 50\n }\n \"\"\"\n self.ma_para = [5,10,20,30,50]\n self.macd_para = {\n 'short': 5,\n 'long': 10,\n 'M': 9\n }\n self.kdj_para = {\n 'N': 9,\n 'M1': 3,\n 'M2': 3\n }\n self.dmi_para = {\n 'N': 14,\n 'M': 6\n }\n\n def prepare_indexer_data(self):\n # ma数据\n for d in self.ma_para:\n data_name = 'ma%d' % d\n data = pd.Series(self.close).rolling(d).mean()\n self.ma_plot_dic[data_name].setData(data)\n\n def set_ma_para(self):\n self.ma_para[0]+=3\n data = pd.Series(self.close).rolling(self.ma_para[0]).mean()\n self.ma_plot_dic['ma5'].setData(data)\n\n def chart(self,date_list, data_list):\n item = CandlestickItem(data_list)\n axis = DateAxis(date_strings=date_list, orientation='bottom')\n plt = pg.PlotWidget()\n plt.axisItems = {'bottom':axis}\n plt.addItem(item, )\n plt.showGrid(x=True, y=True)\n return plt\n\n def chart2(self,x,y):\n plt = pg.PlotWidget()\n plt.addLegend() # 加上图标\n plt.plot(x=x,y=y, pen=\"w\", name='close')\n return plt\n\n def update_plt1(self):\n self.region.setZValue(10)\n minX, maxX = self.region.getRegion()\n\n #Y轴自适应\n int_minY = max(0,int(minX))\n int_maxY = max(1, int(maxX))\n minY = min(self.low[int_minY:int_maxY]) - 5\n maxY = max(self.high[int_minY:int_maxY]) +5\n self.plt1.setYRange(minY, maxY)\n\n self.plt1.setXRange(minX, maxX, padding=0)\n\n\n def updateRegion(self,window, viewRange):\n rgn = viewRange[0]\n self.region.setRegion(rgn)\n\n def mouseMoved(self,event):\n pos = event[0] ## using signal proxy turns original arguments into a tuple\n if self.plt1.sceneBoundingRect().contains(pos):\n a = self.plt1.boundingRect().getRect()\n minx, maxx = self.region.getRegion()\n knum = maxx-minx\n # (pos.x()-35)表示鼠标点距离左边框的位置\n # (a[2]-35)/knum表示每一根K线占用的像素点数量\n # 上面两者两除即为鼠标位置点的K线序号,+minx就是在整个数据列表中的位置\n rx = int((pos.x()-35)/((a[2]-35)/knum)+minx)\n index = rx\n if index > 0 and index < len(self.t):\n open = self.open[index]\n close = self.close[index]\n if open > close:\n c = 'green'\n elif open < close:\n c = 'red'\n else:\n c = 'black'\n self.ui.label_point.setText(\n \"\"\"\n <span style='color: %s'>open=%0.1f,high=%0.1f,low=%0.1f,close=%0.1f</span>,%s\n \"\"\" % (\n c,self.open[index], self.high[index], self.low[index],self.close[index],self.date_list[index]))\n self.ui.label_para.setText(\n self.ma_indexer.get_indexer_value_text(index)\n )\n self.vLine.setPos(index)\n\n def set_parameter(self):\n # 从参数页获取参数\n\n pass\n\n\n\nclass DateAxis(pg.AxisItem):\n\n def __init__(self, date_strings, orientation):\n pg.AxisItem.__init__(self,orientation)\n self.date_strings = date_strings\n self.len = len(self.date_strings)\n def tickStrings(self, values, scale, spacing):\n \"\"\"\n strns = []\n rng = max(values) - min(values)\n # if rng < 120:\n # return pg.AxisItem.tickStrings(self, values, scale, spacing)\n if rng < 3600 * 24:\n string = '%H:%M:%S'\n label1 = '%b %d -'\n label2 = ' %b %d, %Y'\n elif rng >= 3600 * 24 and rng < 3600 * 24 * 30:\n string = '%d'\n label1 = '%b - '\n label2 = '%b, %Y'\n elif rng >= 3600 * 24 * 30 and rng < 3600 * 24 * 30 * 24:\n string = '%b'\n label1 = '%Y -'\n label2 = ' %Y'\n elif rng >= 3600 * 24 * 30 * 24:\n string = '%Y'\n label1 = ''\n label2 = ''\n for x in values:\n try:\n strns.append(time.strftime(string, time.localtime(x)))\n except ValueError: ## Windows can't handle dates before 1970\n strns.append('')\n try:\n label = time.strftime(label1, time.localtime(min(values))) + time.strftime(label2,\n time.localtime(max(values)))\n except ValueError:\n label = ''\n # self.setLabel(text=label)\n return strns\n \"\"\"\n #print values\n strns = []\n for x in values:\n x1 = int(x)\n if 0 <= x1 < self.len:\n strns.append(self.date_strings[x1])\n else:\n strns.append('')\n return strns\n\n\n## Create a subclass of GraphicsObject.\n## The only required methods are paint() and boundingRect()\n## (see QGraphicsItem documentation)\nclass CandlestickItem(pg.GraphicsObject):\n def __init__(self, data):\n pg.GraphicsObject.__init__(self)\n self.data = data ## data must have fields: time, open, close, min, max\n self.generatePicture()\n\n def generatePicture(self):\n ## pre-computing a QPicture object allows paint() to run much more quickly,\n ## rather than re-drawing the shapes every time.\n self.picture = QtGui.QPicture()\n p = QtGui.QPainter(self.picture)\n p.setPen(pg.mkPen('w'))\n w = (self.data[1][0] - self.data[0][0]) / 3.\n for (t, open, close, min, max) in self.data:\n p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))\n if open > close:\n p.setBrush(pg.mkBrush('g'))\n else:\n p.setBrush(pg.mkBrush('r'))\n p.drawRect(QtCore.QRectF(t - w, open, w * 2, close - open))\n p.end()\n\n def paint(self, p, *args):\n p.drawPicture(0, 0, self.picture)\n\n def boundingRect(self):\n ## boundingRect _must_ indicate the entire area that will be drawn on\n ## or else we will get artifacts and possibly crashing.\n ## (in this case, QPicture does all the work of computing the bouning rect for us)\n return QtCore.QRectF(self.picture.boundingRect())\n\nif __name__=='__main__':\n MainWindow()" }, { "alpha_fraction": 0.5286478400230408, "alphanum_fraction": 0.541252851486206, "avg_line_length": 34.863014221191406, "blob_id": "0f29a96a789ee6fc2e25f6a47f3e9f813ab50015", "content_id": "a1bb8da65b86a785e874906ff35b89aad212873d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2704, "license_type": "no_license", "max_line_length": 124, "num_lines": 73, "path": "/Indexer/EMA.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom IndexerBase import IndexerBase\n\n\nclass EMA(IndexerBase):\n indexer_name = 'EMA'\n indexer_name_list = [] # MA的指标名和参数名都跟参数有关,所以要随参数进行设置\n default_para_dic = {\n 'N1': 5,\n 'N2': 10,\n 'N3': 15,\n 'N4': 30,\n 'N5': 50\n }\n\n def __init__(self, raw_data, plt):\n self.indexer_name_list = []\n for para_name, value in self.default_para_dic.items():\n self.indexer_name_list.append(\"EMA%d\"%value)\n super(EMA,self).__init__(raw_data, plt)\n self.indexer_color_dic = {\n 'N1': 'blue',\n 'N2': 'magenta',\n 'N3': 'cyan',\n 'N4': 'red',\n 'N5': 'green'\n }\n\n def calculate_indexer_value(self):\n del self.indexer_value_dic\n del self.indexer_name_list\n self.indexer_name_list = []\n self.indexer_value_dic = {}\n for para_name, para_value, in self.para_dic.items():\n indexer_name = \"EMA%d\" % para_value\n self.indexer_name_list.append(indexer_name)\n self.indexer_value_dic[indexer_name] = self.raw_data['close'].ewm(span=para_value, adjust=False).mean().tolist()\n\n def draw_indexer(self):\n i = 0\n for pname, values in self.para_dic.items():\n indexer_name = \"EMA%d\" % values\n c = self.indexer_color_dic[pname][0]\n self.plt_dic[pname] = self.plt.plot(name=pname, pen=c)\n self.plt_dic[pname].setData(self.indexer_value_dic[indexer_name])\n i += 1\n\n def re_draw_indexer(self):\n for pname, values in self.para_dic.items():\n indexer_name = \"EMA%d\" % values\n self.plt_dic[pname].setData(self.indexer_value_dic[indexer_name])\n\n def get_polar_value(self,start_pos, end_pos):\n max_v = 0\n min_v = 99999\n for value_list in self.indexer_value_dic.values():\n max_v = max(max_v, max(value_list[start_pos:end_pos]))\n min_v = min(min_v, min(value_list[start_pos:end_pos]))\n return max_v, min_v\n\n def get_indexer_value_text(self, pos):\n # 根据传入的位置返回一个指标值的字符串\n t = self.indexer_name + '('\n for para_name, para_value in self.para_dic.items():\n t += '%s_%d ' % (para_name, para_value)\n t += ')'\n i = 0\n for para_name, para_value in self.para_dic.items():\n indexer_name = 'EMA%d'%para_value\n c = self.indexer_color_dic[para_name]\n t += \"<span style='color: %s'>%s=%0.2f </span>\" % (c, indexer_name, self.indexer_value_dic[indexer_name][pos])\n i += 1\n return t\n" }, { "alpha_fraction": 0.5423728823661804, "alphanum_fraction": 0.5451213717460632, "avg_line_length": 28.106666564941406, "blob_id": "b0c2afb0bf366e0f90c989d3a77023b339e68f57", "content_id": "28266c9acc2846e06e64a9f6d0ab402ef8cd3af0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2267, "license_type": "no_license", "max_line_length": 116, "num_lines": 75, "path": "/Indexer/IndexerBase.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n指标类,用于管理指标相内容:\n\"\"\"\n\nclass IndexerBase(object):\n color_list = ['blue', 'magenta', 'cyan', 'red', 'green']\n indexer_name = ''\n indexer_name_list = []\n default_para_dic = {}\n para_dic = {}\n indexer_color_dic = {} # 各指标对应的显示颜色\n\n def __init__(self, raw_data, plt):\n self.raw_data = raw_data\n self.para_dic = {}\n for para_name, value in self.default_para_dic.items():\n self.para_dic[para_name] = value\n self.indexer_value_dic = {}\n self.plt = plt\n self.plt_dic = {}\n self.value_num = self.raw_data.shape[0]\n #self.calculate_indexer_value()\n #self.draw_indexer()\n pass\n\n def calculate_indexer_value(self):\n pass\n\n def draw_indexer(self):\n pass\n\n def re_draw_indexer(self):\n pass\n\n def get_polar_value(self, start_pos, end_pos):\n pass\n\n def close_sub_plt(self):\n for plt in self.plt_dic.values():\n plt.close()\n\n def set_para_dic(self,para_dic):\n for para_name in self.para_dic.keys():\n self.para_dic[para_name] = para_dic[para_name]\n\n def get_para_dic(self):\n return self.para_dic\n\n def update_raw_data(self,raw_data):\n self.raw_data = raw_data\n self.calculate_indexer_value()\n self.re_draw_indexer()\n\n def update_parameter(self, para_dic):\n changed = False\n for para_name in self.default_para_dic.keys():\n if self.para_dic[para_name] != para_dic[para_name]:\n self.para_dic[para_name] = para_dic[para_name]\n changed = True\n if changed:\n self.calculate_indexer_value()\n self.re_draw_indexer()\n\n def get_indexer_value_text(self, pos):\n # 根据传入的位置返回一个指标值的字符串\n t = self.indexer_name + '('\n for para_name, para_value in self.para_dic.items():\n t += '%s_%d ' % (para_name, para_value)\n t += ')'\n i = 0\n for para_name, c in self.indexer_color_dic.items():\n t += \"<span style='color: %s'>%s=%0.2f </span>\" % (c, para_name, self.indexer_value_dic[para_name][pos])\n i += 1\n return t\n" }, { "alpha_fraction": 0.6616102457046509, "alphanum_fraction": 0.6627771258354187, "avg_line_length": 23.514286041259766, "blob_id": "41732e7e5c405f7f927ca635d6e2083f64c8d1f8", "content_id": "c55441eef8e7c196620267b7399340938fddb8a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 857, "license_type": "no_license", "max_line_length": 66, "num_lines": 35, "path": "/Indexer/__init__.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom IndexerWidget import IndexerWidget\nfrom MA import MA\nfrom MACD import MACD\nfrom RSI import RSI\nfrom ATR import ATR\nfrom HullMacd import HULL_MACD\nfrom EMA import EMA\nfrom HullRsi import HULL_RSI\nfrom KDJ import KDJ\nfrom DMI import DMI\n\nindexer_mapping_dic = {\n 'MA': MA,\n 'EMA': EMA,\n 'MACD': MACD,\n 'HULL_MACD': HULL_MACD,\n 'RSI': RSI,\n 'ATR': ATR,\n 'HULL_RSI': HULL_RSI,\n 'KDJ': KDJ,\n 'DMI': DMI\n}\n\ndef get_all_indexer_para_name():\n result_dic = {}\n for indexer_name, indexer in indexer_mapping_dic.items():\n result_dic[indexer_name] = indexer.default_para_dic.keys()\n return result_dic\n\ndef get_all_indexer_para_dic():\n result_dic = {}\n for indexer_name, indexer in indexer_mapping_dic.items():\n result_dic[indexer_name] = indexer.default_para_dic\n return result_dic" }, { "alpha_fraction": 0.5313733816146851, "alphanum_fraction": 0.5427819490432739, "avg_line_length": 36.983333587646484, "blob_id": "6f9a4d10fc99764a8b0720e1d537f76dabcccc75", "content_id": "9bdf4425ea569eb2e5957ca4702858987b86ebe0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2363, "license_type": "no_license", "max_line_length": 104, "num_lines": 60, "path": "/Indexer/KDJ.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom IndexerBase import IndexerBase\nimport numpy as np\nimport talib\n\n\nclass KDJ(IndexerBase):\n indexer_name = 'KDJ'\n indexer_name_list = ['K', 'D', 'J']\n default_para_dic = {\n 'N': 9,\n 'M1': 3,\n 'M2': 3\n }\n\n def __init__(self, raw_data, plt):\n super(KDJ, self).__init__(raw_data, plt)\n self.indexer_name_list = ['K', 'D', 'J'] # MA的指标名和参数名都跟参数有关,所以要随参数进行设置\n self.indexer_color_dic = {\n 'K': 'blue',\n 'D': 'magenta',\n 'J': 'cyan'\n }\n\n def calculate_indexer_value(self):\n n = self.para_dic['N']\n m1 = self.para_dic['M1']\n m2 = self.para_dic['M2']\n low_list = self.raw_data['low'].rolling(n).min().fillna(self.raw_data['low']) # 使用low的值来填充前面的空白\n high_list = self.raw_data['high'].rolling(n).max().fillna(self.raw_data['high']) # 使用high来填充\n rsv = (self.raw_data['close'] - low_list) / (high_list - low_list) * 100\n a = 1.0/m1\n a2 = 1.0/m2\n kdj_k = rsv.ewm(alpha=a, adjust=False).mean()\n kdj_d = kdj_k.ewm(alpha=a2, adjust=False).mean()\n kdj_j = 3 * kdj_k - 2 * kdj_d\n self.indexer_value_dic['K'] = kdj_k\n self.indexer_value_dic['D'] = kdj_d\n self.indexer_value_dic['J'] = kdj_j\n\n def draw_indexer(self):\n i = 0\n for indexer_name, values in self.indexer_value_dic.items():\n c = self.indexer_color_dic[indexer_name][0]\n self.plt_dic[indexer_name] = self.plt.plot(name=indexer_name, pen=c)\n self.plt_dic[indexer_name].setData(values)\n i += 1\n\n def re_draw_indexer(self):\n for pname, values in self.indexer_value_dic.items():\n self.plt_dic[pname].setData(values)\n\n def get_polar_value(self,start_pos, end_pos):\n max_v = max(max(self.indexer_value_dic['K'][start_pos:end_pos]),\n max(self.indexer_value_dic['D'][start_pos:end_pos]),\n max(self.indexer_value_dic['J'][start_pos:end_pos]))\n min_v = min(min(self.indexer_value_dic['K'][start_pos:end_pos]),\n min(self.indexer_value_dic['D'][start_pos:end_pos]),\n min(self.indexer_value_dic['J'][start_pos:end_pos]))\n return max_v, min_v\n" }, { "alpha_fraction": 0.6626100540161133, "alphanum_fraction": 0.6969426870346069, "avg_line_length": 62.162498474121094, "blob_id": "7724c732487b512269f2e8d6281e98a2dfe50773", "content_id": "4a1af93e69d7f23a82f667c232f1d678656c49c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10167, "license_type": "no_license", "max_line_length": 123, "num_lines": 160, "path": "/parameter.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'parameter.ui'\n#\n# Created: Sat Jul 21 16:49:46 2018\n# by: pyside-uic 0.2.15 running on PySide 1.2.4\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PySide import QtCore, QtGui\n\nclass Ui_Form(object):\n def setupUi(self, Form):\n Form.setObjectName(\"Form\")\n Form.resize(398, 494)\n self.verticalLayout = QtGui.QVBoxLayout(Form)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.groupBox = QtGui.QGroupBox(Form)\n self.groupBox.setObjectName(\"groupBox\")\n self.gridLayoutWidget_2 = QtGui.QWidget(self.groupBox)\n self.gridLayoutWidget_2.setGeometry(QtCore.QRect(9, 9, 351, 61))\n self.gridLayoutWidget_2.setObjectName(\"gridLayoutWidget_2\")\n self.gridLayout_2 = QtGui.QGridLayout(self.gridLayoutWidget_2)\n self.gridLayout_2.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint)\n self.gridLayout_2.setContentsMargins(0, 0, 0, 0)\n self.gridLayout_2.setObjectName(\"gridLayout_2\")\n self.lineEdit = QtGui.QLineEdit(self.gridLayoutWidget_2)\n self.lineEdit.setObjectName(\"lineEdit\")\n self.gridLayout_2.addWidget(self.lineEdit, 0, 2, 1, 1)\n self.label_2 = QtGui.QLabel(self.gridLayoutWidget_2)\n self.label_2.setObjectName(\"label_2\")\n self.gridLayout_2.addWidget(self.label_2, 0, 3, 1, 1)\n self.label = QtGui.QLabel(self.gridLayoutWidget_2)\n self.label.setObjectName(\"label\")\n self.gridLayout_2.addWidget(self.label, 0, 0, 1, 1)\n self.comboBox = QtGui.QComboBox(self.gridLayoutWidget_2)\n self.comboBox.setObjectName(\"comboBox\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.gridLayout_2.addWidget(self.comboBox, 0, 4, 1, 1)\n self.label_3 = QtGui.QLabel(self.gridLayoutWidget_2)\n self.label_3.setObjectName(\"label_3\")\n self.gridLayout_2.addWidget(self.label_3, 1, 0, 1, 1)\n self.label_4 = QtGui.QLabel(self.gridLayoutWidget_2)\n self.label_4.setObjectName(\"label_4\")\n self.gridLayout_2.addWidget(self.label_4, 1, 3, 1, 1)\n self.dateEdit_2 = QtGui.QDateEdit(self.gridLayoutWidget_2)\n self.dateEdit_2.setObjectName(\"dateEdit_2\")\n self.gridLayout_2.addWidget(self.dateEdit_2, 1, 4, 1, 1)\n self.dateEdit = QtGui.QDateEdit(self.gridLayoutWidget_2)\n self.dateEdit.setObjectName(\"dateEdit\")\n self.gridLayout_2.addWidget(self.dateEdit, 1, 2, 1, 1)\n self.verticalLayout.addWidget(self.groupBox)\n self.groupBox_5 = QtGui.QGroupBox(Form)\n self.groupBox_5.setObjectName(\"groupBox_5\")\n self.pushButton_3 = QtGui.QPushButton(self.groupBox_5)\n self.pushButton_3.setGeometry(QtCore.QRect(20, 20, 75, 23))\n self.pushButton_3.setObjectName(\"pushButton_3\")\n self.label_11 = QtGui.QLabel(self.groupBox_5)\n self.label_11.setGeometry(QtCore.QRect(110, 30, 54, 12))\n self.label_11.setObjectName(\"label_11\")\n self.verticalLayout.addWidget(self.groupBox_5)\n self.groupBox_2 = QtGui.QGroupBox(Form)\n self.groupBox_2.setObjectName(\"groupBox_2\")\n self.gridLayoutWidget = QtGui.QWidget(self.groupBox_2)\n self.gridLayoutWidget.setGeometry(QtCore.QRect(10, 10, 351, 80))\n self.gridLayoutWidget.setObjectName(\"gridLayoutWidget\")\n self.gridLayout = QtGui.QGridLayout(self.gridLayoutWidget)\n self.gridLayout.setContentsMargins(0, 0, 0, 0)\n self.gridLayout.setObjectName(\"gridLayout\")\n self.label_5 = QtGui.QLabel(self.gridLayoutWidget)\n self.label_5.setObjectName(\"label_5\")\n self.gridLayout.addWidget(self.label_5, 0, 0, 1, 1)\n self.label_7 = QtGui.QLabel(self.gridLayoutWidget)\n self.label_7.setObjectName(\"label_7\")\n self.gridLayout.addWidget(self.label_7, 0, 4, 1, 1)\n self.lineEdit_ma_n3 = QtGui.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n3.setObjectName(\"lineEdit_ma_n3\")\n self.gridLayout.addWidget(self.lineEdit_ma_n3, 0, 5, 1, 1)\n self.lineEdit_ma_n2 = QtGui.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n2.setObjectName(\"lineEdit_ma_n2\")\n self.gridLayout.addWidget(self.lineEdit_ma_n2, 0, 3, 1, 1)\n self.label_6 = QtGui.QLabel(self.gridLayoutWidget)\n self.label_6.setObjectName(\"label_6\")\n self.gridLayout.addWidget(self.label_6, 0, 2, 1, 1)\n self.lineEdit_ma_n1 = QtGui.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n1.setObjectName(\"lineEdit_ma_n1\")\n self.gridLayout.addWidget(self.lineEdit_ma_n1, 0, 1, 1, 1)\n self.label_8 = QtGui.QLabel(self.gridLayoutWidget)\n self.label_8.setObjectName(\"label_8\")\n self.gridLayout.addWidget(self.label_8, 1, 0, 1, 1)\n self.lineEdit_ma_n4 = QtGui.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n4.setObjectName(\"lineEdit_ma_n4\")\n self.gridLayout.addWidget(self.lineEdit_ma_n4, 1, 1, 1, 1)\n self.label_9 = QtGui.QLabel(self.gridLayoutWidget)\n self.label_9.setObjectName(\"label_9\")\n self.gridLayout.addWidget(self.label_9, 1, 2, 1, 1)\n self.lineEdit_ma_n5 = QtGui.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n5.setObjectName(\"lineEdit_ma_n5\")\n self.gridLayout.addWidget(self.lineEdit_ma_n5, 1, 3, 1, 1)\n self.label_10 = QtGui.QLabel(self.gridLayoutWidget)\n self.label_10.setObjectName(\"label_10\")\n self.gridLayout.addWidget(self.label_10, 1, 4, 1, 1)\n self.comboBox_ma = QtGui.QComboBox(self.gridLayoutWidget)\n self.comboBox_ma.setObjectName(\"comboBox_ma\")\n self.comboBox_ma.addItem(\"\")\n self.comboBox_ma.addItem(\"\")\n self.gridLayout.addWidget(self.comboBox_ma, 1, 5, 1, 1)\n self.verticalLayout.addWidget(self.groupBox_2)\n self.groupBox_3 = QtGui.QGroupBox(Form)\n self.groupBox_3.setObjectName(\"groupBox_3\")\n self.verticalLayout.addWidget(self.groupBox_3)\n self.horizontalLayout = QtGui.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.pushButton = QtGui.QPushButton(Form)\n self.pushButton.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.pushButton.setObjectName(\"pushButton\")\n self.horizontalLayout.addWidget(self.pushButton)\n self.pushButton_2 = QtGui.QPushButton(Form)\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.horizontalLayout.addWidget(self.pushButton_2)\n self.verticalLayout.addLayout(self.horizontalLayout)\n\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(QtGui.QApplication.translate(\"Form\", \"Form\", None, QtGui.QApplication.UnicodeUTF8))\n self.groupBox.setTitle(QtGui.QApplication.translate(\"Form\", \"公共参数\", None, QtGui.QApplication.UnicodeUTF8))\n self.label_2.setText(QtGui.QApplication.translate(\"Form\", \"周期\", None, QtGui.QApplication.UnicodeUTF8))\n self.label.setText(QtGui.QApplication.translate(\"Form\", \"合约\", None, QtGui.QApplication.UnicodeUTF8))\n self.comboBox.setItemText(0, QtGui.QApplication.translate(\"Form\", \"0\", None, QtGui.QApplication.UnicodeUTF8))\n self.comboBox.setItemText(1, QtGui.QApplication.translate(\"Form\", \"60\", None, QtGui.QApplication.UnicodeUTF8))\n self.comboBox.setItemText(2, QtGui.QApplication.translate(\"Form\", \"300\", None, QtGui.QApplication.UnicodeUTF8))\n self.comboBox.setItemText(3, QtGui.QApplication.translate(\"Form\", \"600\", None, QtGui.QApplication.UnicodeUTF8))\n self.comboBox.setItemText(4, QtGui.QApplication.translate(\"Form\", \"900\", None, QtGui.QApplication.UnicodeUTF8))\n self.comboBox.setItemText(5, QtGui.QApplication.translate(\"Form\", \"1800\", None, QtGui.QApplication.UnicodeUTF8))\n self.comboBox.setItemText(6, QtGui.QApplication.translate(\"Form\", \"3600\", None, QtGui.QApplication.UnicodeUTF8))\n self.label_3.setText(QtGui.QApplication.translate(\"Form\", \"开始时间\", None, QtGui.QApplication.UnicodeUTF8))\n self.label_4.setText(QtGui.QApplication.translate(\"Form\", \"结束时间\", None, QtGui.QApplication.UnicodeUTF8))\n self.groupBox_5.setTitle(QtGui.QApplication.translate(\"Form\", \"回测文件\", None, QtGui.QApplication.UnicodeUTF8))\n self.pushButton_3.setText(QtGui.QApplication.translate(\"Form\", \"PushButton\", None, QtGui.QApplication.UnicodeUTF8))\n self.label_11.setText(QtGui.QApplication.translate(\"Form\", \"TextLabel\", None, QtGui.QApplication.UnicodeUTF8))\n self.groupBox_2.setTitle(QtGui.QApplication.translate(\"Form\", \"MA参数\", None, QtGui.QApplication.UnicodeUTF8))\n self.label_5.setText(QtGui.QApplication.translate(\"Form\", \"N1\", None, QtGui.QApplication.UnicodeUTF8))\n self.label_7.setText(QtGui.QApplication.translate(\"Form\", \"N3\", None, QtGui.QApplication.UnicodeUTF8))\n self.label_6.setText(QtGui.QApplication.translate(\"Form\", \"N2\", None, QtGui.QApplication.UnicodeUTF8))\n self.label_8.setText(QtGui.QApplication.translate(\"Form\", \"N4\", None, QtGui.QApplication.UnicodeUTF8))\n self.label_9.setText(QtGui.QApplication.translate(\"Form\", \"N5\", None, QtGui.QApplication.UnicodeUTF8))\n self.label_10.setText(QtGui.QApplication.translate(\"Form\", \"算法\", None, QtGui.QApplication.UnicodeUTF8))\n self.comboBox_ma.setItemText(0, QtGui.QApplication.translate(\"Form\", \"MA\", None, QtGui.QApplication.UnicodeUTF8))\n self.comboBox_ma.setItemText(1, QtGui.QApplication.translate(\"Form\", \"EMA\", None, QtGui.QApplication.UnicodeUTF8))\n self.groupBox_3.setTitle(QtGui.QApplication.translate(\"Form\", \"MACD参数\", None, QtGui.QApplication.UnicodeUTF8))\n self.pushButton.setText(QtGui.QApplication.translate(\"Form\", \"确定\", None, QtGui.QApplication.UnicodeUTF8))\n self.pushButton_2.setText(QtGui.QApplication.translate(\"Form\", \"取消\", None, QtGui.QApplication.UnicodeUTF8))\n\n" }, { "alpha_fraction": 0.592362105846405, "alphanum_fraction": 0.6005657911300659, "avg_line_length": 34.71717071533203, "blob_id": "542b934b6e84b06d3c0b21a54169321514717719", "content_id": "c4dc5057c57d4556e3015d3afaa99b2c8ea94938", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3569, "license_type": "no_license", "max_line_length": 75, "num_lines": 99, "path": "/Indexer/IndexerWidget.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom Indexer import *\n\nclass IndexerWidget(QWidget):\n\n signal_para_changed = pyqtSignal(str,dict, name='para_changed')\n\n def __init__(self, all_indexer_para_dic, current_indexer_name):\n super(IndexerWidget,self).__init__()\n #self.setGeometry(300,50,10,10)\n self.setWindowTitle('设置指标参数')\n self.indexer_para_dic = all_indexer_para_dic\n self.leftlist = QListWidget()\n self.para_line_edit_dic = {}\n self.stack_dic = {}\n self.indexer_pos_dic = {} # 记录各个指标在leftlist中的位置\n i = 0\n current_indexer_pos = 0\n self.stack = QStackedWidget(self)\n for indexer_name in self.indexer_para_dic.keys():\n self.leftlist.insertItem(i, indexer_name)\n stack_widget= QWidget()\n layout = QFormLayout()\n indexer_para_dic = self.indexer_para_dic[indexer_name]\n line_edit_dic = {}\n for name, value in indexer_para_dic.items():\n le = QLineEdit()\n le.setValidator(QIntValidator())\n le.setMaxLength(2)\n le.setText(str(value))\n line_edit_dic[name] = le\n layout.addRow(name, le)\n self.para_line_edit_dic[indexer_name] = line_edit_dic\n stack_widget.setLayout(layout)\n self.stack_dic[indexer_name] = stack_widget\n self.stack.addWidget(stack_widget)\n if indexer_name == current_indexer_name:\n current_indexer_pos = i\n i += 1\n main_box = QVBoxLayout(self)\n hbox = QHBoxLayout(self)\n hbox.addWidget(self.leftlist)\n hbox.addWidget(self.stack)\n \n main_box.addLayout(hbox)\n btn_layout = self.setup_button()\n main_box.addLayout(btn_layout)\n self.setLayout(btn_layout)\n self.leftlist.currentRowChanged.connect(self.display)\n self.leftlist.setCurrentRow(current_indexer_pos)\n\n def setup_button(self):\n vbox = QHBoxLayout(self)\n btn_ok = QPushButton('OK')\n btn_cancel = QPushButton('Cancle')\n btn_ok.clicked.connect(self.get_user_para)\n btn_cancel.clicked.connect(self.close)\n vbox.addWidget(btn_ok)\n vbox.addWidget(btn_cancel)\n return vbox\n\n def get_user_para(self):\n all_para_dic = {}\n for indexer_name, line_edit_dic in self.para_line_edit_dic.items():\n para_dic = {}\n for para_name, line_edit in line_edit_dic.items():\n para_dic[para_name] = int(line_edit.text())\n all_para_dic[indexer_name] = para_dic\n selected_indexer = self.leftlist.currentItem().text()\n self.signal_para_changed.emit(selected_indexer,all_para_dic)\n self.close()\n\n def display(self,i):\n self.stack.setCurrentIndex(i)\n\nclass test1():\n\n def __init__(self, name):\n self.name = name\n\n def receive_para_changed(self,selected,dict):\n print (self.name, selected, dict)\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n all_indexer_para_dic = get_all_indexer_para_dic()\n demo = IndexerWidget(all_indexer_para_dic)\n #demo2 = IndexerWidget(all_indexer_para_dic)\n c1 = test1('test1')\n #c2 = test1('test2')\n demo.signal_para_changed.connect(c1.receive_para_changed)\n #demo2.signal_para_changed.connect(c2.receive_para_changed)\n demo.show()\n #demo2.show()\n sys.exit(app.exec_())" }, { "alpha_fraction": 0.7177689671516418, "alphanum_fraction": 0.7296555638313293, "avg_line_length": 54.59321975708008, "blob_id": "f24fca68d7faa4e3b4712f2577395b4104097714", "content_id": "25ab184d39c7a465c92aa78368f1499043b47e62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3281, "license_type": "no_license", "max_line_length": 115, "num_lines": 59, "path": "/nullWindow.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(641, 405)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)\n self.tableWidget.setRowCount(4)\n self.tableWidget.setColumnCount(6)\n self.tableWidget.setObjectName(\"tableWidget\")\n self.tableWidget.setColumnCount(6)\n self.tableWidget.setRowCount(4)\n item = QtWidgets.QTableWidgetItem()\n self.tableWidget.setVerticalHeaderItem(0, item)\n item = QtWidgets.QTableWidgetItem()\n self.tableWidget.setVerticalHeaderItem(1, item)\n item = QtWidgets.QTableWidgetItem()\n self.tableWidget.setHorizontalHeaderItem(0, item)\n item = QtWidgets.QTableWidgetItem()\n self.tableWidget.setHorizontalHeaderItem(1, item)\n item = QtWidgets.QTableWidgetItem()\n self.tableWidget.setHorizontalHeaderItem(2, item)\n self.verticalLayout.addWidget(self.tableWidget)\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.horizontalLayout.addWidget(self.pushButton_2)\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton.setObjectName(\"pushButton\")\n self.horizontalLayout.addWidget(self.pushButton)\n self.verticalLayout.addLayout(self.horizontalLayout)\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 641, 23))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(QtWidgets.QApplication.translate(\"MainWindow\", \"MainWindow\"))\n self.tableWidget.verticalHeaderItem(0).setText(QtWidgets.QApplication.translate(\"MainWindow\", \"1st row\"))\n self.tableWidget.verticalHeaderItem(1).setText(QtWidgets.QApplication.translate(\"MainWindow\", \"2nd row\"))\n self.tableWidget.horizontalHeaderItem(0).setText(QtWidgets.QApplication.translate(\"MainWindow\", \"1st col\"))\n self.tableWidget.horizontalHeaderItem(1).setText(QtWidgets.QApplication.translate(\"MainWindow\", \"2nd col\"))\n self.tableWidget.horizontalHeaderItem(2).setText(QtWidgets.QApplication.translate(\"MainWindow\", \"3rd col\"))\n self.pushButton_2.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"PushButton\"))\n self.pushButton.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"PushButton\"))\n\n" }, { "alpha_fraction": 0.5706609487533569, "alphanum_fraction": 0.5819451808929443, "avg_line_length": 28.09375, "blob_id": "533c1f9ed7ee19601d4ee796530a1ed47b1cb416", "content_id": "96cb63b9c92440d2a98eea169c07c7ca8b53c085", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1873, "license_type": "no_license", "max_line_length": 76, "num_lines": 64, "path": "/MainFrame.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport sys\nfrom PyQt5.QtWidgets import *\nfrom KViewer_new import KViewer\n\n\nclass KViewerMainWindow(QMainWindow):\n def __init__(self, parent=None):\n super(KViewerMainWindow, self).__init__(parent)\n self.resize(800,600)\n self.setWindowTitle('KViewer')\n\n self.tab_widget = QTabWidget()\n self.tab_num = 0\n tab1 = self.new_tab()\n self.tab_widget.addTab(tab1, 'tab%d'% self.tab_num)\n self.tab_widget.setTabText(0, 'contract 0')\n\n self.main_layout = QVBoxLayout()\n self.main_layout.addWidget(self.tab_widget)\n self.setLayout(self.main_layout)\n self.setCentralWidget(self.tab_widget)\n\n tb = self.addToolBar(\"增删\")\n add = QAction(\"增加\",self)\n add.triggered.connect(self.add_tab)\n tb.addAction(add)\n rem = QAction(\"删除\",self)\n rem.triggered.connect(self.remove_tab)\n tb.addAction(rem)\n #tb.actionTriggered[QAction].connect(self.add_tab)\n\n def new_tab(self):\n '''\n tab1 = QWidget()\n layout = QFormLayout()\n layout.addRow(\"name\",QLineEdit())\n layout.addRow(\"address\",QLineEdit())\n tab1.setLayout(layout)\n return tab1\n '''\n kv = KViewer()\n return kv\n\n def add_tab(self,):\n print ('1')\n tab1 = self.new_tab()\n self.tab_num += 1\n self.tab_widget.addTab(tab1, 'tab %d'% self.tab_num)\n self.tab_widget.setTabText(self.tab_num, 'contract%d'% self.tab_num)\n\n def remove_tab(self):\n i = self.tab_widget.currentIndex()\n print (\"current index:%d\" % i)\n print (\"tab_num:%d\" % self.tab_num)\n self.tab_widget.removeTab(i)\n self.tab_num -= 1\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n win = KViewerMainWindow()\n win.show()\n sys.exit(app.exec_())" }, { "alpha_fraction": 0.48894891142845154, "alphanum_fraction": 0.4953339993953705, "avg_line_length": 40.141414642333984, "blob_id": "894520d47f332897878370f4c7733615de0a45db", "content_id": "b217584c6ceb40b0908a258be26e84773a1c3672", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4172, "license_type": "no_license", "max_line_length": 106, "num_lines": 99, "path": "/Indexer/MACD.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom IndexerBase import IndexerBase\nimport pyqtgraph as pg\n\nclass MACD(IndexerBase):\n indexer_name = 'MACD'\n indexer_name_list = ['DIF', 'DEA', 'HIST'] # MA的指标名和参数名都跟参数有关,所以要随参数进行设置\n default_para_dic = {\n 'Short':12,\n 'Mid':9,\n 'Long':26\n }\n\n def __init__(self, raw_data, plt):\n super(MACD, self).__init__(raw_data, plt)\n self.indexer_name_list = ['DIF', 'DEA', 'HIST'] # MA的指标名和参数名都跟参数有关,所以要随参数进行设置\n self.hist_item_up = None\n self.hist_item_down = None\n self.indexer_color_dic = {\n 'DIF': 'blue',\n 'DEA': 'magenta',\n 'HIST': 'red'\n }\n\n def calculate_indexer_value(self):\n closedata = self.raw_data['close']\n short = self.para_dic['Short']\n long1 = self.para_dic['Long']\n mid = self.para_dic['Mid']\n sema = closedata.ewm(span=short, adjust=False).mean()\n lema = closedata.ewm(span=long1, adjust=False).mean()\n data_dif = sema - lema\n # data_dea = pd.ewma(data_dif, span=mid)\n data_dea = data_dif.ewm(span=mid, adjust=False).mean()\n data_bar = (data_dif - data_dea) * 2\n self.indexer_value_dic['DIF'] = data_dif.tolist()\n self.indexer_value_dic['DEA'] = data_dea.tolist()\n self.indexer_value_dic['HIST'] = data_bar.tolist()\n\n def draw_indexer(self):\n i = 0\n for indexer_name, values in self.indexer_value_dic.items():\n if indexer_name == 'HIST':\n n = 0\n up_num = []\n up_value = []\n down_num = []\n down_value = []\n for v in values:\n if v >= 0:\n up_value.append(v)\n up_num.append(n)\n else:\n down_value.append(v)\n down_num.append(n)\n n += 1\n self.hist_item_up = pg.BarGraphItem(x=up_num, height=up_value, width=0.3, brush='r')\n self.hist_item_down = pg.BarGraphItem(x=down_num, height=down_value, width=0.3, brush='g')\n self.plt.addItem(self.hist_item_up)\n self.plt.addItem(self.hist_item_down)\n else:\n c = self.indexer_color_dic[indexer_name][0]\n self.plt_dic[indexer_name] = self.plt.plot(name=indexer_name, pen=c)\n self.plt_dic[indexer_name].setData(values)\n i += 1\n\n def re_draw_indexer(self):\n for pname, values in self.indexer_value_dic.items():\n if pname == 'HIST':\n self.plt.removeItem(self.hist_item_up)\n self.plt.removeItem(self.hist_item_down)\n n = 0\n up_num = []\n up_value = []\n down_num = []\n down_value = []\n for v in values:\n if v >= 0:\n up_value.append(v)\n up_num.append(n)\n else:\n down_value.append(v)\n down_num.append(n)\n n += 1\n self.hist_item_up = pg.BarGraphItem(x=up_num, height=up_value, width=0.3, brush='r')\n self.hist_item_down = pg.BarGraphItem(x=down_num, height=down_value, width=0.3, brush='g')\n self.plt.addItem(self.hist_item_up)\n self.plt.addItem(self.hist_item_down)\n else:\n self.plt_dic[pname].setData(values)\n\n def get_polar_value(self,start_pos, end_pos):\n max_v = max(max(self.indexer_value_dic['DIF'][start_pos:end_pos]),\n max(self.indexer_value_dic['DEA'][start_pos:end_pos]),\n max(self.indexer_value_dic['HIST'][start_pos:end_pos]))\n min_v = min(min(self.indexer_value_dic['DIF'][start_pos:end_pos]),\n min(self.indexer_value_dic['DEA'][start_pos:end_pos]),\n min(self.indexer_value_dic['HIST'][start_pos:end_pos]))\n return max_v, min_v" }, { "alpha_fraction": 0.6550396084785461, "alphanum_fraction": 0.688160240650177, "avg_line_length": 58.39215850830078, "blob_id": "dd48473cef7e3fa38384cecb41ffc9092d2957da", "content_id": "64b7f87232570dcca65824d1f9331c9ae75a6409", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9148, "license_type": "no_license", "max_line_length": 89, "num_lines": 153, "path": "/parameter2.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_Form(object):\n def setupUi(self, Form):\n Form.setObjectName(\"Form\")\n Form.resize(398, 494)\n self.verticalLayout = QtWidgets.QVBoxLayout(Form)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.groupBox = QtWidgets.QGroupBox(Form)\n self.groupBox.setObjectName(\"groupBox\")\n self.gridLayoutWidget_2 = QtWidgets.QWidget(self.groupBox)\n self.gridLayoutWidget_2.setGeometry(QtCore.QRect(9, 9, 351, 61))\n self.gridLayoutWidget_2.setObjectName(\"gridLayoutWidget_2\")\n self.gridLayout_2 = QtWidgets.QGridLayout(self.gridLayoutWidget_2)\n self.gridLayout_2.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)\n self.gridLayout_2.setContentsMargins(0, 0, 0, 0)\n self.gridLayout_2.setObjectName(\"gridLayout_2\")\n self.lineEdit = QtWidgets.QLineEdit(self.gridLayoutWidget_2)\n self.lineEdit.setObjectName(\"lineEdit\")\n self.gridLayout_2.addWidget(self.lineEdit, 0, 2, 1, 1)\n self.label_2 = QtWidgets.QLabel(self.gridLayoutWidget_2)\n self.label_2.setObjectName(\"label_2\")\n self.gridLayout_2.addWidget(self.label_2, 0, 3, 1, 1)\n self.label = QtWidgets.QLabel(self.gridLayoutWidget_2)\n self.label.setObjectName(\"label\")\n self.gridLayout_2.addWidget(self.label, 0, 0, 1, 1)\n self.comboBox = QtWidgets.QComboBox(self.gridLayoutWidget_2)\n self.comboBox.setObjectName(\"comboBox\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.gridLayout_2.addWidget(self.comboBox, 0, 4, 1, 1)\n self.label_3 = QtWidgets.QLabel(self.gridLayoutWidget_2)\n self.label_3.setObjectName(\"label_3\")\n self.gridLayout_2.addWidget(self.label_3, 1, 0, 1, 1)\n self.label_4 = QtWidgets.QLabel(self.gridLayoutWidget_2)\n self.label_4.setObjectName(\"label_4\")\n self.gridLayout_2.addWidget(self.label_4, 1, 3, 1, 1)\n self.dateEdit_2 = QtWidgets.QDateEdit(self.gridLayoutWidget_2)\n self.dateEdit_2.setObjectName(\"dateEdit_2\")\n self.gridLayout_2.addWidget(self.dateEdit_2, 1, 4, 1, 1)\n self.dateEdit = QtWidgets.QDateEdit(self.gridLayoutWidget_2)\n self.dateEdit.setObjectName(\"dateEdit\")\n self.gridLayout_2.addWidget(self.dateEdit, 1, 2, 1, 1)\n self.verticalLayout.addWidget(self.groupBox)\n self.groupBox_5 = QtWidgets.QGroupBox(Form)\n self.groupBox_5.setObjectName(\"groupBox_5\")\n self.pushButton_3 = QtWidgets.QPushButton(self.groupBox_5)\n self.pushButton_3.setGeometry(QtCore.QRect(20, 20, 75, 23))\n self.pushButton_3.setObjectName(\"pushButton_3\")\n self.label_11 = QtWidgets.QLabel(self.groupBox_5)\n self.label_11.setGeometry(QtCore.QRect(110, 30, 54, 12))\n self.label_11.setObjectName(\"label_11\")\n self.verticalLayout.addWidget(self.groupBox_5)\n self.groupBox_2 = QtWidgets.QGroupBox(Form)\n self.groupBox_2.setObjectName(\"groupBox_2\")\n self.gridLayoutWidget = QtWidgets.QWidget(self.groupBox_2)\n self.gridLayoutWidget.setGeometry(QtCore.QRect(10, 10, 351, 80))\n self.gridLayoutWidget.setObjectName(\"gridLayoutWidget\")\n self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)\n self.gridLayout.setContentsMargins(0, 0, 0, 0)\n self.gridLayout.setObjectName(\"gridLayout\")\n self.label_5 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_5.setObjectName(\"label_5\")\n self.gridLayout.addWidget(self.label_5, 0, 0, 1, 1)\n self.label_7 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_7.setObjectName(\"label_7\")\n self.gridLayout.addWidget(self.label_7, 0, 4, 1, 1)\n self.lineEdit_ma_n3 = QtWidgets.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n3.setObjectName(\"lineEdit_ma_n3\")\n self.gridLayout.addWidget(self.lineEdit_ma_n3, 0, 5, 1, 1)\n self.lineEdit_ma_n2 = QtWidgets.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n2.setObjectName(\"lineEdit_ma_n2\")\n self.gridLayout.addWidget(self.lineEdit_ma_n2, 0, 3, 1, 1)\n self.label_6 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_6.setObjectName(\"label_6\")\n self.gridLayout.addWidget(self.label_6, 0, 2, 1, 1)\n self.lineEdit_ma_n1 = QtWidgets.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n1.setObjectName(\"lineEdit_ma_n1\")\n self.gridLayout.addWidget(self.lineEdit_ma_n1, 0, 1, 1, 1)\n self.label_8 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_8.setObjectName(\"label_8\")\n self.gridLayout.addWidget(self.label_8, 1, 0, 1, 1)\n self.lineEdit_ma_n4 = QtWidgets.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n4.setObjectName(\"lineEdit_ma_n4\")\n self.gridLayout.addWidget(self.lineEdit_ma_n4, 1, 1, 1, 1)\n self.label_9 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_9.setObjectName(\"label_9\")\n self.gridLayout.addWidget(self.label_9, 1, 2, 1, 1)\n self.lineEdit_ma_n5 = QtWidgets.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n5.setObjectName(\"lineEdit_ma_n5\")\n self.gridLayout.addWidget(self.lineEdit_ma_n5, 1, 3, 1, 1)\n self.label_10 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_10.setObjectName(\"label_10\")\n self.gridLayout.addWidget(self.label_10, 1, 4, 1, 1)\n self.comboBox_ma = QtWidgets.QComboBox(self.gridLayoutWidget)\n self.comboBox_ma.setObjectName(\"comboBox_ma\")\n self.comboBox_ma.addItem(\"\")\n self.comboBox_ma.addItem(\"\")\n self.gridLayout.addWidget(self.comboBox_ma, 1, 5, 1, 1)\n self.verticalLayout.addWidget(self.groupBox_2)\n self.groupBox_3 = QtWidgets.QGroupBox(Form)\n self.groupBox_3.setObjectName(\"groupBox_3\")\n self.verticalLayout.addWidget(self.groupBox_3)\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.pushButton = QtWidgets.QPushButton(Form)\n self.pushButton.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.pushButton.setObjectName(\"pushButton\")\n self.horizontalLayout.addWidget(self.pushButton)\n self.pushButton_2 = QtWidgets.QPushButton(Form)\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.horizontalLayout.addWidget(self.pushButton_2)\n self.verticalLayout.addLayout(self.horizontalLayout)\n\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(QtWidgets.QApplication.translate(\"Form\", \"Form\"))\n self.groupBox.setTitle(QtWidgets.QApplication.translate(\"Form\", \"公共参数\"))\n self.label_2.setText(QtWidgets.QApplication.translate(\"Form\", \"周期\"))\n self.label.setText(QtWidgets.QApplication.translate(\"Form\", \"合约\"))\n self.comboBox.setItemText(0, QtWidgets.QApplication.translate(\"Form\", \"0\"))\n self.comboBox.setItemText(1, QtWidgets.QApplication.translate(\"Form\", \"60\"))\n self.comboBox.setItemText(2, QtWidgets.QApplication.translate(\"Form\", \"300\"))\n self.comboBox.setItemText(3, QtWidgets.QApplication.translate(\"Form\", \"600\"))\n self.comboBox.setItemText(4, QtWidgets.QApplication.translate(\"Form\", \"900\"))\n self.comboBox.setItemText(5, QtWidgets.QApplication.translate(\"Form\", \"1800\"))\n self.comboBox.setItemText(6, QtWidgets.QApplication.translate(\"Form\", \"3600\"))\n self.label_3.setText(QtWidgets.QApplication.translate(\"Form\", \"开始时间\"))\n self.label_4.setText(QtWidgets.QApplication.translate(\"Form\", \"结束时间\"))\n self.groupBox_5.setTitle(QtWidgets.QApplication.translate(\"Form\", \"回测文件\"))\n self.pushButton_3.setText(QtWidgets.QApplication.translate(\"Form\", \"PushButton\"))\n self.label_11.setText(QtWidgets.QApplication.translate(\"Form\", \"TextLabel\"))\n self.groupBox_2.setTitle(QtWidgets.QApplication.translate(\"Form\", \"MA参数\"))\n self.label_5.setText(QtWidgets.QApplication.translate(\"Form\", \"N1\"))\n self.label_7.setText(QtWidgets.QApplication.translate(\"Form\", \"N3\"))\n self.label_6.setText(QtWidgets.QApplication.translate(\"Form\", \"N2\"))\n self.label_8.setText(QtWidgets.QApplication.translate(\"Form\", \"N4\"))\n self.label_9.setText(QtWidgets.QApplication.translate(\"Form\", \"N5\"))\n self.label_10.setText(QtWidgets.QApplication.translate(\"Form\", \"算法\"))\n self.comboBox_ma.setItemText(0, QtWidgets.QApplication.translate(\"Form\", \"MA\"))\n self.comboBox_ma.setItemText(1, QtWidgets.QApplication.translate(\"Form\", \"EMA\"))\n self.groupBox_3.setTitle(QtWidgets.QApplication.translate(\"Form\", \"MACD参数\"))\n self.pushButton.setText(QtWidgets.QApplication.translate(\"Form\", \"确定\"))\n self.pushButton_2.setText(QtWidgets.QApplication.translate(\"Form\", \"取消\"))\n\n" }, { "alpha_fraction": 0.6389734148979187, "alphanum_fraction": 0.649821400642395, "avg_line_length": 45.09756088256836, "blob_id": "35f3f28833d13bcfdf0624b0f6227acad2b4a088", "content_id": "4c9ad1f53c825aed90338cd4986b9b6f5173ba56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7779, "license_type": "no_license", "max_line_length": 126, "num_lines": 164, "path": "/KViewer_new.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom Indexer import *\nimport pyqtgraph as pg\nimport pandas as pd\nfrom ChildGraph import ChildGraph\nimport DataInterface.DataInterface as DI\n\n\nclass KViewer(QWidget):\n\n def __init__(self,):\n super(KViewer, self).__init__()\n self.raw_data = None\n self.main_layout = QVBoxLayout(self)\n self.setting_layout = QHBoxLayout(self)\n self.child_graph_layout = QVBoxLayout(self)\n self.region = pg.LinearRegionItem()\n self.region_minx = 0 # region控制框的宽度\n self.region_maxx = 0\n self.range_control_plt = pg.PlotWidget()\n self.setting_view_btn = QPushButton('显示')\n self.setting_add_child_btn = QPushButton('增加子图')\n self.setting_remove_child_btn = QPushButton('删除子图')\n self.setting_end_date = QDateEdit()\n self.setting_start_date = QDateEdit()\n self.setting_bar_type_cb = QComboBox()\n self.setting_symbol_edit = QLineEdit() # 品种\n self.setting_exchange_cb = QComboBox()\n #self.setting_exchange_edit = QLineEdit() # 交易所\n self.setting_contract_edit = QLineEdit() # 合约\n self.setting_dic = {}\n self.setup_ui()\n self.setup_range_control_view()\n self.main_child_graph = ChildGraph(False)\n self.main_child_graph.main_child_plt_changed.connect(self.main_child_plt_changed)\n self.child_graph_list = []\n second_child_graph = ChildGraph(True)\n self.child_graph_list.append(second_child_graph)\n self.child_graph_layout.addWidget(self.main_child_graph,stretch=2)\n self.child_graph_layout.addWidget(second_child_graph, stretch=2)\n self.child_graph_layout.addWidget(self.range_control_plt, stretch=1)\n self.main_layout.addLayout(self.setting_layout)\n self.main_layout.addLayout(self.child_graph_layout)\n self.setLayout(self.main_layout)\n\n def setup_ui(self):\n self.setup_ui_header()\n\n def setup_ui_header(self):\n self.setting_layout.addWidget(QLabel('交易所'))\n self.setting_exchange_cb.addItems(['SHFE', 'DCE', 'CZCE', 'CFFEX'])\n self.setting_layout.addWidget(self.setting_exchange_cb)\n #self.setting_layout.addWidget(self.setting_exchange_edit)\n self.setting_layout.addWidget(QLabel('品种'))\n self.setting_layout.addWidget(self.setting_symbol_edit)\n self.setting_layout.addWidget(QLabel('合约'))\n self.setting_layout.addWidget(self.setting_contract_edit)\n self.setting_layout.addWidget(QLabel('周期'))\n self.setting_bar_type_cb.addItems(['0','60','300','600','900','1800','3600'])\n self.setting_layout.addWidget(self.setting_bar_type_cb)\n self.setting_start_date.setDisplayFormat(\"yyyy-MM-dd\")\n self.setting_end_date.setDisplayFormat(\"yyyy-MM-dd\")\n self.setting_layout.addWidget(QLabel('开始日期'))\n self.setting_layout.addWidget(self.setting_start_date)\n self.setting_layout.addWidget(QLabel('结束日期'))\n self.setting_layout.addWidget(self.setting_end_date)\n self.setting_view_btn.clicked.connect(self.get_setting)\n self.setting_layout.addWidget(self.setting_view_btn)\n self.setting_layout.addWidget(self.setting_add_child_btn)\n self.setting_layout.addWidget(self.setting_remove_child_btn)\n self.setting_add_child_btn.clicked.connect(self.add_child_graph)\n self.setting_remove_child_btn.clicked.connect(self.remove_child_graph)\n\n def setup_range_control_view(self):\n # 下面第2个图的范围设置框\n self.region.setZValue(10)\n self.range_control_plt.addItem(self.region)\n #self.range_control_plt.plot(x=x,y=y, pen=\"w\", name='close')\n\n def get_setting(self):\n exchange = self.setting_exchange_cb.currentText()\n symbol = self.setting_symbol_edit.text()\n contract = self.setting_contract_edit.text()\n bar_type = int(self.setting_bar_type_cb.currentText())\n start_date = self.setting_start_date.date().toString(\"yyyy-MM-dd\")\n end_date = self.setting_end_date.date().toString(\"yyyy-MM-dd\")\n self.setting_dic['exchange'] = exchange\n self.setting_dic['symbol'] = symbol\n self.setting_dic['contract'] = contract\n self.setting_dic['period'] = bar_type\n self.setting_dic['start_date'] = start_date\n self.setting_dic['end_date'] = end_date\n self.setup_child_graph()\n\n def setup_child_graph(self):\n domain_symbol = '.'.join([self.setting_dic['exchange'], self.setting_dic['symbol']])\n contract = self.setting_dic['contract']\n bar_type = self.setting_dic['period']\n start_date = self.setting_dic['start_date']\n end_date = self.setting_dic['end_date']\n self.raw_data = DI.getBarBySymbol(domain_symbol, contract, bar_type, start_date + ' 09:00:00', end_date + ' 15:00:00')\n #self.raw_data = pd.read_excel('RB1810_2018-06-19_1m.xlsx')\n self.main_child_graph.set_raw_data(self.raw_data)\n for second_child_graph in self.child_graph_list:\n second_child_graph.set_raw_data(self.raw_data)\n self.range_control_plt.plot(self.raw_data['close'], pen=\"w\", name='close')\n self.region.sigRegionChanged.connect(self.set_child_range)\n self.region.setRegion([0, 100])\n pass\n\n def set_child_range(self):\n #self.region.setZValue(10)\n minX, maxX = self.region.getRegion()\n self.main_child_graph.update_visual_range(int(minX), int(maxX))\n for second_child_graph in self.child_graph_list:\n second_child_graph.update_visual_range(int(minX), int(maxX))\n\n def update_region(self,window, viewRange):\n rgn = viewRange[0]\n self.region.setRegion(rgn)\n self.region_minx, self.region_maxx = self.region.getRegion()\n\n def main_child_plt_changed(self):\n self.main_child_graph.plt.sigRangeChanged.connect(self.update_region)\n self.proxy = pg.SignalProxy(self.main_child_graph.plt.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)\n\n def mouseMoved(self, event):\n pos = event[0] ## using signal proxy turns original arguments into a tuple\n if self.main_child_graph.plt.sceneBoundingRect().contains(pos):\n a = self.main_child_graph.plt.boundingRect().getRect()\n knum = self.region_maxx - self.region_minx\n # (pos.x()-35)表示鼠标点距离左边框的位置\n # (a[2]-35)/knum表示每一根K线占用的像素点数量\n # 上面两者两除即为鼠标位置点的K线序号,+minx就是在整个数据列表中的位置\n rx = int((pos.x()-35)/((a[2]-35)/knum)+ self.region_minx)\n index = rx\n #if index > 0 and index < len(self.t):\n self.main_child_graph.set_indexer_label(index)\n for second_child_graph in self.child_graph_list:\n second_child_graph.set_indexer_label(index)\n\n def add_child_graph(self):\n second_child_graph = ChildGraph(True)\n self.child_graph_list.append(second_child_graph)\n if self.raw_data is not None:\n second_child_graph.set_raw_data(self.raw_data)\n self.child_graph_layout.insertWidget(len(self.child_graph_list), second_child_graph, stretch=2)\n\n def remove_child_graph(self):\n if self.child_graph_list:\n self.child_graph_layout.removeWidget(self.child_graph_list[-1])\n self.child_graph_list[-1].deleteLater()\n del self.child_graph_list[-1]\n pass\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n demo = KViewer()\n demo.show()\n sys.exit(app.exec_())" }, { "alpha_fraction": 0.6632421612739563, "alphanum_fraction": 0.6998022198677063, "avg_line_length": 64.60759735107422, "blob_id": "b506f964ee0512e6f59296271c54398daeae5f89", "content_id": "155dc0fa8afeca9e0c1759e772f5ee72572d3333", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20829, "license_type": "no_license", "max_line_length": 128, "num_lines": 316, "path": "/kviewer2.py", "repo_name": "smartgang/KViewer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(800, 600)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())\n self.centralwidget.setSizePolicy(sizePolicy)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.centralwidget)\n self.verticalLayout_2.setObjectName(\"verticalLayout_2\")\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.gridLayout = QtWidgets.QGridLayout()\n self.gridLayout.setObjectName(\"gridLayout\")\n self.groupBox = QtWidgets.QGroupBox(self.centralwidget)\n self.groupBox.setObjectName(\"groupBox\")\n self.checkBox_ma = QtWidgets.QCheckBox(self.groupBox)\n self.checkBox_ma.setGeometry(QtCore.QRect(40, 10, 71, 16))\n self.checkBox_ma.setObjectName(\"checkBox_ma\")\n self.checkBox_dmi = QtWidgets.QCheckBox(self.groupBox)\n self.checkBox_dmi.setGeometry(QtCore.QRect(40, 30, 71, 16))\n self.checkBox_dmi.setObjectName(\"checkBox_dmi\")\n self.checkBox_macd = QtWidgets.QCheckBox(self.groupBox)\n self.checkBox_macd.setGeometry(QtCore.QRect(140, 10, 71, 16))\n self.checkBox_macd.setObjectName(\"checkBox_macd\")\n self.checkBox_kdj = QtWidgets.QCheckBox(self.groupBox)\n self.checkBox_kdj.setGeometry(QtCore.QRect(250, 10, 71, 16))\n self.checkBox_kdj.setObjectName(\"checkBox_kdj\")\n self.checkBox_5 = QtWidgets.QCheckBox(self.groupBox)\n self.checkBox_5.setGeometry(QtCore.QRect(140, 30, 71, 16))\n self.checkBox_5.setObjectName(\"checkBox_5\")\n self.checkBox_6 = QtWidgets.QCheckBox(self.groupBox)\n self.checkBox_6.setGeometry(QtCore.QRect(250, 30, 71, 16))\n self.checkBox_6.setObjectName(\"checkBox_6\")\n self.gridLayout.addWidget(self.groupBox, 0, 0, 2, 1)\n self.pushButton_draw = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_draw.setObjectName(\"pushButton_draw\")\n self.gridLayout.addWidget(self.pushButton_draw, 1, 1, 1, 1)\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton.setObjectName(\"pushButton\")\n self.gridLayout.addWidget(self.pushButton, 0, 1, 1, 1)\n self.horizontalLayout.addLayout(self.gridLayout)\n self.verticalLayout_2.addLayout(self.horizontalLayout)\n self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)\n self.tabWidget.setObjectName(\"tabWidget\")\n self.tab_plot = QtWidgets.QWidget()\n self.tab_plot.setObjectName(\"tab_plot\")\n self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.tab_plot)\n self.verticalLayout_3.setObjectName(\"verticalLayout_3\")\n self.verticalLayout = QtWidgets.QVBoxLayout()\n self.verticalLayout.setContentsMargins(-1, -1, -1, 0)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.horizontalLayout_plot_field = QtWidgets.QHBoxLayout()\n self.horizontalLayout_plot_field.setObjectName(\"horizontalLayout_plot_field\")\n self.label_para = QtWidgets.QLabel(self.tab_plot)\n self.label_para.setFrameShape(QtWidgets.QFrame.Box)\n self.label_para.setObjectName(\"label_para\")\n self.horizontalLayout_plot_field.addWidget(self.label_para)\n self.label_point = QtWidgets.QLabel(self.tab_plot)\n self.label_point.setFrameShape(QtWidgets.QFrame.Box)\n self.label_point.setObjectName(\"label_point\")\n self.horizontalLayout_plot_field.addWidget(self.label_point)\n self.label_file = QtWidgets.QLabel(self.tab_plot)\n self.label_file.setFrameShape(QtWidgets.QFrame.Box)\n self.label_file.setObjectName(\"label_file\")\n self.horizontalLayout_plot_field.addWidget(self.label_file)\n self.verticalLayout.addLayout(self.horizontalLayout_plot_field)\n self.verticalLayout_3.addLayout(self.verticalLayout)\n self.tabWidget.addTab(self.tab_plot, \"\")\n self.tab_para = QtWidgets.QWidget()\n self.tab_para.setObjectName(\"tab_para\")\n self.groupBox_3 = QtWidgets.QGroupBox(self.tab_para)\n self.groupBox_3.setGeometry(QtCore.QRect(400, 110, 361, 91))\n self.groupBox_3.setObjectName(\"groupBox_3\")\n self.label = QtWidgets.QLabel(self.groupBox_3)\n self.label.setGeometry(QtCore.QRect(30, 40, 41, 16))\n self.label.setObjectName(\"label\")\n self.lineEdit_macd_short = QtWidgets.QLineEdit(self.groupBox_3)\n self.lineEdit_macd_short.setGeometry(QtCore.QRect(80, 40, 41, 20))\n self.lineEdit_macd_short.setObjectName(\"lineEdit_macd_short\")\n self.label_2 = QtWidgets.QLabel(self.groupBox_3)\n self.label_2.setGeometry(QtCore.QRect(150, 40, 31, 16))\n self.label_2.setObjectName(\"label_2\")\n self.lineEdit_macd_long = QtWidgets.QLineEdit(self.groupBox_3)\n self.lineEdit_macd_long.setGeometry(QtCore.QRect(190, 40, 41, 20))\n self.lineEdit_macd_long.setObjectName(\"lineEdit_macd_long\")\n self.label_3 = QtWidgets.QLabel(self.groupBox_3)\n self.label_3.setGeometry(QtCore.QRect(260, 40, 21, 16))\n self.label_3.setObjectName(\"label_3\")\n self.lineEdit_macd_m = QtWidgets.QLineEdit(self.groupBox_3)\n self.lineEdit_macd_m.setGeometry(QtCore.QRect(280, 40, 41, 20))\n self.lineEdit_macd_m.setObjectName(\"lineEdit_macd_m\")\n self.groupBox_2 = QtWidgets.QGroupBox(self.tab_para)\n self.groupBox_2.setGeometry(QtCore.QRect(20, 110, 371, 90))\n self.groupBox_2.setObjectName(\"groupBox_2\")\n self.gridLayoutWidget = QtWidgets.QWidget(self.groupBox_2)\n self.gridLayoutWidget.setGeometry(QtCore.QRect(10, 10, 351, 80))\n self.gridLayoutWidget.setObjectName(\"gridLayoutWidget\")\n self.gridLayout_2 = QtWidgets.QGridLayout(self.gridLayoutWidget)\n self.gridLayout_2.setContentsMargins(0, 0, 0, 0)\n self.gridLayout_2.setObjectName(\"gridLayout_2\")\n self.label_5 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_5.setObjectName(\"label_5\")\n self.gridLayout_2.addWidget(self.label_5, 0, 0, 1, 1)\n self.label_7 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_7.setObjectName(\"label_7\")\n self.gridLayout_2.addWidget(self.label_7, 0, 4, 1, 1)\n self.lineEdit_ma_n3 = QtWidgets.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n3.setObjectName(\"lineEdit_ma_n3\")\n self.gridLayout_2.addWidget(self.lineEdit_ma_n3, 0, 5, 1, 1)\n self.lineEdit_ma_n2 = QtWidgets.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n2.setObjectName(\"lineEdit_ma_n2\")\n self.gridLayout_2.addWidget(self.lineEdit_ma_n2, 0, 3, 1, 1)\n self.label_6 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_6.setObjectName(\"label_6\")\n self.gridLayout_2.addWidget(self.label_6, 0, 2, 1, 1)\n self.lineEdit_ma_n1 = QtWidgets.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n1.setObjectName(\"lineEdit_ma_n1\")\n self.gridLayout_2.addWidget(self.lineEdit_ma_n1, 0, 1, 1, 1)\n self.label_8 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_8.setObjectName(\"label_8\")\n self.gridLayout_2.addWidget(self.label_8, 1, 0, 1, 1)\n self.lineEdit_ma_n4 = QtWidgets.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n4.setObjectName(\"lineEdit_ma_n4\")\n self.gridLayout_2.addWidget(self.lineEdit_ma_n4, 1, 1, 1, 1)\n self.label_9 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_9.setObjectName(\"label_9\")\n self.gridLayout_2.addWidget(self.label_9, 1, 2, 1, 1)\n self.lineEdit_ma_n5 = QtWidgets.QLineEdit(self.gridLayoutWidget)\n self.lineEdit_ma_n5.setObjectName(\"lineEdit_ma_n5\")\n self.gridLayout_2.addWidget(self.lineEdit_ma_n5, 1, 3, 1, 1)\n self.label_10 = QtWidgets.QLabel(self.gridLayoutWidget)\n self.label_10.setObjectName(\"label_10\")\n self.gridLayout_2.addWidget(self.label_10, 1, 4, 1, 1)\n self.comboBox_ma = QtWidgets.QComboBox(self.gridLayoutWidget)\n self.comboBox_ma.setObjectName(\"comboBox_ma\")\n self.comboBox_ma.addItem(\"\")\n self.comboBox_ma.addItem(\"\")\n self.gridLayout_2.addWidget(self.comboBox_ma, 1, 5, 1, 1)\n self.groupBox_5 = QtWidgets.QGroupBox(self.tab_para)\n self.groupBox_5.setGeometry(QtCore.QRect(400, 10, 361, 91))\n self.groupBox_5.setObjectName(\"groupBox_5\")\n self.pushButton_opr_file = QtWidgets.QPushButton(self.groupBox_5)\n self.pushButton_opr_file.setGeometry(QtCore.QRect(30, 40, 75, 23))\n self.pushButton_opr_file.setObjectName(\"pushButton_opr_file\")\n self.label_opr = QtWidgets.QLabel(self.groupBox_5)\n self.label_opr.setGeometry(QtCore.QRect(130, 40, 54, 12))\n self.label_opr.setObjectName(\"label_opr\")\n self.groupBox_4 = QtWidgets.QGroupBox(self.tab_para)\n self.groupBox_4.setGeometry(QtCore.QRect(20, 10, 371, 90))\n self.groupBox_4.setObjectName(\"groupBox_4\")\n self.gridLayoutWidget_2 = QtWidgets.QWidget(self.groupBox_4)\n self.gridLayoutWidget_2.setGeometry(QtCore.QRect(9, 9, 351, 61))\n self.gridLayoutWidget_2.setObjectName(\"gridLayoutWidget_2\")\n self.gridLayout_3 = QtWidgets.QGridLayout(self.gridLayoutWidget_2)\n self.gridLayout_3.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)\n self.gridLayout_3.setContentsMargins(0, 0, 0, 0)\n self.gridLayout_3.setObjectName(\"gridLayout_3\")\n self.lineEdit_contract = QtWidgets.QLineEdit(self.gridLayoutWidget_2)\n self.lineEdit_contract.setObjectName(\"lineEdit_contract\")\n self.gridLayout_3.addWidget(self.lineEdit_contract, 0, 2, 1, 1)\n self.label_4 = QtWidgets.QLabel(self.gridLayoutWidget_2)\n self.label_4.setObjectName(\"label_4\")\n self.gridLayout_3.addWidget(self.label_4, 0, 3, 1, 1)\n self.label_12 = QtWidgets.QLabel(self.gridLayoutWidget_2)\n self.label_12.setObjectName(\"label_12\")\n self.gridLayout_3.addWidget(self.label_12, 0, 0, 1, 1)\n self.comboBox_bar = QtWidgets.QComboBox(self.gridLayoutWidget_2)\n self.comboBox_bar.setObjectName(\"comboBox_bar\")\n self.comboBox_bar.addItem(\"\")\n self.comboBox_bar.addItem(\"\")\n self.comboBox_bar.addItem(\"\")\n self.comboBox_bar.addItem(\"\")\n self.comboBox_bar.addItem(\"\")\n self.comboBox_bar.addItem(\"\")\n self.comboBox_bar.addItem(\"\")\n self.gridLayout_3.addWidget(self.comboBox_bar, 0, 4, 1, 1)\n self.label_13 = QtWidgets.QLabel(self.gridLayoutWidget_2)\n self.label_13.setObjectName(\"label_13\")\n self.gridLayout_3.addWidget(self.label_13, 1, 0, 1, 1)\n self.label_14 = QtWidgets.QLabel(self.gridLayoutWidget_2)\n self.label_14.setObjectName(\"label_14\")\n self.gridLayout_3.addWidget(self.label_14, 1, 3, 1, 1)\n self.dateEdit_end = QtWidgets.QDateEdit(self.gridLayoutWidget_2)\n self.dateEdit_end.setDateTime(QtCore.QDateTime(QtCore.QDate(2018, 6, 30), QtCore.QTime(0, 0, 0)))\n self.dateEdit_end.setObjectName(\"dateEdit_end\")\n self.gridLayout_3.addWidget(self.dateEdit_end, 1, 4, 1, 1)\n self.dateEdit_start = QtWidgets.QDateEdit(self.gridLayoutWidget_2)\n self.dateEdit_start.setObjectName(\"dateEdit_start\")\n self.gridLayout_3.addWidget(self.dateEdit_start, 1, 2, 1, 1)\n self.pushButton_set_para = QtWidgets.QPushButton(self.tab_para)\n self.pushButton_set_para.setGeometry(QtCore.QRect(360, 330, 75, 23))\n self.pushButton_set_para.setObjectName(\"pushButton_set_para\")\n self.groupBox_6 = QtWidgets.QGroupBox(self.tab_para)\n self.groupBox_6.setGeometry(QtCore.QRect(20, 210, 371, 80))\n self.groupBox_6.setObjectName(\"groupBox_6\")\n self.lineEdit_kdj_n = QtWidgets.QLineEdit(self.groupBox_6)\n self.lineEdit_kdj_n.setGeometry(QtCore.QRect(40, 30, 51, 20))\n self.lineEdit_kdj_n.setObjectName(\"lineEdit_kdj_n\")\n self.lineEdit_kdj_m1 = QtWidgets.QLineEdit(self.groupBox_6)\n self.lineEdit_kdj_m1.setGeometry(QtCore.QRect(160, 30, 51, 20))\n self.lineEdit_kdj_m1.setObjectName(\"lineEdit_kdj_m1\")\n self.lineEdit_kdj_m2 = QtWidgets.QLineEdit(self.groupBox_6)\n self.lineEdit_kdj_m2.setGeometry(QtCore.QRect(270, 30, 51, 20))\n self.lineEdit_kdj_m2.setObjectName(\"lineEdit_kdj_m2\")\n self.label_11 = QtWidgets.QLabel(self.groupBox_6)\n self.label_11.setGeometry(QtCore.QRect(20, 30, 21, 16))\n self.label_11.setObjectName(\"label_11\")\n self.label_15 = QtWidgets.QLabel(self.groupBox_6)\n self.label_15.setGeometry(QtCore.QRect(140, 30, 21, 16))\n self.label_15.setObjectName(\"label_15\")\n self.label_16 = QtWidgets.QLabel(self.groupBox_6)\n self.label_16.setGeometry(QtCore.QRect(250, 30, 21, 16))\n self.label_16.setObjectName(\"label_16\")\n self.groupBox_7 = QtWidgets.QGroupBox(self.tab_para)\n self.groupBox_7.setGeometry(QtCore.QRect(400, 210, 361, 81))\n self.groupBox_7.setObjectName(\"groupBox_7\")\n self.lineEdit_dmi_n = QtWidgets.QLineEdit(self.groupBox_7)\n self.lineEdit_dmi_n.setGeometry(QtCore.QRect(70, 30, 41, 20))\n self.lineEdit_dmi_n.setObjectName(\"lineEdit_dmi_n\")\n self.lineEdit_dmi_m = QtWidgets.QLineEdit(self.groupBox_7)\n self.lineEdit_dmi_m.setGeometry(QtCore.QRect(190, 30, 41, 20))\n self.lineEdit_dmi_m.setObjectName(\"lineEdit_dmi_m\")\n self.label_17 = QtWidgets.QLabel(self.groupBox_7)\n self.label_17.setGeometry(QtCore.QRect(40, 30, 31, 16))\n self.label_17.setObjectName(\"label_17\")\n self.label_18 = QtWidgets.QLabel(self.groupBox_7)\n self.label_18.setGeometry(QtCore.QRect(170, 30, 21, 16))\n self.label_18.setObjectName(\"label_18\")\n self.tabWidget.addTab(self.tab_para, \"\")\n self.verticalLayout_2.addWidget(self.tabWidget)\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n self.tabWidget.setCurrentIndex(0)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(QtWidgets.QApplication.translate(\"MainWindow\", \"MainWindow\"))\n self.groupBox.setTitle(QtWidgets.QApplication.translate(\"MainWindow\", \"指标开关\"))\n self.checkBox_ma.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"MA\"))\n self.checkBox_dmi.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"DMI\"))\n self.checkBox_macd.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"MACD\"))\n self.checkBox_kdj.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"KDJ\"))\n self.checkBox_5.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"CheckBox\"))\n self.checkBox_6.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"CheckBox\"))\n self.pushButton_draw.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"绘图\"))\n self.pushButton.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"设置参数\"))\n self.label_para.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"TextLabel\"))\n self.label_point.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"TextLabel\"))\n self.label_file.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"TextLabel\"))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_plot), QtWidgets.QApplication.translate(\"MainWindow\", \"行情\"))\n self.groupBox_3.setTitle(QtWidgets.QApplication.translate(\"MainWindow\", \"MACD参数\"))\n self.label.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"Short\"))\n self.lineEdit_macd_short.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"12\"))\n self.label_2.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"Long\"))\n self.lineEdit_macd_long.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"26\"))\n self.label_3.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"M\"))\n self.lineEdit_macd_m.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"9\"))\n self.groupBox_2.setTitle(QtWidgets.QApplication.translate(\"MainWindow\", \"MA参数\"))\n self.label_5.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"N1\"))\n self.label_7.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"N3\"))\n self.lineEdit_ma_n3.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"20\"))\n self.lineEdit_ma_n2.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"10\"))\n self.label_6.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"N2\"))\n self.lineEdit_ma_n1.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"5\"))\n self.label_8.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"N4\"))\n self.lineEdit_ma_n4.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"30\"))\n self.label_9.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"N5\"))\n self.lineEdit_ma_n5.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"50\"))\n self.label_10.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"算法\"))\n self.comboBox_ma.setItemText(0, QtWidgets.QApplication.translate(\"MainWindow\", \"MA\"))\n self.comboBox_ma.setItemText(1, QtWidgets.QApplication.translate(\"MainWindow\", \"EMA\"))\n self.groupBox_5.setTitle(QtWidgets.QApplication.translate(\"MainWindow\", \"回测文件\"))\n self.pushButton_opr_file.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"PushButton\"))\n self.label_opr.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"TextLabel\"))\n self.groupBox_4.setTitle(QtWidgets.QApplication.translate(\"MainWindow\", \"公共参数\"))\n self.label_4.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"周期\"))\n self.label_12.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"合约\"))\n self.comboBox_bar.setItemText(0, QtWidgets.QApplication.translate(\"MainWindow\", \"0\"))\n self.comboBox_bar.setItemText(1, QtWidgets.QApplication.translate(\"MainWindow\", \"60\"))\n self.comboBox_bar.setItemText(2, QtWidgets.QApplication.translate(\"MainWindow\", \"300\"))\n self.comboBox_bar.setItemText(3, QtWidgets.QApplication.translate(\"MainWindow\", \"600\"))\n self.comboBox_bar.setItemText(4, QtWidgets.QApplication.translate(\"MainWindow\", \"900\"))\n self.comboBox_bar.setItemText(5, QtWidgets.QApplication.translate(\"MainWindow\", \"1800\"))\n self.comboBox_bar.setItemText(6, QtWidgets.QApplication.translate(\"MainWindow\", \"3600\"))\n self.label_13.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"开始时间\"))\n self.label_14.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"结束时间\"))\n self.pushButton_set_para.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"设置\"))\n self.groupBox_6.setTitle(QtWidgets.QApplication.translate(\"MainWindow\", \"KDJ参数\"))\n self.lineEdit_kdj_n.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"9\"))\n self.lineEdit_kdj_m1.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"3\"))\n self.lineEdit_kdj_m2.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"3\"))\n self.label_11.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"N\"))\n self.label_15.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"M1\"))\n self.label_16.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"M2\"))\n self.groupBox_7.setTitle(QtWidgets.QApplication.translate(\"MainWindow\", \"DMI参数\"))\n self.lineEdit_dmi_n.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"14\"))\n self.lineEdit_dmi_m.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"6\"))\n self.label_17.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"N\"))\n self.label_18.setText(QtWidgets.QApplication.translate(\"MainWindow\", \"M\"))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_para), QtWidgets.QApplication.translate(\"MainWindow\", \"参数设置\"))\n\n" } ]
26
nandreik/RapLyrics-NLP
https://github.com/nandreik/RapLyrics-NLP
5bfd0e41a4a46da0434f58769d4ae5dba6d583d3
a7ab6920ce0267ad0dbfeb357c204405001a28c3
8238e3752e09a1284569fa080b6384688c6bdbd6
refs/heads/master
2022-11-21T04:06:54.266649
2020-07-16T18:44:07
2020-07-16T18:44:07
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.780339777469635, "alphanum_fraction": 0.780339777469635, "avg_line_length": 47.411766052246094, "blob_id": "07c2e781d847c4904cb6189021012827cc9f0591", "content_id": "1832811de438430e5bbf85d9478a044d3a01803f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 824, "license_type": "no_license", "max_line_length": 141, "num_lines": 17, "path": "/README.md", "repo_name": "nandreik/RapLyrics-NLP", "src_encoding": "UTF-8", "text": "# Classyfing-Rap-Subgenres-with-NLP\nThe goal of this project was to use natural language processing to answer a question: \n\n**Can rap lyrics be used to classify a subgenre of rap?**\n\nThis project used three algorithms: \n* neural network\n* decision tree\n* self-implemented K-nearest neighbor \n\nThe dataset was originally taken from Kaggle, and then manually reduced to contain only the data I needed (rap lyrics, etc.). \n\nreport_Andreikin.Nikita.pdf details the different steps of the project such as my approach, my dataset, experiments, results, and conclusion.\n\nvideo_Andreikin.Nikita.txt contains a link to a youtube video which gives a brief summary of the project and the results. \n\n**TLDR: Rap lyrics alone cannot reliably be used to classify the song's rap subgenre, but it was fun to see if it could be possible.** \n" }, { "alpha_fraction": 0.5438902378082275, "alphanum_fraction": 0.5559639930725098, "avg_line_length": 49.73114776611328, "blob_id": "0a3d560356030f330b9e8186e410cdc65fa5d1c1", "content_id": "ce1c518edbe6f00a3cda849544428538906a62fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31564, "license_type": "no_license", "max_line_length": 155, "num_lines": 610, "path": "/RapProject.py", "repo_name": "nandreik/RapLyrics-NLP", "src_encoding": "UTF-8", "text": "# coding=utf-8\r\n# Nikita Andreikin\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport re\r\nfrom nltk.tokenize import word_tokenize\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem.wordnet import WordNetLemmatizer\r\nfrom nltk.stem import PorterStemmer\r\nfrom scipy.spatial import distance\r\nfrom os.path import join\r\nimport time\r\nimport copy\r\nimport math\r\nimport random\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn import neural_network\r\nimport warnings\r\nfrom sklearn import metrics\r\nwarnings.simplefilter('ignore', RuntimeWarning)\r\npd.options.mode.chained_assignment = None # default='warn' Removing Warning\r\n\r\nfilePath = r'C:\\Users\\Nikita\\Desktop\\CS484 Semester Project nandreik\\Dataset' # point to dir of dataset\r\ndataFile = 'songs_dataset.csv' # name of data set\r\nfinalResult = 'result.txt' # the output of the algorithm's run\r\ntrack_results = \"track_of_runs.txt\" # track scores of each run in this file\r\n\r\n\r\ndef read_data(): # read original song data\r\n data = pd.read_csv(join(filePath, dataFile))\r\n return data\r\n\r\n\r\ndef write_data(result, algtype): # write the result of an algorithm to use for accuracy measure\r\n subFile = open(join(filePath, finalResult), \"w+\")\r\n if algtype == \"knn\":\r\n for i in range(len(result)):\r\n subFile.write(result[i])\r\n subFile.write(\"\\n\")\r\n if algtype == \"tree\" or algtype == \"nn\":\r\n for i in range(len(result)):\r\n subFile.write(result[i])\r\n subFile.write(\"\\n\")\r\n subFile.close()\r\n\r\n\r\ndef save_result(algType, dataType, accuracy, prec, rec, f1, k, wordF, wordL): # save results of runs in one file\r\n with open(join(filePath, track_results), \"a\") as subFile:\r\n subFile.write(\"Alg: \")\r\n subFile.write(str(algType))\r\n subFile.write(\"\\t\\t\\tData: \")\r\n subFile.write(str(dataType))\r\n subFile.write(\"\\t\\t\\tAcc: \")\r\n subFile.write(str(accuracy))\r\n subFile.write(\"\\t\\t\\tPrec: \")\r\n subFile.write(str(prec))\r\n subFile.write(\"\\t\\t\\tRec: \")\r\n subFile.write(str(rec))\r\n subFile.write(\"\\t\\t\\tF1: \")\r\n subFile.write(str(f1))\r\n if algType == \"knn\":\r\n subFile.write(\"\\t\")\r\n subFile.write(\" K: \" + str(k))\r\n subFile.write(\" WF: \" + str(wordF))\r\n subFile.write(\" WL: \" + str(wordL))\r\n else:\r\n subFile.write(\"\\t\")\r\n subFile.write(\" WF: \" + str(wordF))\r\n subFile.write(\" WL: \" + str(wordL))\r\n subFile.write(\"\\n\")\r\n\r\n\r\ndef convert_to_num(string): # helper for converting different strings to numbers\r\n string = string.strip()\r\n if \".\" in string:\r\n res = float(string)\r\n elif string.isdigit():\r\n res = int(string)\r\n else:\r\n res = string\r\n return res\r\n\r\n\r\ndef split_data(vectorData, genreData, numSplits): # split data into numSplits folds\r\n songSplits = []\r\n genreSplits = []\r\n data_size = len(vectorData)\r\n splitAmt = int(data_size / numSplits) # get split size\r\n splitFrom = 0\r\n splitTo = splitAmt\r\n for i in range(numSplits): # split data into numSplits sections\r\n if i == numSplits:\r\n songSplit = vectorData[splitFrom:]\r\n genreSplit = genreData[splitFrom:]\r\n else:\r\n songSplit = vectorData[splitFrom:splitTo]\r\n genreSplit = genreData[splitFrom:splitTo]\r\n songSplits.append(songSplit)\r\n genreSplits.append(genreSplit)\r\n splitFrom += splitAmt + 1\r\n splitTo += splitAmt + 1\r\n return songSplits, genreSplits\r\n\r\n\r\ndef format_data(originalData): # format data to be processed\r\n split = originalData.loc[0:]\r\n splitLyrics = split[\"Lyrics\"].values\r\n splitSubGenres = split[\"Subgenre\"].values\r\n for j in range(len(splitLyrics)): # format the lyrics/subgenres of each song in the split\r\n split[\"Subgenre\"].loc[j] = format_string(splitSubGenres[j], False) # Removed Warning for this above\r\n split[\"Lyrics\"].loc[j] = format_string(splitLyrics[j], True)\r\n return split\r\n\r\n\r\ndef format_string(string, isLyric):\r\n if isLyric: # only remove words between brackets for lyrics\r\n string = re.sub(\"[\\(\\[].*?[\\)\\]]\", \"\", string) # added to remove brackets and text in brackets in lyrics [Brackets arent part of lyrics]\r\n string = re.sub('[\\[\\]*.,!:?\\\"\\'«»]', '', string) # strip string for better tokenization\r\n string = re.sub('[-–——]+', ' ', string)\r\n string = string.strip().lower()\r\n string = string.replace('\\n', ' ') # this was added to replace all \\n in lyrics with a space\r\n return string\r\n\r\n\r\ndef process_data(data, wordFrq, wordLen, dataType): # process song lyrics and create vectors for algorithms\r\n bagWords = [] # bag of words\r\n wordCount = [] # word count for each word in bag of words\r\n wordCountVectors = [] # word counts by song\r\n wordVectors = [] # list of arrays of words in each song\r\n songVectors = [] # list of song vectors that hold word counts for each word in BagWords for corresponding song\r\n subGenres = [] # subgenres of each song from 0 to n in split\r\n numSongs = 0 # track number of songs in this split\r\n totalWords = 0\r\n maxSongLyricLength = -1\r\n stopWords = set(stopwords.words(\"english\"))\r\n lemma = WordNetLemmatizer()\r\n stem = PorterStemmer()\r\n for i in range(len(data)): # process each song and its sub-genres in data split\r\n # if i % 100 == 0:\r\n # print \"Processed Songs: \", i\r\n numSongs += 1\r\n lyrics = word_tokenize(data[\"Lyrics\"].loc[i]) # split lyrics into separate word tokens\r\n lyrics = [word for word in lyrics if word.isalpha() and word not in stopWords] # take out numbers/stopwords\r\n subGenres.append(data[\"Subgenre\"].loc[i]) # append the subgenres for this current song\r\n songVectorWords = [] # holds small bag of words for each song\r\n songVectorCount = []\r\n for word in lyrics: # for each word in lyrics\r\n word = stem.stem(word) # stem word\r\n word = lemma.lemmatize(word) # lemmatize word, probably has minimal effect due to slang\r\n if len(word) >= wordLen:\r\n if word not in bagWords: # add word to bag of words\r\n bagWords.append(word)\r\n wordCount.append(1)\r\n else: # if already in BoW, inc its count\r\n index = bagWords.index(word)\r\n wordCount[index] += 1\r\n if word not in songVectorWords: # add word to song vector\r\n songVectorWords.append(word)\r\n songVectorCount.append(1)\r\n else: # if already in vector, inc its count\r\n index = songVectorWords.index(word)\r\n songVectorCount[index] += 1\r\n if len(songVectorCount) > maxSongLyricLength: # check max song length (NOT SURE IF NEEDED)\r\n maxSongLyricLength = len(songVectorCount)\r\n # check word counts in song vectors to be >= wf\r\n newSongVectCount = [] # temp vect arrays\r\n newSongVectWords = []\r\n for i in range(len(songVectorCount)):\r\n if songVectorCount[i] >= wordFrq: # if word count if >= required word frequency, keep word in vector\r\n newSongVectCount.append(songVectorCount[i])\r\n newSongVectWords.append(songVectorWords[i])\r\n wordCountVectors.append(newSongVectCount)\r\n wordVectors.append(newSongVectWords)\r\n\r\n newWords = [] # new bag of words and word count, after removing words under word frequency threshold\r\n newWordCount = []\r\n for j in range(len(bagWords)): # check word counts in bag words\r\n if wordCount[j] >= wordFrq:\r\n newWords.append(bagWords[j])\r\n newWordCount.append(wordCount[j])\r\n totalWords += wordCount[j] # add to total word count\r\n bagWords = newWords\r\n wordCount = newWordCount\r\n\r\n # now that the bag of words and word count is finalized, vectorize the songs\r\n print \"Vectorizing.. \"\r\n for i in range(len(wordVectors)): # for each word song vector, convert it to a word count vector of ALL words in bag of words\r\n # if i % 100 == 0:\r\n # print \"Vectors: \", i\r\n songVector = np.zeros(len(bagWords))\r\n wordVector = wordVectors[i]\r\n wordCountVector = wordCountVectors[i]\r\n for j in range(len(wordVector)): # for each word in vector\r\n word = wordVector[j] # get the word from the current song's words\r\n wordC = wordCountVector[j] # get that word's count in the current song\r\n wordIndBagOfWords = bagWords.index(word) # get words index in BOW\r\n songVector[wordIndBagOfWords] = wordC # update that song's index in the songVector with the current song's word count\r\n songVectors.append(songVector) # add the finished song vector to the list of song vectors\r\n\r\n numSongsWithWord = np.zeros(len(bagWords)) # count of songs that have this word in it\r\n for vector in wordVectors: # for each array of words of each song\r\n for word in vector: # for each word in array\r\n if word in bagWords: # if word in bagwords, update its count for number of songs it is in\r\n wordInd = bagWords.index(word)\r\n numSongsWithWord[wordInd] += 1\r\n\r\n tfVectors = [] # calc tfidf\r\n idfVectors = []\r\n tfidfVectors = []\r\n if dataType == \"tfidf\":\r\n print \"Calculating TFIDF Vectors.. \"\r\n count = 0\r\n for vector in wordVectors: # for each word vector\r\n # if count % 100:\r\n # print \"TFIDF Vectors: \", count\r\n count += 1\r\n tfV = np.zeros(len(bagWords))\r\n idfV = np.zeros(len(bagWords))\r\n tfidfV = np.zeros(len(bagWords))\r\n for i in range(len(vector)): # for each word in vector\r\n word = vector[i]\r\n wordInd = bagWords.index(word) # calc the tfidf value for each word in that vector\r\n tf = float(wordCount[wordInd]) / float(totalWords)\r\n idf = math.log(float(numSongs) / float(numSongsWithWord[wordInd] + 1))\r\n tfidf = tf * idf\r\n tfV[wordInd] = tf\r\n idfV[wordInd] = idf\r\n tfidfV[wordInd] = tfidf\r\n tfVectors.append(tfV) # add the calculated vectors to the vectors lists\r\n idfVectors.append(idfV)\r\n tfidfVectors.append(tfidfV)\r\n return bagWords, wordCount, subGenres, numSongs, songVectors, maxSongLyricLength, tfidfVectors\r\n\r\n\r\ndef process_genres_to_single(data): # convert multilabeled subgenres to single labels by artist\r\n singleDataGenres = [\"\"]*len(data[\"Subgenre\"].values)\r\n artistList = []\r\n subGenreCount = [0]*10\r\n subGenreNames = [\"trap\", \"r&b\", \"alternative\", \"drill\", \"east\", \"west\", \"gangsta\", \"uk\", \"cloud\", \"atlanta\"]\r\n print \"Calculating Major Genre of Artists...\"\r\n for i in range(len(data)): # give each artist's song ONE genre label, based on the artist's majority subgenres\r\n artist = data[\"Artist\"].loc[i]\r\n if artist not in artistList: # if artist has not be processed yet, process\r\n artistList.append(artist)\r\n artistIndexesInData = []\r\n for j in range(len(data)): # for every song by that artist, count the subgenres\r\n if data[\"Artist\"].loc[j] == artist:\r\n artistIndexesInData.append(j)\r\n genre = data[\"Subgenre\"].loc[j]\r\n if \"trap\" in genre: # inc count for each subgenre in the song\r\n subGenreCount[0] += 1\r\n if \"r&b\" in genre:\r\n subGenreCount[1] += 1\r\n if \"alternative\" in genre:\r\n subGenreCount[2] += 1\r\n if \"drill\" in genre:\r\n subGenreCount[3] += 1\r\n if \"east\" in genre:\r\n subGenreCount[4] += 1\r\n if \"west\" in genre:\r\n subGenreCount[5] += 1\r\n if \"gangsta\" in genre:\r\n subGenreCount[6] += 1\r\n if \"uk\" in genre:\r\n subGenreCount[7] += 1\r\n if \"cloud\" in genre:\r\n subGenreCount[8] += 1\r\n if \"atlanta\" in genre:\r\n subGenreCount[9] += 1\r\n # print subGenreCount\r\n majorityGenreCount = -1\r\n majorityGenre = \"\"\r\n for k in range(len(subGenreCount)): # find most popular genre by count\r\n if subGenreCount[k] > majorityGenreCount:\r\n majorityGenreCount = subGenreCount[k]\r\n majorityGenre = subGenreNames[k]\r\n subGenreCount = [0] * 10\r\n # print majorityGenre\r\n for m in range(len(artistIndexesInData)): # update all song's genres of that artist to the majority genre\r\n index = artistIndexesInData[m]\r\n singleDataGenres[index] = majorityGenre\r\n return singleDataGenres\r\n\r\n\r\ndef sample_data(songVectors, subgenres): # total songs in orig data set = 5852\r\n numSamples = len(subgenres) / 10 # num of samples of each category to take, ~580\r\n sampleCounts = np.zeros(10) # count for number of samples of each genre\r\n vectorsList = []\r\n subGenresList = []\r\n notEnoughSamples = True\r\n while notEnoughSamples: # if not enough samples for each genre\r\n notEnoughSamples = False\r\n for i in range(len(sampleCounts)):\r\n if sampleCounts[i] != numSamples:\r\n notEnoughSamples = True\r\n for j in range(len(subgenres)): # add songs until all genres have 100 samples\r\n genre = str(subgenres[j])\r\n song = songVectors[j]\r\n rand = random.uniform(0, 1) # adding a little randomization to what samples get picked\r\n randThreshold = .75\r\n # check genre and sample count before adding sample\r\n if \"trap\" in genre and sampleCounts[0] < numSamples:\r\n if \"r&b\" not in genre: # this statement is in each if statement to limit how often r&b and trap are sampled\r\n # many of the non trap or rnb subgenres have trap or r&n in their subgenre, which creates a skew in the labels\r\n if rand >= randThreshold:\r\n vectorsList.append(song)\r\n subGenresList.append(genre)\r\n sampleCounts[0] += 1\r\n if \"r&b\" in genre and sampleCounts[1] < numSamples:\r\n if \"trap\" not in genre:\r\n if rand >= randThreshold:\r\n vectorsList.append(song)\r\n subGenresList.append(genre)\r\n sampleCounts[1] += 1\r\n if \"alternative\" in genre and sampleCounts[2] < numSamples:\r\n if \"trap\" not in genre and \"r&b\" not in genre:\r\n if rand >= randThreshold:\r\n vectorsList.append(song)\r\n subGenresList.append(genre)\r\n sampleCounts[2] += 1\r\n if \"drill\" in genre and sampleCounts[3] < numSamples:\r\n if \"trap\" not in genre and \"r&b\" not in genre:\r\n if rand >= randThreshold:\r\n vectorsList.append(song)\r\n subGenresList.append(genre)\r\n sampleCounts[3] += 1\r\n if \"east\" in genre and sampleCounts[4] < numSamples:\r\n if \"trap\" not in genre and \"r&b\" not in genre:\r\n if rand >= randThreshold:\r\n vectorsList.append(song)\r\n subGenresList.append(genre)\r\n sampleCounts[4] += 1\r\n if \"west\" in genre and sampleCounts[5] < numSamples:\r\n if \"trap\" not in genre and \"r&b\" not in genre:\r\n if rand >= randThreshold:\r\n vectorsList.append(song)\r\n subGenresList.append(genre)\r\n sampleCounts[5] += 1\r\n if \"gangsta\" in genre and sampleCounts[6] < numSamples:\r\n if \"trap\" not in genre and \"r&b\" not in genre:\r\n if rand >= randThreshold:\r\n vectorsList.append(song)\r\n subGenresList.append(genre)\r\n sampleCounts[6] += 1\r\n if \"uk\" in genre and sampleCounts[7] < numSamples:\r\n if \"trap\" not in genre and \"r&b\" not in genre:\r\n if rand >= randThreshold:\r\n vectorsList.append(song)\r\n subGenresList.append(genre)\r\n sampleCounts[7] += 1\r\n if \"cloud\" in genre and sampleCounts[8] < numSamples:\r\n if \"trap\" not in genre and \"r&b\" not in genre:\r\n if rand >= randThreshold:\r\n vectorsList.append(song)\r\n subGenresList.append(genre)\r\n sampleCounts[8] += 1\r\n if \"atlanta\" in genre and sampleCounts[9] < numSamples:\r\n if \"trap\" not in genre and \"r&b\" not in genre:\r\n if rand >= randThreshold:\r\n vectorsList.append(song)\r\n subGenresList.append(genre)\r\n sampleCounts[9] += 1\r\n return vectorsList, subGenresList\r\n\r\n\r\ndef knn(k, trainData, subGenres, testData):\r\n knnAr = [0] * k # knn list\r\n knnInd = [0] * k # indexes of knns\r\n knnGenres = [\"\"] * k # track sub genres of each Knn Songs\r\n testResult = [\"\"] * len(testData) # holds subgenre result for each test vector\r\n testInd = 0 # index for testVectors\r\n trainInd = 0 # index for trainVectors\r\n resultInd = 0 # index for final result array\r\n subGenreNames = [\"trap\", \"r&b\", \"alternative\", \"drill\", \"east\", \"west\", \"gangsta\", \"uk\", \"cloud\", \"atlanta\"]\r\n subGenreCount = [0] * len(subGenreNames) # list of counts for each of the ten subgenres\r\n for test in testData:\r\n for train in trainData:\r\n testV = np.asarray(test)\r\n trainV = np.asarray(train)\r\n # dist = distance.euclidean(test, train) # get distance measure of test and train vectors\r\n dist = 1 - distance.cosine(testV, trainV)\r\n if math.isnan(dist): # set nan's to 0, nans appear bc some vectors may be all 0s\r\n dist = 0\r\n for i in range(len(knnAr)): # for each k in knn, update knn array w/ new dist\r\n if knnAr[i] < dist:\r\n knnAr[i] = dist # update Knn's distance value\r\n knnInd[i] = trainInd # track that song's index in the training data\r\n knnGenres[i] = subGenres[trainInd] # track that song's subgenres\r\n break\r\n trainInd += 1\r\n for j in range(len(knnAr)): # check subgenres from knn array\r\n if \"trap\" in knnGenres[j]: # inc count for each subgenre in the song\r\n subGenreCount[0] += 1\r\n if \"r&b\" in knnGenres[j]:\r\n subGenreCount[1] += 1\r\n if \"alternative\" in knnGenres[j]:\r\n subGenreCount[2] += 1\r\n if \"drill\" in knnGenres[j]:\r\n subGenreCount[3] += 1\r\n if \"east\" in knnGenres[j]:\r\n subGenreCount[4] += 1\r\n if \"west\" in knnGenres[j]:\r\n subGenreCount[5] += 1\r\n if \"gangsta\" in knnGenres[j]:\r\n subGenreCount[6] += 1\r\n if \"uk\" in knnGenres[j]:\r\n subGenreCount[7] += 1\r\n if \"cloud\" in knnGenres[j]:\r\n subGenreCount[8] += 1\r\n if \"atlanta\" in knnGenres[j]:\r\n subGenreCount[9] += 1\r\n # print \"Genre Counts: \", subGenreCount\r\n maxCount = -1\r\n genreLabel = \"\"\r\n for u in range(len(subGenreCount)): # get most popular subgenre count\r\n if subGenreCount[u] > maxCount:\r\n maxCount = subGenreCount[u]\r\n for z in range(len(subGenreCount)): # classify song as most popular genre out of the k neighbors\r\n if subGenreCount[z] == maxCount: # if there are ties in counts with multi. genres, pick the first one encountered in the for loop\r\n genreLabel += subGenreNames[z] # *this should work better with higher K's**\r\n break\r\n testResult[resultInd] = genreLabel\r\n subGenreCount = [0] * 10 # update/reset counts and indexes\r\n resultInd += 1\r\n trainInd = 0\r\n testInd += 1\r\n for i in range(len(knnAr)):\r\n knnAr[i] = 0\r\n knnInd[i] = 0\r\n knnGenres[i] = \"\"\r\n # if testInd % 100 == 0:\r\n # print \"Number Tested: \", testInd\r\n return testResult\r\n\r\n\r\ndef get_train_test_splits(wordCountVectors, subGenres): # get 4 folds of train data and test data\r\n subGenresTrain1 = copy.copy(subGenres[0]) # train data 1\r\n for x in subGenres[1]:\r\n subGenresTrain1.append(x)\r\n for x in subGenres[2]:\r\n subGenresTrain1.append(x)\r\n subGenresTrain2 = copy.copy(subGenres[1]) # train data 2\r\n for x in subGenres[2]:\r\n subGenresTrain2.append(x)\r\n for x in subGenres[3]:\r\n subGenresTrain2.append(x)\r\n subGenresTrain3 = copy.copy(subGenres[2]) # train data 3\r\n for x in subGenres[3]:\r\n subGenresTrain3.append(x)\r\n for x in subGenres[0]:\r\n subGenresTrain3.append(x)\r\n subGenresTrain4 = copy.copy(subGenres[3]) # train data 4\r\n for x in subGenres[0]:\r\n subGenresTrain4.append(x)\r\n for x in subGenres[1]:\r\n subGenresTrain4.append(x)\r\n\r\n wordCountTrain1 = copy.copy(wordCountVectors[0]) # train data 1\r\n for x in wordCountVectors[1]:\r\n wordCountTrain1.append(x)\r\n for x in wordCountVectors[2]:\r\n wordCountTrain1.append(x)\r\n wordCountTrain2 = copy.copy(wordCountVectors[1]) # train data 2\r\n for x in wordCountVectors[2]:\r\n wordCountTrain2.append(x)\r\n for x in wordCountVectors[3]:\r\n wordCountTrain2.append(x)\r\n wordCountTrain3 = copy.copy(wordCountVectors[2]) # train data 3\r\n for x in wordCountVectors[3]:\r\n wordCountTrain3.append(x)\r\n for x in wordCountVectors[0]:\r\n wordCountTrain3.append(x)\r\n wordCountTrain4 = copy.copy(wordCountVectors[3]) # train data 4\r\n for x in wordCountVectors[0]:\r\n wordCountTrain4.append(x)\r\n for x in wordCountVectors[1]:\r\n wordCountTrain4.append(x)\r\n\r\n wordCountTest1 = copy.copy(wordCountVectors[3]) # test data for train corresponding train data 1 - 4\r\n wordCountTest2 = copy.copy(wordCountVectors[0]) # if using train data 1, use test data 1\r\n wordCountTest3 = copy.copy(wordCountVectors[1])\r\n wordCountTest4 = copy.copy(wordCountVectors[2])\r\n subGenreTest1 = copy.copy(subGenres[3]) # subgenres for test data to evaluate their accuracy\r\n subGenreTest2 = copy.copy(subGenres[0])\r\n subGenreTest3 = copy.copy(subGenres[1])\r\n subGenreTest4 = copy.copy(subGenres[2])\r\n\r\n return (subGenresTrain1, subGenresTrain2, subGenresTrain3, subGenresTrain4,\r\n wordCountTrain1, wordCountTrain2, wordCountTrain3, wordCountTrain4,\r\n wordCountTest1, wordCountTest2, wordCountTest3, wordCountTest4,\r\n subGenreTest1, subGenreTest2, subGenreTest3, subGenreTest4)\r\n\r\n\r\ndef train_tree(X, y):\r\n tree = DecisionTreeClassifier(criterion=\"entropy\", # def = \"gini\"\r\n random_state=484,\r\n max_depth=None, # def = None\r\n min_samples_split=2, # def = 2\r\n min_samples_leaf=50, # def = 1\r\n max_leaf_nodes=None) # def = None\r\n tree.fit(X, y)\r\n return tree\r\n\r\n\r\ndef train_mlp_nn(X, y):\r\n nn = neural_network.MLPClassifier(solver=\"sgd\", # def = \"adam\"\r\n activation=\"logistic\", # def = \"relu\"\r\n hidden_layer_sizes=(100,), # def = (100, )\r\n max_iter=200, # def = 200\r\n random_state=484)\r\n nn.fit(X, y)\r\n return nn\r\n\r\n\r\ndef prepare_data(dataType, wf, wl):\r\n print \"Processing Data..\"\r\n data = read_data() # read data\r\n dataFormatted = format_data(data) # format data\r\n bagWords, wordCount, subGenres, numSongs, songVectors, maxSongLyricLength, tfidfVectors = process_data(dataFormatted, wf, wl, dataType) # process data\r\n subGenres = process_genres_to_single(data) # convert subgenres to be single labelled\r\n if dataType == \"unchanged\": # get train and test splits using only word count\r\n print \"Data Unchanged..\"\r\n songSplits, genreSplits = split_data(songVectors, subGenres, 4)\r\n (subGenresTrain1, subGenresTrain2, subGenresTrain3, subGenresTrain4,\r\n wordCountTrain1, wordCountTrain2, wordCountTrain3, wordCountTrain4,\r\n wordCountTest1, wordCountTest2, wordCountTest3, wordCountTest4,\r\n subGenreTest1, subGenreTest2, subGenreTest3, subGenreTest4) = get_train_test_splits(songSplits, genreSplits)\r\n if dataType == \"tfidf\": # get train and test split using tfidf values instead of word count\r\n print \"Calculating TFIDF..\"\r\n songSplits, genreSplits = split_data(tfidfVectors, subGenres, 4) # split data on tfidf vectors\r\n (subGenresTrain1, subGenresTrain2, subGenresTrain3, subGenresTrain4,\r\n wordCountTrain1, wordCountTrain2, wordCountTrain3, wordCountTrain4,\r\n wordCountTest1, wordCountTest2, wordCountTest3, wordCountTest4,\r\n subGenreTest1, subGenreTest2, subGenreTest3, subGenreTest4) = get_train_test_splits(songSplits, genreSplits)\r\n if dataType == \"sampled\": # sample genres so that popular genres don't overwhelm training\r\n print \"Sampling Data..\"\r\n newVectorsList, newSubGenres = sample_data(songVectors, subGenres) # sample data\r\n songSplits, genreSplits = split_data(newVectorsList, newSubGenres, 4) # split data\r\n (subGenresTrain1, subGenresTrain2, subGenresTrain3, subGenresTrain4,\r\n wordCountTrain1, wordCountTrain2, wordCountTrain3, wordCountTrain4,\r\n wordCountTest1, wordCountTest2, wordCountTest3, wordCountTest4,\r\n subGenreTest1, subGenreTest2, subGenreTest3, subGenreTest4) = get_train_test_splits(songSplits, genreSplits)\r\n return (subGenresTrain1, subGenresTrain2, subGenresTrain3, subGenresTrain4,\r\n wordCountTrain1, wordCountTrain2, wordCountTrain3, wordCountTrain4,\r\n wordCountTest1, wordCountTest2, wordCountTest3, wordCountTest4,\r\n subGenreTest1, subGenreTest2, subGenreTest3, subGenreTest4)\r\n\r\n\r\ndef class_report(actualSubgenres, predictedSubgenres): # create confusion matrix and evaluate it with Sklearn\r\n labels = [\"trap\", \"r&b\", \"alternative\", \"drill\", \"east coast\", \"west coast\", \"gangsta rap\", \"uk\", \"cloud rap\", \"atlanta\"]\r\n report = metrics.classification_report(actualSubgenres, predictedSubgenres, labels=labels)\r\n matrix = metrics.confusion_matrix(actualSubgenres, predictedSubgenres, labels=labels)\r\n accuracy = metrics.accuracy_score(actualSubgenres, predictedSubgenres)\r\n precRecF1Weight = metrics.precision_recall_fscore_support(actualSubgenres, predictedSubgenres, labels=labels, average=\"weighted\")\r\n prec = precRecF1Weight[0]\r\n rec = precRecF1Weight[1]\r\n f1 = precRecF1Weight[2]\r\n print \"Weighted: \", precRecF1Weight\r\n print matrix\r\n print report\r\n print \"Accuracy: \", accuracy\r\n print \"Precision: \", precRecF1Weight[0]\r\n print \"Recall: \", precRecF1Weight[1]\r\n print \"F1-Score: \", precRecF1Weight[2]\r\n return report, accuracy, prec, rec, f1\r\n\r\n\r\ndef main():\r\n print \"START\"\r\n start = time.clock()\r\n alg = \"knn\" # pick what algorithm to run: \"knn\", \"tree\", \"nn\"\r\n k = 3 # knn number\r\n wf = 2 # min word freq limit\r\n wl = 3 # min word length limit\r\n dataType = \"unchanged\" # pick type of data to use: \"unchanged\", \"tfidf\", \"sampled\"\r\n\r\n # process and split the data\r\n (subGenresTrain1, subGenresTrain2, subGenresTrain3, subGenresTrain4,\r\n wordCountTrain1, wordCountTrain2, wordCountTrain3, wordCountTrain4,\r\n wordCountTest1, wordCountTest2, wordCountTest3, wordCountTest4,\r\n subGenreTest1, subGenreTest2, subGenreTest3, subGenreTest4) = prepare_data(dataType, wf, wl)\r\n\r\n # choose which data folds to train and test with\r\n wordCountTrain = wordCountTrain1\r\n subGenresTrain = subGenresTrain1\r\n wordCountTest = wordCountTest1\r\n subGenreTest = subGenreTest1\r\n\r\n print \"Running \", alg, \" Algorithm\"\r\n if alg == \"knn\": # run knn\r\n result = knn(k, wordCountTrain, subGenresTrain, wordCountTest)\r\n write_data(result, \"knn\")\r\n if alg == \"tree\": # run dec tree\r\n tree = train_tree(wordCountTrain, subGenresTrain)\r\n result = tree.predict(wordCountTest)\r\n write_data(result, \"tree\")\r\n if alg == \"nn\": # run NN\r\n nn = train_mlp_nn(wordCountTrain, subGenresTrain)\r\n result = nn.predict(wordCountTest)\r\n write_data(result, \"nn\")\r\n report, accuracy, prec, rec, f1 = class_report(subGenreTest, result) # get the report of the confusion matrix\r\n save_result(alg, dataType, accuracy, prec, rec, f1, k, wf, wl) # save result\r\n print \"DONE\"\r\n done = (time.clock() - start)\r\n print done/60, \" Minutes\"\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n" } ]
2
LiuyangKyotoU/ChemBias_Causal
https://github.com/LiuyangKyotoU/ChemBias_Causal
c71d85c340510be3c9f34ef8acc15b1da9d074bf
4250e09370fcd6f4fcf6767a40d24e6dc68ed5d2
9f9e3ddaf1bfb24a1aaaf3b71e58ff464c02f879
refs/heads/main
2023-04-17T06:52:46.191381
2021-05-09T14:51:13
2021-05-09T14:51:13
343,741,111
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5862358212471008, "alphanum_fraction": 0.6000839471817017, "avg_line_length": 34.04411697387695, "blob_id": "e6ce3d06ce393a601ba6664e78ab8f7ea808d9de", "content_id": "9274814c87b38f652edb4c617cb939f588125a2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2383, "license_type": "no_license", "max_line_length": 91, "num_lines": 68, "path": "/preprocessor.py", "repo_name": "LiuyangKyotoU/ChemBias_Causal", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn.functional as F\nfrom torch_geometric.datasets import QM9, ZINC\nfrom torch_geometric.datasets import MoleculeNet\n\n\nclass Preprocessor:\n\n def _qm9(self, target):\n dataset = QM9('data/QM9', transform=QM9Transformer(target))\n mean = dataset.data.y.mean(dim=0, keepdim=True)\n std = dataset.data.y.std(dim=0, keepdim=True)\n dataset.data.y = (dataset.data.y - mean) / std\n return dataset, std[:, target].item(), 11, 4\n\n def _zinc(self):\n dataset = ZINC('data/ZINC', transform=ZINCTransformer())\n mean = dataset.data.y.mean()\n std = dataset.data.y.std()\n dataset.data.y = (dataset.data.y - mean) / std\n return dataset, std.item(), 28, 4\n\n def _molenet(self, task):\n dataset = MoleculeNet('data/MolNet', task, transform=MolNetTransformer())\n mean = dataset.data.y.mean()\n std = dataset.data.y.std()\n dataset.data.y = (dataset.data.y - mean) / std\n return dataset, std.item(), 9, 3\n\n def _split(self, dataset, scenario):\n dic = torch.load('sampling/' + scenario + '.pt')\n return dataset[dic['test_ids']], dataset[dic['train_ids']], dataset[dic['val_ids']]\n\n def get_dataset(self, task, scenario):\n if task[:3] == 'qm9':\n target = int(task.split('_')[1])\n dataset, std, i_dim, e_dim = self._qm9(target)\n elif task == 'zinc':\n dataset, std, i_dim, e_dim = self._zinc()\n elif task in ['esol', 'lipo', 'freesolv']:\n dataset, std, i_dim, e_dim = self._molenet(task)\n\n test_dataset, train_dataset, val_dataset = self._split(dataset, scenario)\n return (test_dataset, train_dataset, val_dataset), std, i_dim, e_dim\n\n\nclass QM9Transformer(object):\n def __init__(self, target):\n self.target = target\n\n def __call__(self, data):\n data.y = data.y[:, self.target]\n return data\n\n\nclass ZINCTransformer(object):\n def __call__(self, data):\n data.x = F.one_hot(data.x.view(-1), num_classes=28).to(torch.float32)\n data.edge_attr = F.one_hot(data.edge_attr, num_classes=4).to(torch.float32)\n return data\n\n\nclass MolNetTransformer(object):\n def __call__(self, data):\n data.x = data.x.to(torch.float32)\n data.edge_attr = data.edge_attr.to(torch.float32)\n data.y = data.y[:, 0]\n return data\n" }, { "alpha_fraction": 0.5717053413391113, "alphanum_fraction": 0.5763428211212158, "avg_line_length": 45.416893005371094, "blob_id": "63cd2313e8ecdc0820b459aa8202283bad2f2133", "content_id": "f1ff48649ba0f48ac3757ae9d3516dfd4653cf20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17035, "license_type": "no_license", "max_line_length": 116, "num_lines": 367, "path": "/trainers.py", "repo_name": "LiuyangKyotoU/ChemBias_Causal", "src_encoding": "UTF-8", "text": "import torch\nimport copy\nimport numpy as np\nimport torch.nn.functional as F\nfrom torch_geometric.nn import global_mean_pool\nfrom torch_geometric.data import DataLoader\nfrom geomloss import SamplesLoss\n\nimport models\nfrom preprocessor import Preprocessor\nfrom evaluator import Evaluator\n\n\nclass Trainer:\n def __init__(self, task, scenario, **kw):\n self.task = task\n self.scenario = scenario\n self.name = task + '==>' + scenario\n\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n self.h_dim = kw.get('h_dim')\n self.times = kw.get('times')\n self.batch_size = kw.get('batch_size')\n self.lr = kw.get('lr')\n self.epoch = kw.get('epoch')\n\n self.datasets, self.std, self.i_dim, self.e_dim = Preprocessor().get_dataset(task, scenario)\n self.test_loader, self.train_loader, self.val_loader = self._create_loaders()\n self.batch_error_func, self.all_error_func = Evaluator().get_error_func(task)\n\n def _train(self, *args):\n raise NotImplementedError\n\n def _test(self, *args):\n raise NotImplementedError\n\n def run(self):\n raise NotImplementedError\n\n def _save(self, test_error, model_state_dic):\n with open('results/test_errors.txt', 'a') as f:\n f.write(self.name + '\\t' + str(test_error) + '\\n')\n torch.save(model_state_dic, 'results/' + self.name + '.pt')\n print('Result of {} saved!'.format(self.name))\n\n def _create_loaders(self, ):\n test_dataset, train_dataset, val_dataset = self.datasets\n test_loader = DataLoader(test_dataset, batch_size=self.batch_size, shuffle=False)\n train_loader = DataLoader(train_dataset, batch_size=self.batch_size, shuffle=True)\n val_loader = DataLoader(val_dataset, batch_size=self.batch_size, shuffle=False)\n print('Load {} successfully!'.format(self.name))\n return test_loader, train_loader, val_loader\n\n\nclass BaselineTrainer(Trainer):\n def __init__(self, task, scenario, **kw):\n super(BaselineTrainer, self).__init__(task, scenario, **kw)\n self.name = 'Baseline' + str(self.times) + '==>' + self.name\n\n def _train(self, model, optimizer):\n model.train()\n loss_all = 0\n for batch in self.train_loader:\n batch = batch.to(self.device)\n optimizer.zero_grad()\n loss = F.mse_loss(model(batch), batch.y)\n loss.backward()\n loss_all += loss.item() * batch.num_graphs\n optimizer.step()\n return loss_all / len(self.train_loader.dataset)\n\n def _test(self, model, loader):\n model.eval()\n error = 0\n for batch in loader:\n batch = batch.to(self.device)\n with torch.no_grad():\n pred = model(batch)\n error += self.batch_error_func(pred, batch.y, self.std)\n return self.all_error_func(error / len(loader.dataset))\n\n def run(self):\n model = models.BaselineRegressNet(self.i_dim, self.h_dim, self.e_dim, self.times).to(self.device)\n optimizer = torch.optim.Adam(model.parameters(), self.lr)\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.7, patience=5,\n min_lr=0.00001)\n best_val_error = float('inf')\n best_model_dic = None\n for e in range(self.epoch):\n train_loss = self._train(model, optimizer)\n val_error = self._test(model, self.val_loader)\n scheduler.step(val_error)\n if val_error <= best_val_error:\n best_val_error = val_error\n best_model_dic = copy.deepcopy(model.state_dict())\n print(e, train_loss, val_error)\n model = models.BaselineRegressNet(self.i_dim, self.h_dim, self.e_dim, self.times).to(self.device)\n model.load_state_dict(best_model_dic)\n test_error = self._test(model, self.test_loader)\n self._save(test_error, best_model_dic)\n\n\nclass IpsTrainer(Trainer):\n def __init__(self, task, scenario, **kw):\n super(IpsTrainer, self).__init__(task, scenario, **kw)\n self.first_train_epoch = kw.get('first_train_epoch')\n assert self.first_train_epoch is not None\n\n self.name = 'IPS' + str(self.times) + '==>' + self.name\n\n def _train(self, model, optimizer, classifier):\n classifier.eval()\n model.train()\n loss_all = 0\n for batch in self.train_loader:\n batch = batch.to(self.device)\n optimizer.zero_grad()\n loss = F.mse_loss(model(batch), batch.y, reduction='none')\n with torch.no_grad():\n weights = 1 / (torch.exp(classifier(batch)[:, 1]) * 2)\n loss = loss * weights\n loss = loss.mean()\n loss.backward()\n loss_all += loss.item() * batch.num_graphs\n optimizer.step()\n return loss_all / len(self.train_loader.dataset)\n\n def _test(self, model, loader):\n model.eval()\n error = 0\n for batch in loader:\n batch = batch.to(self.device)\n with torch.no_grad():\n pred = model(batch)\n error += self.batch_error_func(pred, batch.y, self.std)\n return self.all_error_func(error / len(loader.dataset))\n\n def _first_train(self, model, optimizer, scheduler):\n unbias_dataset, bias_dataset, _ = self.datasets\n n = len(bias_dataset)\n val_size = int(n * 0.3)\n ids = torch.randperm(n)\n val_bias_dataset = bias_dataset[ids[:val_size]]\n val_unbias_dataset = unbias_dataset[ids[:val_size]]\n train_bias_dataset = bias_dataset[ids[val_size:]]\n train_unbias_dataset = unbias_dataset[ids[val_size:]]\n val_bias_loader = DataLoader(val_bias_dataset, batch_size=self.batch_size, shuffle=False)\n val_unbias_loader = DataLoader(val_unbias_dataset, batch_size=self.batch_size, shuffle=False)\n train_bias_loader = DataLoader(train_bias_dataset, batch_size=self.batch_size, shuffle=True)\n train_unbias_loader = DataLoader(train_unbias_dataset, batch_size=self.batch_size, shuffle=True)\n best_val_acc = -float('inf')\n best_model_dict = None\n for e in range(self.first_train_epoch):\n model.train()\n train_bias_iter = iter(train_bias_loader)\n train_unbias_iter = iter(train_unbias_loader)\n loss_all = 0\n for _ in range(len(train_bias_iter)):\n bias_batch = train_bias_iter.next().to(self.device)\n unbias_batch = train_unbias_iter.next().to(self.device)\n optimizer.zero_grad()\n loss = F.nll_loss(\n torch.cat((model(bias_batch), model(unbias_batch))),\n torch.cat((torch.ones(bias_batch.num_graphs),\n torch.zeros(unbias_batch.num_graphs))).to(torch.int64).to(self.device)\n )\n loss.backward()\n loss_all += loss.item() * (bias_batch.num_graphs + unbias_batch.num_graphs)\n optimizer.step()\n loss_all = loss_all / (len(train_bias_loader.dataset) + len(train_unbias_loader.dataset))\n model.eval()\n correct = 0\n val_bias_iter = iter(val_bias_loader)\n val_unbias_iter = iter(val_unbias_loader)\n for _ in range(len(val_bias_iter)):\n bias_batch = val_bias_iter.next().to(self.device)\n unbias_batch = val_unbias_iter.next().to(self.device)\n with torch.no_grad():\n pred = torch.cat((model(bias_batch), model(unbias_batch))).max(1)[1]\n correct += pred.eq(\n torch.cat((torch.ones(bias_batch.num_graphs),\n torch.zeros(unbias_batch.num_graphs))).to(torch.int64).to(self.device)\n ).sum().item()\n val_acc = correct / (len(val_bias_loader.dataset) + len(val_unbias_loader.dataset))\n scheduler.step()\n if val_acc >= best_val_acc:\n best_val_acc = val_acc\n best_model_dict = copy.deepcopy(model.state_dict())\n print(e, loss_all, val_acc)\n return best_model_dict\n\n def run(self):\n # first step\n classifier = models.IpsClassifyNet(self.i_dim, self.h_dim, self.e_dim, self.times).to(self.device)\n optimizer = torch.optim.Adam(classifier.parameters(), self.lr)\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, self.first_train_epoch // 2, gamma=0.1)\n classifier_best_stat_dic = self._first_train(classifier, optimizer, scheduler)\n classifier = models.IpsClassifyNet(self.i_dim, self.h_dim, self.e_dim, self.times).to(self.device)\n classifier.load_state_dict(classifier_best_stat_dic)\n # second step\n model = models.BaselineRegressNet(self.i_dim, self.h_dim, self.e_dim, self.times).to(self.device)\n optimizer = torch.optim.Adam(model.parameters(), self.lr)\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.7, patience=5,\n min_lr=0.00001)\n best_val_error = float('inf')\n best_model_dic = None\n for e in range(self.epoch):\n train_loss = self._train(model, optimizer, classifier)\n val_error = self._test(model, self.val_loader)\n scheduler.step(val_error)\n if val_error <= best_val_error:\n best_val_error = val_error\n best_model_dic = copy.deepcopy(model.state_dict())\n print(e, train_loss, val_error)\n model = models.BaselineRegressNet(self.i_dim, self.h_dim, self.e_dim, self.times).to(self.device)\n model.load_state_dict(best_model_dic)\n test_error = self._test(model, self.test_loader)\n self._save(test_error, best_model_dic)\n\n\nclass DirlTrainer(Trainer):\n def __init__(self, task, scenario, **kw):\n super(DirlTrainer, self).__init__(task, scenario, **kw)\n self.name = 'Dirl' + '==>' + self.name\n\n def _train(self, model, optimizer, e):\n model.train()\n source_iter = iter(self.train_loader) # bias_iter\n target_iter = iter(self.test_loader) # unbias_iter\n loss_all = 0\n for i in range(len(source_iter)):\n p = (i + e * len(source_iter)) / self.epoch / len(source_iter)\n alpha = 2 / (1 + np.exp(-10 * p)) - 1\n\n optimizer.zero_grad()\n # {source / bias / train} domain\n batch = source_iter.next().to(self.device)\n label_out, domain_out = model(batch, alpha)\n loss = F.mse_loss(label_out, batch.y)\n loss += F.nll_loss(domain_out, torch.zeros(batch.num_graphs).to(torch.int64).to(self.device))\n # {target / unbias / test} domain\n batch = target_iter.next().to(self.device)\n _, domain_out = model(batch, alpha)\n loss += F.nll_loss(domain_out, torch.ones(batch.num_graphs).to(torch.int64).to(self.device))\n loss.backward()\n loss_all += loss.item() * batch.num_graphs\n optimizer.step()\n return loss_all / len(self.train_loader.dataset)\n\n def _test(self, model, loader):\n model.eval()\n error = 0\n for batch in loader:\n batch = batch.to(self.device)\n with torch.no_grad():\n label_out, _ = model(batch, 0)\n error += self.batch_error_func(label_out, batch.y, self.std)\n return self.all_error_func(error / len(loader.dataset))\n\n def run(self):\n model = models.DirlNet(self.i_dim, self.h_dim, self.e_dim, self.times).to(self.device)\n optimizer = torch.optim.Adam(model.parameters(), self.lr)\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.7, patience=5,\n min_lr=0.00001)\n best_val_error = float('inf')\n best_model_dic = None\n for e in range(self.epoch):\n train_loss = self._train(model, optimizer, e)\n val_error = self._test(model, self.val_loader)\n scheduler.step(val_error)\n if val_error <= best_val_error:\n best_val_error = val_error\n best_model_dic = copy.deepcopy(model.state_dict())\n print(e, train_loss, val_error)\n model = models.DirlNet(self.i_dim, self.h_dim, self.e_dim, self.times).to(self.device)\n model.load_state_dict(best_model_dic)\n test_error = self._test(model, self.test_loader)\n self._save(test_error, best_model_dic)\n\n\nclass CfrIswTrainer(Trainer):\n def __init__(self, task, scenario, **kw):\n super(CfrIswTrainer, self).__init__(task, scenario, **kw)\n self.alpha = kw.get('alpha')\n assert self.alpha is not None\n\n self.name = 'CfrIsw' + str(self.alpha) + '==>' + self.name\n\n def _train(self, R, L, D, disc_func, optimizer):\n R.train()\n L.train()\n D.train()\n bias_iter = iter(self.train_loader)\n unbias_iter = iter(self.test_loader)\n loss_rl, loss_d = 0, 0\n for _ in range(len(bias_iter)):\n optimizer.zero_grad()\n bias_batch = bias_iter.next().to(self.device)\n unbias_batch = unbias_iter.next().to(self.device)\n\n bias_repr = R(bias_batch)\n unbias_repr = R(unbias_batch)\n\n disc_loss = disc_func(global_mean_pool(bias_repr, bias_batch.batch),\n global_mean_pool(unbias_repr, unbias_batch.batch))\n with torch.no_grad():\n weights = 1 / (2 * torch.exp(D(bias_batch, bias_repr.data)[:, 1]))\n label_loss = F.mse_loss(L(bias_batch, bias_repr), bias_batch.y, reduction='none')\n label_loss = (label_loss * weights).mean()\n loss = self.alpha * disc_loss + label_loss\n loss.backward()\n loss_rl += loss.item() * bias_batch.num_graphs\n optimizer.step()\n\n optimizer.zero_grad()\n loss = F.nll_loss(\n torch.cat((D(bias_batch, bias_repr.data), D(unbias_batch, unbias_repr.data))),\n torch.cat((torch.ones(bias_batch.num_graphs),\n torch.zeros(unbias_batch.num_graphs))).to(torch.int64).to(self.device)\n )\n loss.backward()\n loss_d += loss.item() * (bias_batch.num_graphs + unbias_batch.num_graphs)\n optimizer.step()\n loss_rl = loss_rl / len(self.train_loader.dataset)\n loss_d = loss_d / (len(self.train_loader.dataset) + len(self.test_loader.dataset))\n return loss_rl, loss_d\n\n def _test(self, R, L, loader):\n R.eval()\n L.eval()\n error = 0\n for batch in loader:\n batch = batch.to(self.device)\n with torch.no_grad():\n pred = L(batch, R(batch))\n error += self.batch_error_func(pred, batch.y, self.std)\n return self.all_error_func(error / len(loader.dataset))\n\n def run(self):\n R = models.CausalFeatureNet(self.i_dim, self.h_dim, self.e_dim, self.times).to(self.device)\n L = models.CausalRegressNet(self.h_dim, self.e_dim, self.times).to(self.device)\n D = models.CausalClassifyNet(self.h_dim, self.e_dim, self.times).to(self.device)\n optimizer = torch.optim.Adam(list(R.parameters()) + list(L.parameters()) + list(D.parameters()), lr=self.lr)\n # There will not be val_error for D training part, thus we use two optimizer.\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.7, patience=5,\n min_lr=0.00001)\n best_val_error = float('inf')\n best_model_dic = None\n disc_func = SamplesLoss('sinkhorn')\n for e in range(self.epoch):\n train_loss_lr, train_loss_d = self._train(R, L, D, disc_func, optimizer)\n val_error = self._test(R, L, self.val_loader)\n scheduler.step(val_error)\n if val_error <= best_val_error:\n best_val_error = val_error\n best_model_dic = (copy.deepcopy(R.state_dict()),\n copy.deepcopy(L.state_dict()),\n copy.deepcopy(D.state_dict()))\n print(e, train_loss_lr, train_loss_d, val_error)\n R = models.CausalFeatureNet(self.i_dim, self.h_dim, self.e_dim, self.times).to(self.device)\n L = models.CausalRegressNet(self.h_dim, self.e_dim, self.times).to(self.device)\n D = models.CausalClassifyNet(self.h_dim, self.e_dim, self.times).to(self.device)\n R.load_state_dict(best_model_dic[0])\n L.load_state_dict(best_model_dic[1])\n D.load_state_dict(best_model_dic[2])\n test_error = self._test(R, L, self.test_loader)\n self._save(test_error, best_model_dic)\n" }, { "alpha_fraction": 0.6047589182853699, "alphanum_fraction": 0.6188671588897705, "avg_line_length": 36.1015625, "blob_id": "af2034f357e614fbd9a845f27318b9f182fdf734", "content_id": "c1057884dc0fb5b997f8c08cee00a8deb2c8b620", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4749, "license_type": "no_license", "max_line_length": 99, "num_lines": 128, "path": "/models.py", "repo_name": "LiuyangKyotoU/ChemBias_Causal", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn.functional as F\nfrom torch.nn import Sequential, Linear, ReLU, GRU\nfrom torch_geometric.nn import NNConv, global_mean_pool\n\n\nclass ConvLayer(torch.nn.Module):\n def __init__(self, h_dim, e_dim, times=3):\n super(ConvLayer, self).__init__()\n nn = Sequential(Linear(e_dim, h_dim), ReLU(), Linear(h_dim, h_dim * h_dim))\n self.conv = NNConv(h_dim, h_dim, nn, aggr='mean')\n self.gru = GRU(h_dim, h_dim)\n self.times = times\n\n def forward(self, batch, out):\n h = out.unsqueeze(0)\n for _ in range(self.times):\n m = F.relu(self.conv(out, batch.edge_index, batch.edge_attr))\n out, h = self.gru(m.unsqueeze(0), h)\n out = out.squeeze(0)\n return out\n\n\nclass BaselineRegressNet(torch.nn.Module):\n def __init__(self, i_dim, h_dim, e_dim, times):\n super(BaselineRegressNet, self).__init__()\n self.lin0 = Sequential(Linear(i_dim, h_dim), ReLU())\n self.conv_layer = ConvLayer(h_dim, e_dim, times)\n self.lin1 = Sequential(Linear(h_dim, h_dim), ReLU(), Linear(h_dim, 1))\n\n def forward(self, batch):\n out = self.lin1(global_mean_pool(self.conv_layer(batch, self.lin0(batch.x)), batch.batch))\n return out.view(-1)\n\n\nclass IpsClassifyNet(torch.nn.Module):\n def __init__(self, i_dim, h_dim, e_dim, times):\n super(IpsClassifyNet, self).__init__()\n self.lin0 = Sequential(Linear(i_dim, h_dim), ReLU())\n self.conv_layer = ConvLayer(h_dim, e_dim, times)\n self.lin1 = Sequential(Linear(h_dim, h_dim), ReLU(), Linear(h_dim, 2))\n\n def forward(self, batch):\n out = self.lin1(global_mean_pool(self.conv_layer(batch, self.lin0(batch.x)), batch.batch))\n return F.log_softmax(out, dim=1)\n\n\nclass ReverseLayerF(torch.autograd.Function):\n @staticmethod\n def forward(ctx, x, alpha):\n ctx.alpha = alpha\n return x.view_as(x)\n\n @staticmethod\n def backward(ctx, grad_output):\n output = grad_output.neg() * ctx.alpha\n return output, None\n\n\nclass DirlNet(torch.nn.Module):\n def __init__(self, i_dim, h_dim, e_dim, times):\n super(DirlNet, self).__init__()\n self.lin0 = Sequential(Linear(i_dim, h_dim), ReLU())\n self.feature_conv_layer = ConvLayer(h_dim, e_dim, times)\n self.label_conv_layer = ConvLayer(h_dim, e_dim, times)\n self.lin1 = Sequential(Linear(h_dim, h_dim), ReLU(), Linear(h_dim, 1))\n self.domain_conv_layer = ConvLayer(h_dim, e_dim, times)\n self.lin2 = Sequential(Linear(h_dim, h_dim), ReLU(), Linear(h_dim, 2))\n\n def forward(self, batch, alpha):\n out = self.feature_conv_layer(batch, self.lin0(batch.x))\n r_out = ReverseLayerF.apply(out, alpha)\n label_out = self.lin1(global_mean_pool(self.label_conv_layer(batch, out), batch.batch))\n domain_out = self.lin2(global_mean_pool(self.domain_conv_layer(batch, r_out), batch.batch))\n return label_out.view(-1), F.log_softmax(domain_out, dim=1)\n\n\nclass CausalFeatureNet(torch.nn.Module):\n def __init__(self, i_dim, h_dim, e_dim, times):\n super(CausalFeatureNet, self).__init__()\n self.lin0 = Sequential(Linear(i_dim, h_dim), ReLU())\n self.conv_layer = ConvLayer(h_dim, e_dim, times)\n\n def forward(self, batch):\n return self.conv_layer(batch, self.lin0(batch.x))\n\n\nclass CausalRegressNet(torch.nn.Module):\n def __init__(self, h_dim, e_dim, times):\n super(CausalRegressNet, self).__init__()\n self.conv_layer = ConvLayer(h_dim, e_dim, times)\n self.lin1 = Sequential(Linear(h_dim, h_dim), ReLU(), Linear(h_dim, 1))\n\n def forward(self, batch, out):\n out = self.lin1(global_mean_pool(self.conv_layer(batch, out), batch.batch))\n return out.view(-1)\n\n\nclass CausalClassifyNet(torch.nn.Module):\n def __init__(self, h_dim, e_dim, times):\n super(CausalClassifyNet, self).__init__()\n self.conv_layer = ConvLayer(h_dim, e_dim, times)\n self.lin1 = Sequential(Linear(h_dim, h_dim), ReLU(), Linear(h_dim, 2))\n\n def forward(self, batch, out):\n out = self.lin1(global_mean_pool(self.conv_layer(batch, out), batch.batch))\n return F.log_softmax(out, dim=1)\n\n\nif __name__ == '__main__':\n from torch_geometric.datasets import QM9\n from torch_geometric.data import DataLoader\n\n dataset = QM9('data/QM9')\n loader = DataLoader(dataset, batch_size=6)\n data = iter(loader).next()\n\n model = BaselineRegressNet(11, 32, 4, 6)\n print(model(data))\n\n model = DirlNet(11, 32, 4, 3)\n print(model(data, 1))\n\n R = CausalFeatureNet(11, 32, 4, 3)\n D = CausalClassifyNet(32, 4, 3)\n L = CausalRegressNet(32, 4, 3)\n print(R(data))\n print(D(data, R(data)), L(data, R(data)))\n" }, { "alpha_fraction": 0.4868255853652954, "alphanum_fraction": 0.4905897080898285, "avg_line_length": 22.441177368164062, "blob_id": "13f2772ccf6174fe9310283c10e7009057b33d5a", "content_id": "ca4a92004f24cb9196ab3da552d0a9608cc01717", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 797, "license_type": "no_license", "max_line_length": 54, "num_lines": 34, "path": "/evaluator.py", "repo_name": "LiuyangKyotoU/ChemBias_Causal", "src_encoding": "UTF-8", "text": "import math\n\n\nclass Evaluator:\n\n def _mae(self, x, y, std):\n return (x * std - y * std).abs().sum().item()\n\n def _rmse(self, x, y, std):\n return ((x * std - y * std) ** 2).sum().item()\n\n def _keep(self, x):\n return x\n\n def _sqrt(self, x):\n return math.sqrt(x)\n\n def _mae_funcs(self):\n return self._mae, self._keep\n\n def _rmse_funcs(self):\n return self._rmse, self._sqrt\n\n def get_error_func(self, task):\n if task[:3] == 'qm9':\n return self._mae_funcs()\n if task == 'zinc':\n return self._mae_funcs()\n if task == 'esol':\n return self._rmse_funcs()\n if task == 'lipo':\n return self._rmse_funcs()\n if task == 'freesolv':\n return self._rmse_funcs()\n" }, { "alpha_fraction": 0.5428025722503662, "alphanum_fraction": 0.5693696737289429, "avg_line_length": 34.993751525878906, "blob_id": "422fdbf93d8ef734acbfb5141134d3fa0b36641d", "content_id": "b6a668b5fd1f01c230cb00e67ddaff2af79011d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5759, "license_type": "no_license", "max_line_length": 111, "num_lines": 160, "path": "/samplers.py", "repo_name": "LiuyangKyotoU/ChemBias_Causal", "src_encoding": "UTF-8", "text": "import torch\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torch_geometric.datasets import QM9, ZINC, MoleculeNet\nimport itertools\n\n\nclass Sampler(object):\n def __init__(self, dataset, f1_alpha, f2_alpha, f3_alpha):\n self.n = len(dataset)\n self.f1_tensor = self._get_mols_f1(dataset)\n self.f2_tensor = self._get_mols_f2(dataset)\n self.f3_tensor = self._get_mols_f3(dataset)\n self.f1_alpha = f1_alpha\n self.f2_alpha = f2_alpha\n self.f3_alpha = f3_alpha\n self.name = self.__class__.__name__ + ':'\n\n def _get_mols_f1(self, dataset):\n raise NotImplementedError\n\n def _get_mols_f2(self, dataset):\n raise NotImplementedError\n\n def _get_mols_f3(self, dataset):\n raise NotImplementedError\n\n def _sigmoid(self, x, a, b):\n return 1 / (1 + torch.exp(-a * (x - b)))\n\n def _save(self, test_ids, train_ids, val_ids, factors, trial):\n dic = {'test_ids': test_ids, 'train_ids': train_ids, 'val_ids': val_ids}\n torch.save(dic, 'sampling/' + self.name + '+'.join(factors) + '_' + str(trial) + '.pt')\n\n def run_all_sampling(self):\n factors = ['f1', 'f2', 'f3']\n for i in range(len(factors) + 1):\n for subset in itertools.combinations(factors, i):\n for trial in range(10):\n self.sampling(subset, trial)\n\n def sampling(self, factors, trial):\n ids = torch.randperm(self.n)\n test_ids = ids[:self.n // 10]\n other_ids = ids[self.n // 10:]\n scores = torch.zeros(other_ids.shape[0]).to(torch.float32)\n if not factors:\n scores = torch.ones(other_ids.shape[0]).to(torch.float32)\n for factor in factors:\n t = self.__getattribute__(factor + '_tensor')\n a = self.__getattribute__(factor + '_alpha')\n scores += self._sigmoid(t[other_ids], a, t.median())\n scores = scores / scores.sum()\n train_val_ids = torch.tensor(\n np.random.choice(other_ids, self.n // 10 * 10 // 7, replace=False, p=scores.numpy()))\n train_val_ids = train_val_ids[torch.randperm(train_val_ids.shape[0])]\n train_ids = train_val_ids[:self.n // 10]\n val_ids = train_val_ids[self.n // 10:]\n self._save(test_ids, train_ids, val_ids, factors, trial)\n\n def draw(self, factor, bins, xlim=None):\n dic = torch.load('sampling/' + self.name + factor + '.pt')\n unbias_ids = dic['test_ids']\n bias_ids = dic['train_ids']\n t = self.__getattribute__(factor + '_tensor')\n a = self.__getattribute__(factor + '_alpha')\n tmp1 = t[unbias_ids].numpy()\n tmp2 = t[bias_ids].numpy()\n fig, ax = plt.subplots()\n ax.hist(tmp1, weights=np.ones_like(tmp1) / len(tmp1), bins=bins, alpha=0.5)\n ax.hist(tmp2, weights=np.ones_like(tmp2) / len(tmp2), bins=bins, alpha=0.5)\n ax_ = ax.twinx()\n x = torch.linspace(t.min(), t.max(), 100)\n ax_.plot(x.numpy(), self._sigmoid(x, a, t.median()).numpy())\n if xlim:\n ax.set_xlim([*xlim])\n plt.show()\n\n\nclass QM9Sampler(Sampler):\n def __init__(self, f1_alpha, f2_alpha, f3_alpha):\n dataset = QM9('data/QM9')\n super(QM9Sampler, self).__init__(dataset, f1_alpha, f2_alpha, f3_alpha)\n\n def _get_mols_f1(self, dataset):\n ans = []\n for data in dataset:\n ans.append(data.x.shape[0])\n return torch.tensor(ans).to(torch.float32)\n\n def _get_mols_f2(self, dataset):\n ans = []\n for data in dataset:\n ans.append((data.edge_attr[:, 0].sum() / data.edge_attr.shape[0]).item())\n return torch.tensor(ans).to(torch.float32)\n\n def _get_mols_f3(self, dataset):\n ans = []\n for data in dataset:\n ans.append(data.y[0, 4].item())\n return torch.tensor(ans).to(torch.float32)\n\n\nclass ZINCSampler(Sampler):\n def __init__(self, f1_alpha, f2_alpha, f3_alpha):\n dataset = ZINC('data/ZINC')\n super(ZINCSampler, self).__init__(dataset, f1_alpha, f2_alpha, f3_alpha)\n\n def _get_mols_f1(self, dataset):\n ans = []\n for data in dataset:\n ans.append(data.x.shape[0])\n return torch.tensor(ans).to(torch.float32)\n\n def _get_mols_f2(self, dataset):\n ans = []\n for data in dataset:\n ans.append(torch.nonzero(data.edge_attr == 1).shape[0] / data.edge_attr.shape[0])\n return torch.tensor(ans).to(torch.float32)\n\n def _get_mols_f3(self, dataset):\n ans = []\n for data in dataset:\n ans.append(data.y.item())\n return torch.tensor(ans).to(torch.float32)\n\n\nclass MoleNetSampler(Sampler):\n def __init__(self, task, f1_alpha, f2_alpha, f3_alpha):\n dataset = MoleculeNet('data/MolNet', task)\n super(MoleNetSampler, self).__init__(dataset, f1_alpha, f2_alpha, f3_alpha)\n\n def _get_mols_f1(self, dataset):\n ans = []\n for data in dataset:\n ans.append(data.x.shape[0])\n return torch.tensor(ans).to(torch.float32)\n\n def _get_mols_f2(self, dataset):\n ans = []\n for data in dataset:\n ans.append((torch.nonzero(data.edge_attr[:, 0] == 1).shape[0] + 1) / (data.edge_attr.shape[0] + 1))\n return torch.tensor(ans).to(torch.float32)\n\n def _get_mols_f3(self, dataset):\n ans = []\n for data in dataset:\n ans.append(data.y[0, 0].item())\n return torch.tensor(ans).to(torch.float32)\n\n\nif __name__ == '__main__':\n sampler = QM9Sampler(-1, -50, 2)\n sampler.run_all_sampling()\n # sampler.sampling('f1')\n # sampler.sampling('f2')\n # sampler.sampling('f3')\n # sampler.draw('f1', 40)\n # sampler.draw('f2', 20, [0.75, 1])\n # sampler.draw('f3', 40,[2,12])\n" } ]
5
Jamie1919/Python-Crash-Course-
https://github.com/Jamie1919/Python-Crash-Course-
8eb09d097b06af2a2f5f09343c2432342596c840
bc124530fcce22fa9a7c85aeb156431562caab4d
2bdb87286bd882c0d7225e50e301aeb5bb31657e
refs/heads/main
2023-03-22T16:17:34.897622
2021-03-15T13:18:29
2021-03-15T13:18:29
347,913,614
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7055920958518982, "alphanum_fraction": 0.7105262875556946, "avg_line_length": 21.924528121948242, "blob_id": "8bd3e9791de37c23ceea00558e83b01df5a6b213", "content_id": "31be655be97720cddca077dade48dc0780c529cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1216, "license_type": "no_license", "max_line_length": 67, "num_lines": 53, "path": "/Chap 3/bicycles.py", "repo_name": "Jamie1919/Python-Crash-Course-", "src_encoding": "UTF-8", "text": "bicycles = [ 'trek', 'cannondale','redline','specialized']\nprint(bicycles[0])\n\nmotorcycles = ['honda', 'yamaha', 'suzuki']\nprint(motorcycles)\nmotorcycles[0] = 'ducati'\nprint(motorcycles)\nmotorcycles.append('ducati')\nprint(motorcycles)\nmotorcycles.insert(0, 'bmw')\nprint(motorcycles)\n\nmotorcycles = ['honda', 'yamaha', 'suzuki']\nprint(motorcycles)\ndel motorcycles[0]\nprint(motorcycles)\n\nmotorcycles = ['honda', 'yamaha', 'suzuki']\nprint(motorcycles)\npopped_motorcycle = motorcycles.pop()\nprint(motorcycles)\nprint(popped_motorcycle)\n\nfirst_owned = motorcycles.pop(1)\nprint(f\"The first motorcycle I owned was a {first_owned.title()}.\")\n\n\nmotorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']\nprint(motorcycles)\ntoo_expensive = 'ducati'\nmotorcycles.remove(too_expensive)\nprint(motorcycles)\nprint(f\"\\nA {too_expensive.title()} is too expensivefor me.\")\n\ncars = ['bmw', 'audi', 'toyota', 'subaru']\ncars.sort()\nprint(cars)\n\ncars = ['bmw', 'audi', 'toyota', 'subaru']\nprint(\"Here is the original list:\")\nprint(cars)\nprint(\"\\nHere is the sorted list:\")\nprint(sorted(cars))\nprint(\"\\nHere is the original list again:\")\nprint(cars)\n\ncars= ['bmw','Merc','audi','subaru']\nprint(cars)\n\ncars.reverse()\nprint(cars)\n\nprint(cars[-1])\n\n" }, { "alpha_fraction": 0.585106372833252, "alphanum_fraction": 0.7127659320831299, "avg_line_length": 12.571428298950195, "blob_id": "39b6abb460b362c2f7f83e00c7452428452c149e", "content_id": "900dd534f61935bc841f2cfe09c2b57010f7bb10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 94, "license_type": "no_license", "max_line_length": 23, "num_lines": 7, "path": "/Chap 2/Tryityourself_75.py", "repo_name": "Jamie1919/Python-Crash-Course-", "src_encoding": "UTF-8", "text": "print(4+4)\nprint(2*4)\nprint(10-2)\nprint(16/2)\n\nfavourite_number = '19'\nprint(favourite_number)" }, { "alpha_fraction": 0.6901408433914185, "alphanum_fraction": 0.6901408433914185, "avg_line_length": 34.75, "blob_id": "57b6663b765d3bc715ad3e48d0560430c5b6b2fe", "content_id": "ea084c5aec40189bb622cd6a854e13164faf09c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 142, "license_type": "no_license", "max_line_length": 54, "num_lines": 4, "path": "/Chap4/magicians.py", "repo_name": "Jamie1919/Python-Crash-Course-", "src_encoding": "UTF-8", "text": "magicians = ['Joker', 'Jester','Clown']\nfor magician in magicians:\n\tprint(f\"\\nHello {magician.title()}, that was funny!\")\n\tprint(f\"\\nGoodbye\")" }, { "alpha_fraction": 0.6984127163887024, "alphanum_fraction": 0.6984127163887024, "avg_line_length": 24.25, "blob_id": "36794d0ae3a415eb097e426a4f20d6e8245f9483", "content_id": "f1c79cb55fc4794933904c770fba68d3b1c511d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 504, "license_type": "no_license", "max_line_length": 92, "num_lines": 20, "path": "/Chap 2/Tryityourself_71.py", "repo_name": "Jamie1919/Python-Crash-Course-", "src_encoding": "UTF-8", "text": "first_name = \"John\"\nlast_name = \"Smith\"\nfull_name=f\"{first_name} {last_name}\"\nprint(full_name.title())\nprint(f\"Hello, {full_name.title()} how are you?\")\n\nname = \"John Smith\"\nprint(name.title())\nprint(name.upper())\nprint(name.lower())\n\nmessage = 'Joker once said, \"The only sensible way to live in this world is without rules.\"'\nprint(message)\n\nfamous_person = \"Joker\"\nmessage = 'Joker once said, \"The only sensible way to live in this world is without rules.\"'\n\nfirst_name = 'John'\nfirst_name.rstrip()\n'John'" }, { "alpha_fraction": 0.6183673739433289, "alphanum_fraction": 0.6448979377746582, "avg_line_length": 17.80769157409668, "blob_id": "56b101677f77346edd745664505841050c6dba79", "content_id": "2ae00a63f9fa99cd3802cc106206cc33a89aa1b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 490, "license_type": "no_license", "max_line_length": 48, "num_lines": 26, "path": "/Chap 2/name.py", "repo_name": "Jamie1919/Python-Crash-Course-", "src_encoding": "UTF-8", "text": "name = \"ada lovelace\"\nprint(name.title())\nprint(name.upper())\nprint(name.lower())\n\nfirst_name = \"ada\"\nlast_name = \"lovelace\"\nfull_name = f\"{first_name} {last_name}\"\nprint(full_name.title())\nprint(f\"\\tHello, \\n{full_name.title()}!\")\n\nname = \"Languages:\"\nname2 = \"Python\"\nname3 = \"C\"\nName4 = \"Java\"\nprint(name.title())\nprint(name2.upper())\nprint(name3.lower())\nprint(Name4.upper())\n\nprint(\"Languages:\\n\\tPython\\n\\tC\\n\\tJavascript\")\n\nx, y, z = 1, 2, 3\nprint(f\"{x} {y} {z}\")\n\nMAX_CONNECTIONS = 5000\n\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.625, "avg_line_length": 23.5, "blob_id": "7f48ffa81bfd3a1e7544745f9cb7e8f952378dfd", "content_id": "de3cba8a52e421fa8bc597efa43144ef6ddb45c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 48, "license_type": "no_license", "max_line_length": 35, "num_lines": 2, "path": "/Chap 3/Tryityourself_82.py", "repo_name": "Jamie1919/Python-Crash-Course-", "src_encoding": "UTF-8", "text": "names = ['Ayush', 'Caleb', 'Shaun']\nprint(names)" }, { "alpha_fraction": 0.667475700378418, "alphanum_fraction": 0.667475700378418, "avg_line_length": 30.769229888916016, "blob_id": "dd3083d8e1d1ca397e45fafe1e4d18c46f4656a7", "content_id": "0af6539ee9405186a097e1e4d2373125e89e64f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 412, "license_type": "no_license", "max_line_length": 55, "num_lines": 13, "path": "/Chap4/Tryityourselfpage105.py", "repo_name": "Jamie1919/Python-Crash-Course-", "src_encoding": "UTF-8", "text": "pizza = ['Pepperoni', 'Ham and Mushroom', 'Chicken' ]\nfor pizza in pizza:\n\tprint(f\"\\n{pizza.title()}, That flavour is great!\")\n\tprint(f\"Could I have another please,{pizza.title()}.\")\n\n\tprint(\"Thank you for the food\\n\")\n\nanimals = ['Lion', 'Leopard', 'Jaguar']\nfor animal in animals:\n\tprint(f\"\\n{animal.title()},It is a big cat\")\n\tprint(f\"It is an apex predator, {animal.title()}\")\n\n\tprint(\"It shouldnt be a pet\")" }, { "alpha_fraction": 0.737500011920929, "alphanum_fraction": 0.737500011920929, "avg_line_length": 19, "blob_id": "5921c2e9bf7eec78d4c1d561d3830b9732569090", "content_id": "579f0a1865689bcbc525760254edd78a30994b12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 80, "license_type": "no_license", "max_line_length": 40, "num_lines": 4, "path": "/Chap 2/Tryityourself_63.py", "repo_name": "Jamie1919/Python-Crash-Course-", "src_encoding": "UTF-8", "text": "print(\"Captain Price\")\n\nmessage = \" Call of Duty Modern Warfare\"\nprint(message)\n" } ]
8
saadjansari/KymoAnalysis
https://github.com/saadjansari/KymoAnalysis
c8a65b2b381e51bdfcd069dc761d255b6ecde71d
37f2fc953186313b6d9abad982d850857f9f76fd
fe4504eee843a404dc47699919e6ad003ee7461b
refs/heads/main
2023-03-15T18:14:26.064883
2022-10-03T16:46:25
2022-10-03T16:46:25
201,294,342
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5226486921310425, "alphanum_fraction": 0.5314626693725586, "avg_line_length": 35.06438446044922, "blob_id": "f1e9e84df6f5459684897ef5ced5bf0d93bdf92e", "content_id": "18715f14c28acdaf88198a747cd7941369fcd0bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17926, "license_type": "permissive", "max_line_length": 167, "num_lines": 497, "path": "/src/Features.py", "repo_name": "saadjansari/KymoAnalysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os, pdb\nimport numpy as np\nfrom scipy import interpolate, signal\nfrom .node_graph import Graph\nimport matplotlib.pyplot as plt\nimport math\nimport uuid\n\n# Superclass for Poles and tracks that stores positional and intensity information\nclass Feature:\n def __init__(self, time, position, intensity, strain='xxx', time_step=1):\n self.time = np.array( time )\n self.position = np.array( position )\n self.intensity = np.array( intensity )\n self.id = uuid.uuid1()\n self.strain = strain\n self.time_step = time_step\n self.pixel_time = self.time / self.time_step\n\n # Resample data\n self.ResampleData()\n\n def ResampleData( self, sample_factor=3):\n # resample data based on time pixels\n\n # Define an interpolation function for positions\n ifunc_pos = interpolate.interp1d( self.time, self.position, kind='linear')\n\n # Define a grid of resampled time points \n self.time = np.linspace( self.time[0], self.time[-1], max([ 2, sample_factor*(self.time[-1]-self.time[0])]) )\n if len(self.time) == 1:\n pdb.set_trace()\n print('oops')\n self.position = ifunc_pos( self.time) \n\n# Class for a Pole\nclass Pole(Feature):\n def __init__(self, time, position, intensity=[], time_step=1, strain='xxx'):\n Feature.__init__(self, time, position, intensity, strain=strain, time_step=time_step)\n\n # Define an interpolation/extrapolation function\n self.ifunc = interpolate.interp1d(self.time, self.position, kind='linear', fill_value='extrapolate')\n\n def Print(self):\n print('Pole :')\n print(' ID : {}'.format(self.id))\n print(' Time : {}'.format( self.time))\n print(' Position : {}'.format( self.position))\n print(' Intensity : {}'.format( self.intensity))\n print('--------------------------------- ')\n\n# Class for a Track: additionally stores associated poles and track direction\nclass Track(Feature):\n def __init__(self, time, position, intensity, poles, direction, line_type, time_step=1, strain='xxx'):\n Feature.__init__(self, time, position, intensity, time_step=time_step, strain=strain)\n\n if time_step == 1:\n pdb.set_trace()\n print('woah')\n\n self.poles = poles\n self.direction = direction\n self.line_type = line_type\n self.polePosition = []\n self.data = {\n 'pos_pole' : np.zeros( (2, np.size(self.position) ) ),\n 'pos_track_rel' : [],\n 'velocity' : { 'P' : [], 'AP' : [],'I': []},\n 'runlength' : { 'P' : [], 'AP' : [],'I': []},\n 'lifetime' : { 'P' : [], 'AP' : [],'I': []},\n 'lifetime_total' : [],\n 'velocity_mean' : [],\n 'switch_count' : [],\n 'switch_total' : [],\n }\n self.bad = 0\n\n # Order poles with 1st pole being main pole(closest at start)\n # self.OrderPoles()\n\n # Calcualte spindle length\n self.CalcSpindleLength()\n\n if self.line_type == 'Curve' and self.direction != 'Ambiguous':\n self.direction = 'Ambiguous'\n # pdb.set_trace()\n # print('1')\n\n def Analyze(self, ipole=0):\n # Run useful analysis methods\n\n self.CalcPositionTrackRelativeToPole()\n\n # Split the track and save analysis \n tracks_mini, switches = self.SplitTrack( ipole=ipole)\n\n for track in tracks_mini:\n\n if track.direction == 'Poleward':\n label = 'P'\n elif track.direction == 'Antipoleward':\n label = 'AP'\n elif track.direction == 'Inactive':\n label = 'I'\n else:\n pdb.set_trace()\n raise ValueError('line direction is neither poleward nor antipoleward nor inactive')\n\n # Calculate and append data of the mini track\n # Velocity\n self.data['velocity'][label] += [track.CalcVelocityLinear(ipole=ipole)]\n # Run length\n self.data['runlength'][label] += [track.CalcRunLength(ipole=ipole)]\n # Lifetime\n self.data['lifetime'][label] += [track.CalcLifetime()]\n\n # Combine data from the split tracks\n self.data['lifetime_total'] = self.CalcLifetime()\n self.data['velocity_mean'] = self.CalcVelocityMean(ipole=ipole)\n self.data['switch_count'] = switches\n # pdb.set_trace()\n # print('woah')\n\n def OrderPoles(self):\n # Order the poles with the first one being the closest one to the start of the track\n\n if len(self.poles) != 2:\n return\n\n pos = self.CalcPositionTrackRelativeToPole()\n if np.absolute( pos[1,0] ) < np.absolute( pos[0,0]):\n self.poles = [self.poles[1], self.poles[0]]\n \n def CalcSpindleLength(self):\n # Calculate the spindle length\n\n if len(self.poles) != 2:\n return\n\n # Find the distance between the poles for the extent of this track\n self.spindleLength = np.absolute( self.poles[0].ifunc( self.time) - self.poles[1].ifunc( self.time) )\n\n def CheckViability(self):\n # Check if the track's time points are always increasing\n\n self.bad = 0\n # Check track time is always increasing\n if np.any( np.diff( self.time) <= 0 ):\n self.bad = 1 \n\n return self.bad\n\n def CheckLinearLifetime( self, min_lt = 0.5):\n # Check lifetime is above a min threshold\n\n self.bad = 0\n if self.line_type == 'Line' and self.CalcLifetime() < min_lt:\n self.bad = 1\n\n return self.bad\n\n\n def CalcPositionPoleCurrent(self):\n # Get pole position at the current time (i.e at the times of the track) by using the interpolation/extrapolation function of the pole\n\n for idx, pole in enumerate( self.poles) :\n pos_pole = np.array(pole.ifunc( self.time) )\n self.data['pos_pole'][idx,:] = pos_pole\n return self.data['pos_pole'] \n\n def CalcPositionTrackRelativeToPole(self):\n # Calculate track position relative to the pole \n\n pos_pole = self.CalcPositionPoleCurrent()\n\n # If bipolar spindle\n if len( self.poles) == 2:\n pos_track_rel = np.zeros( np.shape(pos_pole))\n for idx,ele in enumerate( pos_pole):\n pos_track_rel[idx,:] = np.array( self.position - ele)\n\n # If monopolar spindle\n else:\n pos_track_rel = np.array( self.position - pos_pole )\n # pos_track_rel = pos_track_rel[0,:]\n\n self.data['pos_track_rel'] = pos_track_rel\n return pos_track_rel\n\n def CalcVelocityLinear(self, ipole=0):\n # Calculate the velocity of this linear track\n \n if self.direction == 'Ambiguous':\n raise Exception('Track.CalcVelocityLinear() is only defined for tracks with a single direction')\n\n # Calc relative positions if not done already\n if len( self.data['pos_track_rel']) == 0 or not self.data['pos_track_rel'].any():\n pos_track_rel = self.CalcPositionTrackRelativeToPole()\n else:\n pos_track_rel = self.data['pos_track_rel']\n\n # Check\n if len(self.time) <= 1:\n pdb.set_trace()\n print('oops')\n\n # Find Velocity\n vel = np.average( np.absolute( np.divide( np.diff( pos_track_rel[ipole,:]) , np.diff( self.time) ) ), weights = np.diff(self.time) )\n\n # Check\n if np.size( vel) > 1:\n pdb.set_trace()\n print('1')\n\n return vel\n \n def CalcRunLength(self, ipole=0):\n # Calculate the run length of this track\n \n # Calc relative positions if not done already\n if len( self.data['pos_track_rel']) == 0 or not self.data['pos_track_rel'].any():\n pos_track_rel = self.CalcPositionTrackRelativeToPole()\n else:\n pos_track_rel = self.data['pos_track_rel']\n\n # Find Run length \n run_length = np.absolute( pos_track_rel[ipole,-1] - pos_track_rel[ipole,0] )\n \n self.data['run_length'] = run_length\n\n # Check\n if np.size( run_length) > 1:\n pdb.set_trace()\n print('1')\n\n return run_length\n\n def CalcLifetime(self):\n # Calculate the lifetime of this track\n\n lifetime = self.time[-1] - self.time[0]\n self.data['lifetime'] = lifetime\n return lifetime\n\n def CalcVelocityMean(self,ipole=0):\n # Calculate the mean velocity of this track\n\n if self.line_type == 'Curve' and not self.data['velocity']:\n # Split the track \n tracks_mini = self.SplitTrack()\n for track in tracks_mini:\n vv = track.CalcVelocityLinear()\n if track.direc == 'Poleward':\n self.data['velocity']['P'] += [ vv[ipole]]\n elif self.direc == 'Antipoleward':\n self.data['velocity']['AP'] += [ vv[ipole]]\n \n vel_mu = np.mean( np.concatenate( (self.data['velocity']['P'], self.data['velocity']['AP']) ) )\n return vel_mu\n\n def CalcSwitchingCount(self):\n # Calculate the mean velocity of this track\n\n if self.line_type == 'Curve' and not self.data['velocity']:\n # Split the track \n tracks_mini = self.SplitTrack()\n for track in tracks_mini:\n if track.direc == 'Poleward':\n self.data['velocity']['P'] += [track.CalcVelocityLinear()]\n elif self.direc == 'Antipoleward':\n self.data['velocity']['AP'] += [track.CalcVelocityLinear()]\n \n vel_mu = np.mean( np.concat( self.data['velocity']['P'], self.data['velocity']['AP']) )\n return vel_mu\n\n def CalcIntensityMean(self):\n # Calculate the mean intensity of this track\n self.data['intensity_mean'] = np.mean( self.intensity) \n \n def SplitTrack(self, ipole=0):\n # Spit curved track into multiple mini unidirectional tracks\n\n switches = {\n 'P' : { 'P' : 0, 'AP': 0, 'I' : 0,},\n 'AP' : { 'P' : 0, 'AP': 0, 'I' : 0,},\n 'I' : { 'P' : 0, 'AP': 0, 'I' : 0,},\n }\n\n if self.direction != 'Ambiguous':\n return [self], switches\n\n if self.line_type == 'Line' and self.direction == 'Ambiguous':\n position = np.absolute( self.CalcPositionTrackRelativeToPole() )\n vel = np.mean( np.divide( np.diff( position) , np.diff(self.time) ) )\n if abs( vel) < 0.005:\n self.direction = 'Inactive'\n elif vel > 0:\n self.direction = 'Antipoleward'\n elif vel < 0:\n self.direction = 'Poleward'\n return [self], switches\n\n # Find track position relative to the pole\n if len( self.data['pos_track_rel']) == 0 or not self.data['pos_track_rel'].any():\n position = self.CalcPositionTrackRelativeToPole()\n else:\n position = self.data['pos_track_rel'][ipole,:]\n\n position = np.absolute( position)\n states = []\n\n # Smoothing window:\n # Use a time-sliding window to find the average velocity, and use that to figure out state\n def FindStates_RollingWindow( positions, times, t_window, v_cutoff=1):\n\n dt = np.mean( np.diff( times) ) \n n_hwindow = int( np.ceil( t_window / (2*dt)) )\n states = []\n\n for i, t in enumerate( times): \n i_min = max( [ 0, i-n_hwindow])\n i_max = min( [ len(times), i+n_hwindow])\n\n vel = np.mean( np.divide( np.diff( positions[i_min:i_max] ) , np.diff( times[i_min:i_max] ) ) )\n # pdb.set_trace()\n\n # Assign labels based on value of vel \n if abs( vel) < v_cutoff:\n states += ['I']\n elif vel > 0:\n states += ['AP']\n elif vel < 0:\n states += ['P']\n\n return states\n \n states = FindStates_RollingWindow(position,self.time,5,v_cutoff=0.005)\n\n # Remove singly occuring states\n for cnt, st in enumerate(states):\n\n if cnt > 1 and cnt < len(states)-1:\n if st != states[cnt-1] and st != states[cnt+1]:\n states[cnt] = states[cnt-1]\n\n # set first state to second state\n if cnt == 0:\n states[cnt] = states[cnt+1]\n\n # set last state to second last state\n if cnt == len(states)-1:\n states[cnt] = states[cnt-1]\n\n # Count switches and get track indices\n p_state = 'XXX' \n track = { 'pos': [], 'time': [], 'dir':[] }\n idx = [0 , 0]\n for cnt, st in enumerate(states):\n \n if cnt == 0:\n p_state = st\n idx[0] = 0\n continue\n\n if st == p_state:\n idx[1] += 1 \n \n if st != p_state:\n\n # store old stuff\n pos = self.position[ idx[0]: idx[1]+2]\n # pos.tolist()\n time = self.time[ idx[0]: idx[1]+2]\n # time.tolist()\n track['pos'] += [pos]\n track['time'] += [time]\n track['dir'] += [p_state]\n p_state = st\n\n # begin new\n idx[0] = cnt\n idx[1] = cnt\n\n # Store the last info\n if cnt == len(states)-1:\n\n pos = self.position[ idx[0]: idx[1]+1]\n # pos.tolist()\n time = self.time[ idx[0]: idx[1]+1]\n # time.tolist()\n track['pos'] += [pos]\n track['time'] += [time]\n track['dir'] += [p_state]\n\n # record switches\n for cnt, dd in enumerate( track['dir']):\n if cnt == 0:\n continue\n switches[ track['dir'][cnt-1]][track['dir'][cnt]] += 1\n \n # Create track objects from the information\n mini_tracks = []\n for time, pos, direc in zip( track['time'], track['pos'], track['dir']):\n if direc is 'P':\n direction = 'Poleward'\n elif direc is 'AP':\n direction = 'Antipoleward'\n elif direc is 'I':\n direction = 'Inactive'\n pos = pos.tolist()\n time = time.tolist()\n if len(pos) == 1:\n pdb.set_trace()\n print('oops')\n\n mini_tracks += [Track( time, pos, self.intensity, self.poles, direction, 'Line', time_step=self.time_step, strain=self.strain)]\n\n # if self.strain == 'B PA-GFP' and mini_tracks[0].direction == 'Inactive':\n # pdb.set_trace()\n # print('1')\n \n for t in mini_tracks:\n if len( t.position) < 2:\n pdb.set_trace()\n print('oops')\n\n return mini_tracks, switches\n\n def PlotCurveWithStates(self, figname='curved_track.pdf'):\n # Plot a curve with states( inactive, poleward and antipoleward) in different colors.\n\n cols = {\n 'Inactive' : 'blue',\n 'Poleward' : 'red',\n 'Antipoleward' : 'green',\n }\n\n minis, switches = self.SplitTrack()\n\n # Generate figure and axes and set colors\n fig = plt.figure( figsize=(6,4) )\n ax = fig.add_subplot(111)\n\n pos_pole = self.CalcPositionPoleCurrent()\n for idx,pole in enumerate(self.poles):\n ax.plot( pos_pole[idx,:], self.time, linewidth=3 )\n\n for trk in minis:\n ax.plot( trk.position, trk.time, linewidth=2, color=cols[trk.direction] )\n\n plt.text(1,1, 'Poleward', color='red', transform=ax.transAxes, ha='right', va='top')\n plt.text(1,0.95, 'AntiPoleward', color='green', transform=ax.transAxes, ha='right', va='top')\n plt.text(1,0.9, 'Inactive', color='blue', transform=ax.transAxes, ha='right', va='top')\n plt.text(1,0.85, 'MainPole', color='skyblue', transform=ax.transAxes, ha='right', va='top')\n plt.text(1,0.8, 'SecondaryPole', color='orange', transform=ax.transAxes, ha='right', va='top')\n # Set axes limits\n axes = plt.gca()\n x_min = min([ min(self.position), min([min( pol.position) for pol in self.poles]) ]) -0.5\n x_max = max([ max( self.position), max([max( pol.position) for pol in self.poles]) ]) +0.5\n axes.set_xlim([ x_min, x_max])\n axes.set_xlabel('Position')\n axes.set_ylim([ min(self.time)-5,max(self.time)+5])\n axes.set_ylabel('Time')\n\n fig.savefig( figname)\n\n def Trim(self,lrange=[0,100]):\n # Trim the track to be inside the range specified\n \n if len( self.poles) == 1:\n return self\n\n # Get indices of times when spindle length is between the given range values\n lens = self.spindleLength\n idx = np.argwhere( (lens > lrange[0]) & (lens < lrange[1]) ).T[0].tolist()\n if len(idx) == 0:\n return None\n\n idx = range( idx[0], idx[-1]+1) \n\n # Create the new trimmed track\n tracknew = Track( self.time[idx], self.position[idx], self.intensity, self.poles, self.direction, self.line_type, time_step=self.time_step, strain=self.strain)\n\n return tracknew\n\n\n def Print(self):\n print('Feature :')\n print(' ID : {}'.format(self.id))\n print(' Direction : {}'.format( self.direction))\n print(' Line type : {}'.format( self.line_type))\n print(' Time : {}'.format( self.time))\n print(' Position : {}'.format( self.position))\n print(' Intensity : {}'.format( self.intensity))\n print('--------------------------------- ')\n\n\n" }, { "alpha_fraction": 0.6061967015266418, "alphanum_fraction": 0.6201167702674866, "avg_line_length": 34.90322494506836, "blob_id": "9748d0f6fe0e56776858f022279670aec33cd15e", "content_id": "c1414835867e550e999df2f7b7d3712b44767837", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2227, "license_type": "permissive", "max_line_length": 109, "num_lines": 62, "path": "/src/smooth_test.py", "repo_name": "saadjansari/KymoAnalysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os, pdb\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom pathlib import Path\nfrom .Kymograph import *\nimport shutil\n\n'''\nName: breakBipolar.py\nDescription: Plots the pole separation of a bipolar file\n'''\n\nfolds = ['wild type']\nsavepath = Path('/Users/saadjansari/Documents/Projects/ImageAnalysis/KymoAnalysis/Analysis/result_smoothing')\nparent_path = Path('/Users/saadjansari/Documents/Projects/ImageAnalysis/KymoAnalysis/data/temp')\n\ndef smooth_data(arr, span):\n re = np.convolve(arr, np.ones(span * 2 + 1) / (span * 2 + 1), mode=\"same\")\n\n # The \"my_average\" part: shrinks the averaging window on the side that\n # reaches beyond the data, keeps the other side the same size as given\n # by \"span\"\n re[0] = np.average(arr[:span])\n for i in range(1, span + 1):\n re[i] = np.average(arr[:i + span])\n re[-i] = np.average(arr[-i - span:])\n return re\n\nif not Path.exists( savepath):\n os.mkdir( savepath)\n\nfor jj,jfold in enumerate(folds):\n print('Data: {0}'.format(jfold))\n mainpath = parent_path / jfold\n # txt files\n files2break = mainpath.glob('*txt')\n\n # Pole separation vs time\n print('Calculating pole separations...')\n for jj, fil in enumerate(files2break):\n # print(fil)\n kymo = Kymograph(fname=str(fil))\n\n if len(kymo.poles) == 2:\n fig, ax = plt.subplots()\n time = np.array( sorted( np.hstack( (kymo.poles[0].time, kymo.poles[1].time) ) )[1::10] )\n time = np.linspace(time[0], time[-1], int(np.ceil(time[-1]-time[0])))\n spindleLength = np.array( np.absolute( kymo.poles[1].ifunc(time)- kymo.poles[0].ifunc(time)) )\n slope_windows = [5,25,50]\n for slope in slope_windows:\n spindleLength_cnv = smooth_data(spindleLength, slope)\n ax.plot(time, spindleLength_cnv, label='Window = {0}'.format(slope))\n\n ax.plot(time, spindleLength, 'k:', lw=2,label='Original')\n ax.legend()\n ax.set(xlabel='Time (s)', ylabel=r'Pole separation ($\\mu m$)')\n\n plt.tight_layout()\n plt.savefig(savepath / 'smoothing_{0}_{1}.pdf'.format(mainpath.stem, jj))\n plt.close(fig)\n\n" }, { "alpha_fraction": 0.4784288704395294, "alphanum_fraction": 0.4961358904838562, "avg_line_length": 35.455108642578125, "blob_id": "8e5656340533f3763b2e6b67f03118e873fc1195", "content_id": "b017925daf29b5d09145641a2d68709af12713e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23550, "license_type": "permissive", "max_line_length": 167, "num_lines": 646, "path": "/src/Strain.py", "repo_name": "saadjansari/KymoAnalysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os, pdb\nfrom .Load import Load\nfrom .Kymograph import Kymograph\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport math, random\nimport pickle\nfrom pathlib import Path\nfrom scipy import interpolate, signal\n\n\nclass Strain:\n def __init__(self, trackpaths, label=\"xxx\"):\n\n self.paths = trackpaths\n self.label = label\n self.LoadKymographs()\n self.tracks = []\n\n def LoadKymographs(self):\n # Initialize kymograph classes for each loaded file\n self.kymographs = []\n for pth in self.paths:\n print(pth)\n kname = pth.split(\"/\")[-1]\n self.kymographs += [Kymograph(fname=pth)]\n\n def GetTracks(self, spindle_length=None):\n # Get tracks that lie within the spindle lengths defined. Trims the tracks\n # Combine tracks from all kymographs\n self.tracks = []\n for kymo in self.kymographs:\n for track in kymo.tracks:\n trimmed = track.Trim(lrange=spindle_length)\n if trimmed is not None:\n self.tracks += [trimmed]\n\n def TrimUsingKmeansLabel(self, kmean_label):\n\n # load kmeans model\n kmeans_path = Path(self.paths[0]).parent / \"kmeans.pickle\"\n with open(kmeans_path, \"rb\") as f:\n model = pickle.load(f)\n\n for kymo in self.kymographs:\n # Only do stuff if its bipolar\n if len(kymo.poles) == 1:\n continue\n\n # Times\n time = np.array(\n sorted(np.hstack((kymo.poles[0].time, kymo.poles[1].time)))[1::10]\n )\n time = np.linspace(time[0], time[-1], int(np.ceil(time[-1] - time[0])))\n\n # Calculate spindle length, velocity, acceleration\n clen = np.absolute(kymo.poles[1].ifunc(time) - kymo.poles[0].ifunc(time))\n cvel = list((clen[1:] - clen[:-1]) / (time[1:] - time[:-1]))\n cvel.insert(0, cvel[0])\n cvel = np.array(cvel).reshape(-1, 1)\n # use velocity to predict label using fitted model\n labels_raw = model.predict(cvel)\n labels = self.ForceLabelsOneWay(\n self.SmoothClassifiedLabels(labels_raw, span=100)\n )\n if np.max(labels) == 0 or np.max(clen) < 2:\n AB_transition = -1\n if kmean_label == 0:\n time_keep = [time[0], time[-1]]\n elif kmean_label == 1:\n time_keep = [-1, -1]\n elif np.min(labels) == 1:\n AB_transition = -1\n if kmean_label == 0:\n time_keep = [-1, -1]\n elif kmean_label == 1:\n time_keep = [time[0], time[-1]]\n else:\n AB_transition = time[np.where((labels == 1) & (clen > 2))[0][0]]\n if kmean_label == 0:\n time_keep = [time[0], AB_transition]\n elif kmean_label == 1:\n time_keep = [AB_transition, time[-1]]\n # if kymo.label == '/Users/saadjansari/Documents/Projects/ImageAnalysis/KymoAnalysis/data/bipolar/wild type/MAX_1032_100msR_50msG_7Z_004_cell A_KYMOGRAPH':\n # pdb.set_trace()\n # print(AB_transition)\n # print(time_keep)\n print(\"Total time = {0:.2f} - {1:.2f}\".format(time[0], time[-1]))\n print(\"Anaphase B = {0:.2f}\".format(AB_transition))\n print(\"Kmeans Label = {0}\".format(kmean_label))\n print(\"Time 2 keep = {0}\".format(time_keep))\n kymo.TrimBasedOnTime(time_keep)\n\n # SmoothClassifiedLabels {{{\n def SmoothClassifiedLabels(self, label, span=100):\n\n # smooth_data {{{\n def smooth_data(arr, span):\n re = np.convolve(arr, np.ones(span * 2 + 1) / (span * 2 + 1), mode=\"same\")\n\n # The \"my_average\" part: shrinks the averaging window on the side that\n # reaches beyond the data, keeps the other side the same size as given\n # by \"span\"\n re[0] = np.average(arr[:span])\n for i in range(1, span + 1):\n re[i] = np.average(arr[: i + span])\n re[-i] = np.average(arr[-i - span :])\n return re\n\n # }}}\n\n # Smoothed Labels\n label_new = np.where(\n np.array(smooth_data(label, min([span, int(len(label) / 2)]))) >= 0.5, 1, 0\n )\n\n # Once 1, always 1\n # label_perm = [max(label_new[:1+jj]) for jj in range(len(label_new))]\n return label_new\n\n # }}}\n\n # ForceLabelsOneWay {{{\n def ForceLabelsOneWay(self, label):\n labels = [np.max(label[: 1 + idx]) for idx in range(len(label))]\n return np.array(labels)\n\n # }}}\n\n def TossFarTracks(self, threshold):\n # Toss tracks that start above a threshold distance from the first pole\n self.tracks = []\n for kymo in self.kymographs:\n tracksKeep = []\n for track in kymo.tracks:\n if track.CalcPositionRelative()[0, 0] < threshold:\n tracksKeep.append(track)\n kymo.tracks = tracksKeep\n self.GetTracks()\n\n def TossCloseTracks(self, threshold):\n # Toss tracks that start above a threshold distance from the first pole\n self.tracks = []\n for kymo in self.kymographs:\n tracksKeep = []\n for track in kymo.tracks:\n if track.CalcPositionRelative()[0, 0] > threshold:\n tracksKeep.append(track)\n kymo.tracks = tracksKeep\n self.GetTracks()\n\n def GetSegmentsPAP(self):\n # Splits the tracks into segments and returns [poleward, antipoleward]\n segs = {\"Poleward\": [], \"Antipoleward\": []}\n bad_cnt = 0\n good_cnt = 0\n for track in self.tracks:\n segments, _ = track.SplitTrack()\n\n # Toss short-time segments\n for seg in segments:\n if seg.time[-1] - seg.time[0] < 2 * seg.time_step:\n bad_cnt += 1\n elif seg.direction is \"Poleward\":\n good_cnt += 1\n segs[\"Poleward\"] += [seg]\n elif seg.direction is \"Antipoleward\":\n good_cnt += 1\n segs[\"Antipoleward\"] += [seg]\n\n # if good_cnt + bad_cnt > 0:\n # print('Major segments : {0} ({1:.2f}%)'.format(good_cnt, 100*good_cnt/(good_cnt+bad_cnt)))\n return [segs[\"Poleward\"], segs[\"Antipoleward\"]]\n\n def FilterSegments(self, segments):\n # Filter segments by imposing restrictions on velocity, run length and lifetimes\n # Velocities\n print(\"1\")\n\n def GetRunLengths(self):\n # Get run lengths of poleward and antipoleward tracks (units nm)\n segsPAP = self.GetSegmentsPAP()\n runlens = []\n for segs in segsPAP:\n runlen = [\n 1000\n * np.absolute(\n seg.CalcPositionRelative()[0, -1] - seg.CalcPositionRelative()[0, 0]\n )\n for seg in segs\n ]\n runlens += [runlen]\n return runlens\n\n def GetVelocities(self):\n # Get velocities of poleward and antipoleward tracks (units nm/sec)\n segsPAP = self.GetSegmentsPAP()\n vels = []\n for segs in segsPAP:\n vel = [1000 * seg.CalcVelocity()[0] for seg in segs]\n vels += [vel]\n return vels\n\n def GetLifetimes(self):\n # Get velocities of poleward and antipoleward tracks (units sec)\n segsPAP = self.GetSegmentsPAP()\n lifes = []\n for segs in segsPAP:\n life = [seg.time[-1] - seg.time[0] for seg in segs]\n lifes += [life]\n return lifes\n\n def GetIntensities(self):\n # Get velocities of poleward and antipoleward tracks\n segsPAP = self.GetSegmentsPAP()\n ins = []\n for segs in segsPAP:\n inss = [seg.CalcIntensity() for seg in segs]\n ins += [inss]\n return ins\n\n def GetTotalSwitches(self):\n # Get total switches out of state A to state B (states: poleward,antipoleward,inactive)\n\n switches = {\"P\": 0, \"AP\": 0, \"I\": 0}\n labs = [\"P\", \"AP\", \"I\"]\n for track in self.tracks:\n segments, trans = track.SplitTrack()\n for lab in labs:\n switches[lab] += sum([a for k, a in trans[lab].items()])\n return switches\n\n def GetFractionKymographsWithMovement(self):\n # Get fraction of kymographs with movement events\n\n nMovement = 0\n for kymo in self.kymographs:\n nAdd = 0\n for track in kymo.tracks:\n trks_all, _ = track.SplitTrack()\n for mini in trks_all:\n if mini.direction != \"Inactive\":\n nAdd = 1\n nMovement += nAdd\n return nMovement / len(self.kymographs)\n\n def GetDirectionalEventsPerMinute(self):\n # Get total number of directional events per minute\n\n events = {\"P\": 0, \"AP\": 0}\n events_per_min = {\"P\": 0, \"AP\": 0}\n for track in self.tracks:\n segs, _ = track.SplitTrack()\n for seg in segs:\n if seg.direction == \"Poleward\":\n events[\"P\"] += 1\n elif seg.direction == \"Antipoleward\":\n events[\"AP\"] += 1\n\n # total kymograph time\n time_total = 0\n for kymo in self.kymographs:\n time_total += kymo.poles[0].time[-1] - kymo.poles[0].time[0]\n events_per_min[\"P\"] = events[\"P\"] / (time_total / 60)\n events_per_min[\"AP\"] = events[\"AP\"] / (time_total / 60)\n return events_per_min, events\n\n def GetDirectionalEventsPerMinutePerCell(self):\n # Get total number of directional events per minute per cell\n\n events = {\"P\": [], \"AP\": []}\n times = {\"P\": [], \"AP\": []}\n for kymo in self.kymographs:\n nP = 0\n nAP = 0\n for track in kymo.tracks:\n segs, _ = track.SplitTrack()\n for seg in segs:\n if seg.direction == \"Poleward\":\n nP += 1\n elif seg.direction == \"Antipoleward\":\n nAP += 1\n if nP + nAP > 0:\n time_total = kymo.poles[0].time[-1] - kymo.poles[0].time[0]\n else:\n time_total = 1\n if time_total > 1:\n events[\"P\"].append(nP)\n events[\"AP\"].append(nAP)\n times[\"P\"].append(time_total / 60)\n times[\"AP\"].append(time_total / 60)\n # events['P'].append( nP/(time_total/60))\n # events['AP'].append( nAP/(time_total/60))\n return events, times\n\n def GetTotalDirectionalTime(self):\n # Find total number of directed time\n\n times = {\"P\": 0.01, \"AP\": 0.01, \"I\": 0.01}\n for track in self.tracks:\n # Split the track into linear tracks\n segs, _ = track.SplitTrack()\n # Calculate lifetimes and sum it all up for each direction of the track\n for seg in segs:\n if seg.direction == \"Poleward\":\n times[\"P\"] += seg.time[-1] - seg.time[0]\n elif seg.direction == \"Antipoleward\":\n times[\"AP\"] += seg.time[-1] - seg.time[0]\n elif seg.direction == \"Inactive\":\n times[\"I\"] += seg.time[-1] - seg.time[0]\n else:\n raise ValueError(\"what is this unknown line direction\")\n return times\n\n def GetTotalDirectionalTimeMinutes(self):\n # Find total number of directed time\n\n times = {\"P\": 0.01, \"AP\": 0.01, \"I\": 0.01}\n for track in self.tracks:\n # Split the track into linear tracks\n segs, _ = track.SplitTrack()\n # Calculate lifetimes and sum it all up for each direction of the track\n for seg in segs:\n if seg.direction == \"Poleward\":\n times[\"P\"] += (seg.time[-1] - seg.time[0]) / 60\n elif seg.direction == \"Antipoleward\":\n times[\"AP\"] += (seg.time[-1] - seg.time[0]) / 60\n elif seg.direction == \"Inactive\":\n times[\"I\"] += (seg.time[-1] - seg.time[0]) / 60\n else:\n raise ValueError(\"what is this unknown line direction\")\n return times\n\n def GetSwitchFrequencyPerMinutePerCell(self):\n\n events = {\"P\": [], \"AP\": [], \"I\": []}\n times_all = {\"P\": [], \"AP\": [], \"I\": []}\n for kymo in self.kymographs:\n\n # Get total track time\n times = {\"P\": 10 ** -7, \"AP\": 10 ** -7, \"I\": 10 ** -7}\n for track in kymo.tracks:\n # Split the track into linear tracks\n segs, _ = track.SplitTrack()\n # Calculate lifetimes and sum it all up for each direction of the track\n for seg in segs:\n if seg.direction == \"Poleward\":\n times[\"P\"] += (seg.time[-1] - seg.time[0]) / 60\n elif seg.direction == \"Antipoleward\":\n times[\"AP\"] += (seg.time[-1] - seg.time[0]) / 60\n elif seg.direction == \"Inactive\":\n times[\"I\"] += (seg.time[-1] - seg.time[0]) / 60\n else:\n raise ValueError(\"what is this unknown line direction\")\n\n # Get total switches\n switches = {\"P\": 0, \"AP\": 0, \"I\": 0}\n labs = [\"P\", \"AP\", \"I\"]\n for track in kymo.tracks:\n segments, trans = track.SplitTrack()\n for lab in labs:\n switches[lab] += sum([a for k, a in trans[lab].items()])\n\n # switch frequencies\n for lab in labs:\n events[lab].append(switches[lab])\n times_all[lab].append(times[lab])\n return events, times_all\n\n def GetStartDistances(self):\n # Get start distances\n\n dist_P = []\n dist_AP = []\n for track in self.tracks:\n segs, _ = track.SplitTrack()\n for seg in segs:\n if seg.direction == \"Poleward\":\n dist_P.append(seg.CalcPositionRelative()[0, 0])\n elif seg.direction == \"Antipoleward\":\n dist_AP.append(seg.CalcPositionRelative()[0, 0])\n\n return [dist_P, dist_AP]\n\n def GetEndDistances(self):\n # Get end distances\n\n dist_P = []\n dist_AP = []\n for track in self.tracks:\n segs, _ = track.SplitTrack()\n for seg in segs:\n if seg.direction == \"Poleward\":\n dist_P.append(seg.CalcPositionRelative()[0, -1])\n elif seg.direction == \"Antipoleward\":\n dist_AP.append(seg.CalcPositionRelative()[0, -1])\n\n return [dist_P, dist_AP]\n\n def GetAverageDistances(self):\n # Get average distances\n\n segsPAP = self.GetSegmentsPAP()\n avgdists = []\n for segs in segsPAP:\n avgdist = []\n for seg in segs:\n ifunc = interpolate.interp1d(\n seg.time, seg.CalcPositionRelative()[0, :], kind=\"linear\"\n )\n avgdist.extend(\n [\n 1000 * dd\n for dd in ifunc(\n np.arange(seg.time[0], seg.time[-1], seg.time_step)\n )\n ]\n )\n # avgdist = [np.mean(seg.CalcPositionRelative()[0, :]) for seg in segs]\n avgdists += [avgdist]\n return avgdists\n\n def GraphPAP_RunLengths(self, axs, **kwargs):\n lens_pap = self.GetRunLengths()\n # Toss runlengths over 2 micron\n for idx, lens in enumerate(lens_pap):\n ld = [i for i in lens if i < 2]\n lens_pap[idx] = ld\n self.GraphPAP(lens_pap, axs, unit=r\"$\\mu$\" + \"m\", **kwargs)\n\n def GraphPAP_Velocities(self, axs, **kwargs):\n vels_pap = self.GetVelocities()\n # Convert vel from micron/sec to nm/sec. Toss vel over 200 micron/sec\n for idx, v in enumerate(vels_pap):\n ld = [i * 1000 for i in v if i < 0.2]\n vels_pap[idx] = ld\n self.GraphPAP(vels_pap, axs, unit=\"nm/s\", **kwargs)\n\n def GraphPAP_Lifetimes(self, axs, **kwargs):\n lifes_pap = self.GetLifetimes()\n # toss lifetimes over 100 sec\n for idx, life in enumerate(lifes_pap):\n ld = [i for i in life if i < 100]\n lifes_pap[idx] = ld\n self.GraphPAP(lifes_pap, axs, unit=\"s\", **kwargs)\n\n def GraphPAP_StartPosition(self, axs, **kwargs):\n startPos = self.GetStartDistances()\n self.GraphPAP(startPos, axs, unit=r\"$\\mu$\" + \"m\", **kwargs)\n\n def GraphPAP_EndPosition(self, axs, **kwargs):\n endPos = self.GetEndDistances()\n self.GraphPAP(endPos, axs, unit=r\"$\\mu$\" + \"m\", **kwargs)\n\n def GraphPAP(\n self, dat, axs, col=\"m\", lab=None, unit=\"\", xmax=None, xlab=None, ylab=None\n ):\n\n # pdb.set_trace()\n for datt, ax in zip(dat, axs):\n\n # Get x axis max\n if xmax is None:\n # xmax = math.ceil( max(datt))\n xmax = max(datt)\n\n # find bin edges\n nbins = 16\n bins = np.array([float(el) for el in range(nbins + 1)])\n bins = np.dot(np.array(xmax / float(nbins)), bins)\n\n # Plot histogram\n aaa = ax.hist(datt, bins, edgecolor=\"k\", color=col)\n\n # Add labels\n if xlab is not None:\n ax.set_xlabel(xlab)\n if ylab is not None:\n ax.set_ylabel(ylab)\n\n # Set x-limits\n ax.set_xlim([0, xmax])\n # Set y-limits and ticks\n ymax = int(math.ceil(ax.get_ylim()[1] / 10) * 10)\n ax.set_yticks([0, ymax / 2, ymax])\n ax.set_ylim([0, ymax + 2])\n\n # Add strain label\n if lab is not None:\n ax.text(\n 0.95,\n 0.95,\n lab,\n ha=\"right\",\n va=\"top\",\n transform=ax.transAxes,\n fontsize=12,\n weight=\"roman\",\n )\n\n # Add median line\n ax.axvline(np.mean(datt), color=\"k\", linestyle=\"dashed\", linewidth=5)\n # Add median value label\n # mu = np.median( lens )\n mu = np.mean(datt)\n form = \"%.2f\"\n mu_str = np.array2string(mu, formatter={\"float_kind\": lambda mu: form % mu})\n std = np.std(datt)\n std = std / np.sqrt(len(datt))\n std_str = np.array2string(\n std, formatter={\"float_kind\": lambda std: form % std}\n )\n ax.text(\n 0.95,\n 0.85,\n r\"{0} $\\pm$ {1} {2}\".format(mu_str, std_str, unit),\n ha=\"right\",\n va=\"top\",\n transform=ax.transAxes,\n fontsize=12,\n weight=\"roman\",\n )\n ax.text(\n 0.95,\n 0.75,\n r\"N = {0}\".format(len(datt)),\n ha=\"right\",\n va=\"top\",\n transform=ax.transAxes,\n fontsize=12,\n weight=\"roman\",\n )\n\n def PlotTrackByStates(self, cols, k=5):\n # Generate figure and axes and set colors\n\n fig, axs = plt.subplots(3, 1, figsize=(10, 6), sharex=True)\n axsd = {\"Poleward\": axs[0], \"Antipoleward\": axs[1], \"Inactive\": axs[2]}\n\n k = min([k, len(self.tracks)])\n for idx, track in enumerate(random.sample(self.tracks, k)):\n\n minis, _ = track.SplitTrack()\n ax = axsd[minis[0].direction]\n\n # if self.label == \"TD\" and minis[0].direction == 'Antipoleward':\n # pdb.set_trace()\n # print('1')\n for trk in minis:\n pos_track_rel = trk.CalcPositionRelative()\n ax.plot(\n trk.time - track.time[0],\n np.absolute(pos_track_rel[0, :]),\n linewidth=0.5,\n color=cols[trk.direction],\n alpha=0.4,\n )\n\n # Set x and y limits of subplots\n xl = (0, 0)\n yl = (0, 0)\n for ax in axs:\n xli = ax.get_xlim()\n yli = ax.get_ylim()\n xl = (min([xli[0], xl[0]]), max([xli[1], xl[1]]))\n yl = (min([yli[0], yl[0]]), max([yli[1], yl[1]]))\n\n # Force x limit\n xl = (xl[0], 400)\n\n # Legend\n axs[0].plot([], [], label=\"Poleward\", color=cols[\"Poleward\"])\n axs[0].plot([], [], label=\"AntiPoleward\", color=cols[\"Antipoleward\"])\n axs[0].plot([], [], label=\"Inactive\", color=cols[\"Inactive\"])\n axs[0].legend(frameon=False)\n\n axs[2].set_xlabel(\"Time (s)\")\n # axs[0].set_ylabel(r'Distance from SPB ($\\mu m$)')\n axs[1].set_ylabel(r\"Distance from SPB ($\\mu m$)\")\n # axs[2].set_ylabel(r'Distance from SPB ($\\mu m$)')\n axs[0].set_ylim(bottom=-0.01, top=yl[1])\n axs[1].set_ylim(bottom=-0.01, top=yl[1])\n axs[2].set_ylim(bottom=-0.01, top=yl[1])\n axs[0].set_xlim(left=-1, right=xl[1])\n # axs[0].set_xlim(right=300) # WT monopolar\n # axs[0].set_xlim(right=400) # KLP5D monopolar\n # axs[0].xaxis.set_ticklabels([])\n # axs[1].xaxis.set_ticklabels([])\n\n plt.tight_layout()\n fig.savefig(\"tracks_by_state_{0}.pdf\".format(self.label))\n # fig.subplots_adjust(hspace = -0.2)\n plt.close()\n\n def PlotAllTracks(self, cols):\n\n fig, ax = plt.subplots(figsize=(4, 3))\n # axsd = {'Poleward': axs[0], 'Antipoleward': axs[1], 'Inactive':axs[2]}\n\n for idx, track in enumerate(self.tracks):\n\n minis, _ = track.SplitTrack()\n for trk in minis:\n pos_track_rel = trk.CalcPositionRelative()\n ax.plot(\n trk.time - track.time[0],\n np.absolute(pos_track_rel[0, :]),\n linewidth=0.5,\n color=cols[trk.direction],\n alpha=0.6,\n )\n\n # Set x and y limits of subplots\n # ymax=9\n # xmax=1000\n # ax.set_xlim(left=0.0,right=xmax)\n # ax.set_ylim(bottom=-0.1,top=ymax)\n ax.set_xlim(left=0.0)\n ax.set_ylim(bottom=-0.01)\n ymax = ax.get_ylim()[1]\n xmax = ax.get_xlim()[1]\n ax.set(\n xlabel=\"Time (s)\",\n ylabel=\"Distance from SPB ($\\mu m$)\".format(len(self.tracks)),\n )\n # Adding text inside a rectangular box by using the keyword 'bbox'\n plt.text(0.8 * xmax, 0.6 * ymax, \"N = {0}\".format(len(self.tracks)), fontsize=8)\n\n # Legend\n ax.plot([], [], label=\"Poleward\", color=cols[\"Poleward\"])\n ax.plot([], [], label=\"Antipoleward\", color=cols[\"Antipoleward\"])\n ax.plot([], [], label=\"Inactive\", color=cols[\"Inactive\"])\n ax.legend()\n\n plt.tight_layout()\n plt.savefig(\"tracks_{0}.pdf\".format(self.label))\n # fig.subplots_adjust(hspace = -0.2)\n plt.close()\n\n\nif __name__ == \"__main__\":\n print(\"no default implementation\")\n" }, { "alpha_fraction": 0.538276195526123, "alphanum_fraction": 0.5531705021858215, "avg_line_length": 33.44905471801758, "blob_id": "da4d164cbdeb5e1b8a2fbd020068abff39087fcb", "content_id": "1881b4012bef86a104e1d69890ffafc4a2749c41", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9131, "license_type": "permissive", "max_line_length": 187, "num_lines": 265, "path": "/src/Kymograph.py", "repo_name": "saadjansari/KymoAnalysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os, pdb\nimport math\nimport numpy as np\nfrom scipy import interpolate\nfrom .node_graph import Graph\nimport matplotlib.pyplot as plt\n\nfrom .Features import *\nfrom .ReadFiles import *\n\n'''\nName: Kymograph.py\nDescription: Parses general, poles and feature information for a single kymograph and stores the data accordingly \n'''\n\nclass Kymograph:\n def __init__(self, fname='example.txt'):\n \n # get label without '.txt'\n self.label = fname[:-9] \n\n # Read file information \n self.general,self.poles,self.tracks = ReadTxt( fname)\n\n # Remove Bad tracks\n self.RemoveBadTracks()\n\n # Merge tracks whose ends are close enough\n self.MergeTracks(self.tracks)\n\n # Order track poles\n for track in self.tracks:\n track.OrderPoles()\n\n # Trim tracks based on kmeans label \n # self.TrimTracksKmeansLabel()\n\n def RemoveBadTracks(self):\n # Remove tracks that go backward in time\n\n # Find bad tracks\n bad_tracks = []\n for track in self.tracks:\n if not track.CheckViability():\n bad_tracks += [track]\n\n if len( bad_tracks) != 0:\n print('Found some bad tracks')\n\n # Remove bad tracks\n for track in bad_tracks:\n self.tracks.remove( track)\n\n def TrimBasedOnTime(self, time_keep=[-1,-1]):\n \n # Trim poles \n poles_new = []\n for pole in self.poles:\n trimmed = pole.TrimBasedOnTime(time_keep)\n if trimmed is not np.nan and trimmed is not None:\n poles_new.append(trimmed)\n # print(poles_new)\n # if self.label == '/Users/saadjansari/Documents/Projects/ImageAnalysis/KymoAnalysis/data/bipolar/wild type/MAX_1032_100msR_50msG_7Z_004_cell A_KYMOGRAPH':\n # pdb.set_trace()\n self.poles= poles_new \n\n # Trim tracks\n tracks_new = []\n for track in self.tracks:\n trimmed = track.TrimBasedOnTime(time_keep)\n if trimmed is not np.nan and trimmed is not None:\n # trimmed.poles = poles_new\n tracks_new.append(trimmed)\n # if self.label == '/Users/saadjansari/Documents/Projects/ImageAnalysis/KymoAnalysis/data/bipolar/wild type/MAX_1032_100msR_50msG_7Z_004_cell A_KYMOGRAPH':\n # pdb.set_trace()\n # print(tracks_new)\n self.tracks = tracks_new\n\n \n def MergeTracks(self, tracks):\n # Merge linear tracks into a single bidirectional track\n # Represent tracks as nodes in a directional graph\n \n box_half_width = 0.15\n box_height = 2*self.general['time_step']\n\n g = Graph( len( tracks) )\n matches = [[] for i in range( len(tracks) )]\n dist = [[] for i in range( len(tracks) )]\n\n # For each node, find prospective matches \n for v, trackv in enumerate( tracks):\n\n # Find all possible matches\n for w, trackw in enumerate( tracks):\n\n # if tracks are close together\n if ( trackv.position[-1]-box_half_width < trackw.position[0] < trackv.position[-1]+box_half_width ) and ( trackv.time[-1] < trackw.time[0] < trackv.time[-1]+box_height ): \n\n # Add as a possible match\n matches[v].append(w)\n\n # find distance of match \n t1 = [ trackv.position[-1], trackv.time[-1]]\n t2 = [ trackw.position[0], trackw.time[0]]\n dist[v].append( math.sqrt( ((t1[0]-t2[0])**2)+((t1[1]-t2[1])**2) ) )\n\n # Find the best match\n for v, trackv in enumerate( tracks):\n\n if len( matches[v]) == 0:\n continue\n\n # Find match with lowest distance\n w = matches[v][dist[v].index( min( dist[v]) )]\n\n # Add edge between v and w\n g.addEdge(v,w)\n\n # Find connected components\n cc = g.connectedComponents()\n\n # Merge the tracks in time order\n tracks_merged = []\n for comp in cc:\n time = None \n position = None \n \n if len( comp) == 1:\n line_type = tracks[comp[0]].line_type\n direction = tracks[comp[0]].direction\n else:\n line_type = 'Curve'\n direction = 'Ambiguous'\n\n for v in comp:\n if time is None: \n time = tracks[v].time\n else:\n time = np.concatenate( (time, tracks[v].time) )\n\n if position is None:\n position = tracks[v].position\n else:\n position = np.concatenate( (position, tracks[v].position) )\n\n tracks_merged += [Track(time, position, self.general['image'], self.poles, direction, line_type, time_step = self.general['time_step'], pos_step=self.tracks[0].pos_step)]\n \n return tracks_merged \n\n def PlotTracks( self, tracks, poles=[], figName='tracks.pdf'):\n # Plot the given tracks in a figure\n\n # Number of tracks\n nt = len(tracks)\n # Number of poles\n np = len(poles)\n # Number of plots\n nn = nt+np\n\n # Colormap\n cm = plt.get_cmap('gist_rainbow')\n\n # Generate figure and axes and set colors\n fig = plt.figure( figsize=(12,8) )\n ax = fig.add_subplot(111)\n ax.set_prop_cycle(color=[cm( 1.*i/nn) for i in range(nt)])\n\n for idx,pole in enumerate(poles):\n ax.plot( pole.position, pole.time, linewidth=3, label = 'Pole {}'.format(1+idx))\n\n for idx,track in enumerate(tracks):\n ax.plot( track.position, track.time, linewidth=2, label = 'Track {}'.format(1+idx))\n plt.legend()\n\n # Set axes limits\n time_max = max( [max(trk.time) for trk in tracks] + [max(pol.time) for pol in poles] )\n time_min = min( [min(trk.time) for trk in tracks] + [min(pol.time) for pol in poles] )\n x_max = max( [max(trk.position) for trk in tracks] + [max(pol.position) for pol in poles] ) + 0.5\n x_min = min( [min(trk.position) for trk in tracks] + [min(pol.position) for pol in poles] ) - 0.5\n\n axes = plt.gca()\n axes.set_xlim([x_min, x_max])\n axes.set_ylim([time_min,time_max])\n fig.savefig( figName )\n\n def FindIntensityAlongSpindle(self, lrange=[0, 10]):\n\n if len( self.poles) != 2:\n return None\n\n # pdb.set_trace()\n dimT = np.shape( self.general['image'])[0]\n dimX = np.shape( self.general['image'])[1]\n\n # interpolation function for image\n try:\n f = interpolate.interp2d( self.tracks[0].pos_step*np.arange(0,dimX), self.tracks[0].time_step*np.arange(0,dimT), self.general['image'])\n except:\n pdb.set_trace()\n print('1')\n\n # Get times to find pole position\n tStart = max( self.poles[0].time[0], self.poles[1].time[0])\n tEnd = min( self.poles[0].time[-1], self.poles[1].time[-1])\n tVec = np.linspace( tStart, tEnd, math.ceil( (tEnd-tStart)/self.tracks[0].time_step) )\n\n # Get pole position\n pos0 = self.poles[0].ifunc( tVec)\n pos1 = self.poles[1].ifunc( tVec)\n\n # pdb.set_trace()\n # Trim to be within range\n pos0c = [i for i,j in zip(pos0,pos1) if np.abs(i-j) > lrange[0] and np.abs(i-j) < lrange[1]]\n pos1c = [j for i,j in zip(pos0,pos1) if np.abs(i-j) > lrange[0] and np.abs(i-j) < lrange[1]]\n tVecc = [k for i,j,k in zip(pos0,pos1,tVec) if np.abs(i-j) > lrange[0] and np.abs(i-j) < lrange[1]]\n if len(pos0c) == 0:\n return None\n\n # Find intensity between poles for each time value\n intense = np.zeros( (len(tVecc),100) )\n for i, tt in enumerate(tVecc):\n pVec = np.linspace( pos0c[i], pos1c[i],100)\n ttVec = tt*np.ones((100,))\n intense[i,:] = f( pVec, ttVec)[0,:]\n return intense\n\n # # Trim tracks based on kmeans label \n # def TrimTracksKmeansLabel(self, label=-1):\n\n def DisplayTracks(self, ax=None):\n\n if ax is None:\n fig, ax = plt.subplots(figsize=(6,6))\n\n # Display kymograph image\n ax.imshow( self.tracks[0].image)\n\n # Plot tracks\n for track in self.tracks:\n ax.plot( track.position/track.pos_step, track.time/track.time_step, color='red', linewidth=3)\n plt.show()\n\n\n def Print(self):\n # Print information about poles and tracks\n\n print(' ')\n print(' path: {}'.format(self.general['path_tiff'][0:-1]))\n print(' name: {}'.format(self.label ))\n print(' n_poles_exp: {}'.format(self.general['n_poles']))\n print(' n_poles_found: {}'.format(len(self.poles)))\n print(' n_tracks_exp: {}'.format(self.general['n_tracks']))\n print(' n_tracks_found: {}'.format( len(self.tracks)))\n print(' ')\n\n for feat in self.poles+self.tracks:\n feat.Print()\n\n\n##########################################\nif __name__ == \"__main__\":\n print('No default run method')\n\n\n" }, { "alpha_fraction": 0.7787196636199951, "alphanum_fraction": 0.7866120934486389, "avg_line_length": 51.630767822265625, "blob_id": "ee8fa4d09f3283a2907c26d3cf7cad78976cbe6e", "content_id": "01dcc0499a2899f753da9a7512b0af3246e175a1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3426, "license_type": "permissive", "max_line_length": 568, "num_lines": 65, "path": "/README.md", "repo_name": "saadjansari/KymoAnalysis", "src_encoding": "UTF-8", "text": "# KymoAnalysis\n\nKymoAnalysis is a tool that allows users to analyze tracks extracted via KymoAnnotate (https://github.com/saadjansari/KymoAnnotate.git)\n\nThis is useful for analysis of protein movement in fluorescent microscopy.\n\n## Prerequisites\n\nBefore you begin, ensure you have met the following requirements:\n* You have `Python3` (this was tested on Python 3.9.5)\n* You have installed `git`.\n* You have a `MacOS` machine (not tested on `Linux/Windows`).\n\n## Installing KymoAnalysis\n\nTo install KymoAnalysis, follow these steps:\n\n```\ngit clone https://github.com/saadjansari/KymoAnalysis.git\n```\n\n## Using KymoAnalysis\n\nTo run KymoAnalysis, copy an example config.yaml file and then run KymographAnalysis.py.\n```\ncd KymoAnalysis\ncp ExampleConfigFiles/config_bipolar_wt.yaml config.yaml\npython3 KymographAnalysis.py\n```\n\nThis should create a new folder named `wt_bipolar` which contains the analyzed results.\n\nThis repo has config and data files for:\n* Bipolar wt\n* Bipolar 989TD\n* Monopolar wt\n* Monopolar klp5D\n\n## How does it work?\n\nKymograph analysis involves processing the saved results from KymoAnnotate. \nFor a given strain (e.g. bipolar wt), analysis proceeded as follows:\n1. Read results file to yield SPB and cut7 tracks (config file specifies data path).\n2. Track merging. We started by merging tracks that were deemed to belong to the same global track. For example, if track 2 that began within some time interval of track 1 ending (in our case, twice the timestep), and the start position of track 2 was close to the end position of track 1 (in our case, 150 nm), then we merged the tracks (Fig. S2).\n3. Track splitting. After merging, we have a number of tracks that exhibit both poleward and antipoleward motion. Here, a track is split into poleward, antipoleward, and paused segments (Fig. S3) based on the average local velocity along the track. A cutoff value of 3 nm/sec is used. Points with velocity less than the cutoff are assigned as poleward, while points with velocity greater than the cutoff are assigned as antipoleward. The remained points are assigned as paused. With this threshold, we can split a track into poleward, antipoleward and paused segments.\n4. Tracks are analyzed with reference to the position of the SPB. To do that, we assigned each track to it’s nearest SPB. For monopolar spindles, there was only one pole and assignment was straightforward. For bipolar spindles with two SPBs, we picked the SPB that was closest to the track start position.\n5. Track position and velocity was measured relative to the closest SPB.\n6. For each kymograph, the frequency of directional events was calculated by counting the number of poleward and antipoleward tracks and dividing by the total observation time in the kymograph.\n7. Switching frequency was calculated by counting the number of switches out of a state (poleward and antipoleward) divided by the lifetime of tracks in that state. For example, switching frequency for exiting the poleward state was calculated by dividing the number of transitions out of the poleward state by the total lifetime of all poleward tracks.\n\n\n## Contributors\n\nThanks to the following people who have contributed to this project:\n\n* [@saadjansari](https://github.com/saadjansari) 📖\n\n\n## Contact\n\nIf you want to contact me you can reach me at [email protected].\n\n## License\n\nThis project uses the following license: [MIT](https://opensource.org/licenses/MIT).\n" }, { "alpha_fraction": 0.43792062997817993, "alphanum_fraction": 0.45781999826431274, "avg_line_length": 35.62981033325195, "blob_id": "d7c0aadf028a9f8b85eef2cdeae80ef3c2f382f8", "content_id": "a0f5fe00a41eb3194638d37568c232114a8e67eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 44725, "license_type": "permissive", "max_line_length": 152, "num_lines": 1221, "path": "/KymographAnalysis.py", "repo_name": "saadjansari/KymoAnalysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os, pdb, sys\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport math, random\nimport glob, yaml, copy, shutil\n\nfrom src.Strain import *\n\n\"\"\"\nName: KymographAnalysis.py\nDescription: Parses and combines tracks from multiple kymographs for mass analysis \n\"\"\"\n\n\nclass KymographAnalysis:\n def __init__(self):\n\n self.cwd = os.getcwd()\n # Read config file\n with open(\"config.yaml\") as f:\n self.config = yaml.load(f, Loader=yaml.CLoader)\n\n self.InitStrains()\n self.Analyze()\n\n # InitStrains {{{\n def InitStrains(self):\n\n # Initialize strains with track files\n self.strains = []\n # Get filenames for each strain\n for strain in self.config[\"strains\"]:\n trackpaths = []\n for fpath in strain[\"path\"]:\n trackpaths += glob.glob(fpath)\n\n # Initialize\n cstrain = Strain(trackpaths, label=strain[\"type\"])\n cstrain.color = tuple(np.array(strain[\"color\"]) / 255)\n self.strains += [cstrain]\n\n # Use Kmeans classfication if required\n if \"useBipolarKmeansLabel\" in self.config.keys():\n if self.config[\"useBipolarKmeansLabel\"]:\n for strain, strain_c in zip(self.strains, self.config[\"strains\"]):\n strain.TrimUsingKmeansLabel(kmean_label=strain_c[\"kmean_label\"])\n\n # }}}\n\n # Analyze {{{\n def Analyze(self):\n\n # Initialize graphing directory\n if \"saveName\" in self.config.keys():\n gdir = os.path.join(self.cwd, self.config[\"saveName\"])\n else:\n gdir = os.path.join(self.cwd, \"result\")\n if os.path.exists(gdir):\n shutil.rmtree(gdir, ignore_errors=True)\n os.mkdir(gdir)\n os.chdir(gdir)\n\n # Analyze by groups\n if self.config[\"analyzeByLength\"] is True:\n for group in self.config[\"analyzeGroups\"]:\n\n # CD to directory\n ggdir = os.path.join(gdir, group[\"type\"])\n os.mkdir(ggdir)\n os.chdir(ggdir)\n\n print(\"Analyzing {0}\".format(group[\"type\"]))\n strains = copy.deepcopy(self.strains)\n\n # Get tracks that match this spindle length\n for strain in strains:\n strain.GetTracks(spindle_length=group[\"length\"])\n\n # pdb.set_trace()\n if self.config[\"analyzeSpindleIntensity\"] is True:\n self.GraphSpindleIntensity(\n strains, lrange=group[\"length\"], gname=group[\"type\"]\n )\n self.Graph(strains, gname=group[\"type\"])\n\n else:\n\n if self.config[\"analyzeSPBAssociatedTracks\"] == 1:\n for strain in self.strains:\n strain.TossFarTracks(self.config[\"SPBRegion\"])\n\n if self.config[\"analyzeSPBAssociatedTracks\"] == 2:\n for strain in self.strains:\n strain.TossCloseTracks(self.config[\"SPBRegion\"])\n\n # Get all tracks\n for strain in self.strains:\n strain.GetTracks()\n\n if self.config[\"analyzeSpindleIntensity\"] is True:\n self.GraphSpindleIntensity(self.strains)\n self.Graph(self.strains)\n\n os.chdir(self.cwd)\n\n # }}}\n\n # Graph {{{\n def Graph(self, strains, gname=None):\n # Graph useful properties\n\n plt.rcParams.update({\"font.size\": 14})\n plt.rc(\"legend\", fontsize=12)\n\n self.PlotTracksByState(k=1000)\n self.PlotAllTracks()\n # self.GraphStrain_EventsPerMinutePerCellViolin()\n # self.GraphStrain_SwitchFrequencyPerCellViolin()\n # self.GraphStrain_SwitchFrequencyPerCell()\n self.GraphStrain_FractionMovement()\n self.GraphStrain_SwitchFrequency2()\n self.GraphStrain_EventsPerMinute2()\n # self.GraphStrain_EventsPerMinutePerCell()\n self.GraphHistComparison()\n # self.GraphStrainMedianValues()\n # self.GraphStrain_EventsPerMinutePerCellRaw()\n # self.GraphStrain_SwitchFrequencyPerCellRaw()\n\n # Scatter Plots\n graphscatvars = (\n ['Run displacement','Intensity','nm','AU','scatter_intensity_runlength.pdf'],\n # ['Velocity','Intensity',r'$\\mu$m/min','AU','scatter_intensity_velocity.pdf'],\n # ['Lifetime','Intensity','min','AU','scatter_intensity_lifetime.pdf'],\n # [\n # \"Run length\",\n # \"Velocity\",\n # r\"$\\mu$\" + \"m\",\n # \"nm/s\",\n # \"scatter_velocity_runlength.pdf\",\n # ],\n # [\n # \"Run length\",\n # \"Lifetime\",\n # r\"$\\mu$\" + \"m\",\n # \"min\",\n # \"scatter_lifetime_runlength.pdf\",\n # ],\n ['Velocity','Intensity','nm/s','AU','scatter_intensity_velocity.pdf'],\n # [\"Velocity\", \"Lifetime\", \"nm/s\", \"min\", \"scatter_lifetime_velocity.pdf\"],\n # [\n # \"Run length\",\n # \"Average distance from SPB\",\n # r\"$\\mu$\" + \"m\",\n # r\"$\\mu$m\",\n # \"scatter_avgSPBdistance_runlength.pdf\",\n # ],\n # [\n # \"Velocity\",\n # \"Average distance from SPB\",\n # \"nm/s\",\n # r\"$\\mu$m\",\n # \"scatter_avgSPBdistance_velocity.pdf\",\n # ],\n # [\n # \"Lifetime\",\n # \"Average distance from SPB\",\n # \"min\",\n # r\"$\\mu$m\",\n # \"scatter_avgSPBdistance_lifetime.pdf\",\n # ],\n ['Lifetime','Intensity','s','AU','scatter_intensity_lifetime.pdf'],\n )\n for x,y,xunit,yunit,figname in graphscatvars:\n self.GraphStrainScatter( strains,x,y,xlab=x,ylab=y,xunit=xunit,yunit=yunit,figname=figname )\n\n # self.GraphStrain_EventsPerMinute()\n # self.GraphStrain_AvgStartEnd()\n # self.GraphStrain_StateTimes()\n # self.GraphStrain_SwitchCounts()\n # self.GraphStrain_StateSwitchMatrix()\n\n # }}}\n\n # GraphHistComparison {{{\n def GraphHistComparison(self):\n def plot_median_special(ax, xloc, rel_height, col):\n\n (ybottom, ytop) = ax.get_ylim()\n ax.plot(\n [xloc, xloc],\n [ybottom, rel_height * ytop],\n color=col,\n linewidth=1.5,\n alpha=0.3,\n solid_capstyle=\"round\",\n )\n ax.plot(\n [xloc],\n [rel_height * ytop],\n marker=\"d\",\n color=col,\n alpha=0.6,\n markersize=6,\n )\n return ax\n\n graphhistvars = (\n [\n \"GetRunLengths\",\n \"Run displacement\",\n \"Count\",\n \"nm\",\n \"strain_runlength.pdf\",\n ],\n [\"GetVelocities\", \"Velocity\", \"Count\", \"nm/s\", \"strain_velocity.pdf\"],\n [\"GetLifetimes\", \"Lifetime\", \"Count\", \"s\", \"strain_lifetime.pdf\"],\n [\n \"GetAverageDistances\",\n \"Average distance from SPB\",\n \"Count\",\n \"nm\",\n \"strain_avg_pos.pdf\",\n ],\n )\n\n # Special x limits\n # xmaxes = {\n # 'Run displacement': 1.6,\n # 'Velocity': 100.0,\n # 'Lifetime': 1.6,\n # 'Average distance from SPB': 8.0,\n # }\n # if self.config['paperFigure'] == 5:\n # xmaxes['Velocity'] = 60.0\n xmaxes = {\n \"Run displacement\": 1600,\n \"Velocity\": 100.0,\n \"Lifetime\": 100,\n \"Average distance from SPB\": 8000,\n }\n ymax_scaling = {\n \"Run displacement\": 2000,\n \"Velocity\": 50,\n \"Lifetime\": 100,\n \"Average distance from SPB\": 10000,\n }\n if self.config[\"paperFigure\"] == 5:\n xmaxes[\"Velocity\"] = 60.0\n\n nStrain = len(self.strains)\n\n for fcn, xlab, ylab, unit, figname in graphhistvars:\n\n # Make a figure. Two axes (one for poleward, one for antipoleward)\n fig, ax = plt.subplots(figsize=(6, 3))\n cols1 = [cstrain.color for cstrain in self.strains]\n cols2 = [cstrain.color for cstrain in self.strains]\n # cols1 = [[68, 111, 200],[220, 95, 60]]\n # cols1 = [tuple(np.array(x)/255) for x in cols1]\n # cols2 = [[68, 111, 200],[220, 95, 60]]\n # cols2 = [tuple(np.array(x)/255) for x in cols2]\n\n # list for medians\n medians = {}\n\n original_stdout = (\n sys.stdout\n ) # Save a reference to the original standard output\n\n # Save to stats\n print(os.getcwd())\n with open(\"stats.txt\", \"a\") as f:\n sys.stdout = f # Change the standard output to the file we created.\n print(\"-\" * 30)\n print(\"\\nParameter = {0}\".format(xlab))\n sys.stdout = original_stdout # Reset the standard output to its original value # Display\n\n # Make histograms for each strain\n for strain, col1, col2 in zip(self.strains, cols1, cols2):\n # Get data\n funcData = getattr(strain, fcn)\n dataPAP = funcData()\n dataAll = np.hstack((-1 * np.array(dataPAP[0]), dataPAP[1]))\n\n # bins and histogram\n nbins = 16\n bins = np.linspace(-1 * xmaxes[xlab], xmaxes[xlab], nbins + 1)\n # ax.hist( dataAll, bins, density=True, edgecolor='k', alpha=0.6, color = col, label='{0} (N={1})'.format(strain.label, len(dataAll)))\n if self.config[\"paperFigure\"] == 7:\n print(\"Skip WT histograms for TD cell\")\n else:\n _, _, patches = ax.hist(\n dataAll,\n bins,\n density=True,\n edgecolor=\"white\",\n linewidth=1.0,\n alpha=0.6,\n color=col2,\n )\n for i in range(0, int(nbins / 2)):\n patches[i].set_facecolor(col1)\n patches[i].set_hatch(\"////\")\n\n # Draw y-axis in middle\n ax.axvline(x=0, c=\"black\", lw=1.5)\n\n # Add medians info\n medians[strain.label] = dict(\n zip(\n [\"P\", \"AP\"],\n [fac * np.median(db) for db, fac in zip(dataPAP, [-1, 1])],\n )\n )\n\n # ax.hist( [], bins, edgecolor='white', linewidth=1.0, alpha=0.6, color = col2, label='{0} (N={1})'.format(strain.label, len(dataAll)))\n ax.hist(\n [],\n bins,\n edgecolor=\"white\",\n linewidth=1.0,\n alpha=0.6,\n color=col2,\n label=\"{0}\".format(strain.label),\n )\n\n # Print Info\n # Save to stats\n with open(\"stats.txt\", \"a\") as f:\n sys.stdout = f # Change the standard output to the file we created.\n print(\"Strain: {0}\".format(strain.label))\n print(\"Poleward:\")\n print(\"\\tN = {0}\".format(len(dataPAP[0])))\n print(\"\\tMedian = {0:.3f} {1}\".format(np.median(dataPAP[0]), unit))\n print(\"\\tMean = {0:.3f} {1}\".format(np.mean(dataPAP[0]), unit))\n print(\n \"\\tStandard Dev = {0:.3f} {1}\".format(np.std(dataPAP[0]), unit)\n )\n print(\n \"\\tStandard Error = {0:.3f} {1}\".format(\n np.std(dataPAP[0]) / np.sqrt(len(dataPAP[0])), unit\n )\n )\n print(\"Antipoleward:\")\n print(\"\\tN = {0}\".format(len(dataPAP[1])))\n print(\"\\tMedian = {0:.3f} {1}\".format(np.median(dataPAP[1]), unit))\n print(\"\\tMean = {0:.3f} {1}\".format(np.mean(dataPAP[1]), unit))\n print(\n \"\\tStandard Dev = {0:.3f} {1}\".format(np.std(dataPAP[1]), unit)\n )\n print(\n \"\\tStandard Error = {0:.3f} {1}\".format(\n np.std(dataPAP[1]) / np.sqrt(len(dataPAP[1])), unit\n )\n )\n sys.stdout = original_stdout # Reset the standard output to its original value # Display\n\n print(\"-\" * 30)\n # Get max y value (ceiled to the nearest .01)\n ytop = 1.25 * max([pp.get_height() for pp in ax.patches])\n ymax = math.ceil(ytop * ymax_scaling[xlab]) / (ymax_scaling[xlab])\n ax.set_yticks([0, ymax / 2, ymax])\n ax.set(xlabel=\"{0} ({1})\".format(xlab, unit))\n # Limits and ticks\n ax.set_xlim(left=-1 * xmaxes[xlab], right=xmaxes[xlab])\n ax.set_ylim(bottom=0, top=1.0 * ymax)\n\n # Plot medians\n for strain_name, col in zip(medians.keys(), cols1):\n meds = medians[strain_name].values()\n for med in meds:\n ax = plot_median_special(ax, med, 0.9, col)\n\n # Legend\n if nStrain > 1 and xlab == \"Velocity\":\n ax.legend(frameon=False, loc=\"upper left\")\n # ax.legend(frameon=False)\n # Set ylabel\n ax.set(ylabel=\"Probability density\")\n\n # XLABELS\n if xlab == \"Lifetime\":\n ax.set_xticks([-100, -50, 0, 50, 100])\n ax.set_xticklabels(np.abs(ax.get_xticks()))\n elif xlab == \"Velocity\":\n if self.config[\"paperFigure\"] == 5:\n ax.set_xticks([-60, -30, 0, 30, 60])\n else:\n ax.set_xticks([-100, -50, 0, 50, 100])\n elif xlab == \"Average distance from SPB\":\n ax.set_xticks([-8000, -4000, 0, 4000, 8000])\n ax.ticklabel_format(\n style=\"sci\", axis=\"y\", scilimits=(0, 0), useMathText=True\n )\n ax.set_xticklabels(np.abs(ax.get_xticks()))\n\n elif xlab == \"Run displacement\":\n ax.set_xticks([-1600, -800, 0, 800, 1600])\n ax.ticklabel_format(\n style=\"sci\", axis=\"y\", scilimits=(0, 0), useMathText=True\n )\n\n plt.tight_layout()\n plt.savefig(figname)\n plt.close()\n\n # }}}\n\n # GraphStrain_SwitchFrequency2 {{{\n def GraphStrain_SwitchFrequency2(self, figname=\"graph_switch_frequency.pdf\"):\n # Graph comparison bar plot for events per minute\n\n strains = [strain.label for strain in self.strains]\n\n # Data\n n_events = np.zeros((len(self.strains), 2))\n dt = 0 * n_events\n\n for idx, strain in enumerate(self.strains):\n events, times = strain.GetSwitchFrequencyPerMinutePerCell()\n for je, jt in zip(events[\"P\"], times[\"P\"]):\n n_events[idx, 0] += je\n dt[idx, 0] += jt * 60\n for je, jt in zip(events[\"AP\"], times[\"AP\"]):\n n_events[idx, 1] += je\n dt[idx, 1] += jt * 60\n events_per_min = n_events / dt\n events_per_min_err = np.sqrt(n_events) / dt\n\n df = pd.DataFrame(\n {\"Poleward\": events_per_min[:, 0], \"AntiPoleward\": events_per_min[:, 1]},\n index=strains,\n )\n\n # Plot\n fig, ax = plt.subplots(figsize=(4, 3))\n ax = df.plot(\n kind=\"bar\",\n ax=ax,\n color=[\"Green\", \"Red\"],\n rot=0,\n yerr=events_per_min_err,\n error_kw=dict(ecolor=\"k\"),\n legend=False,\n )\n ax.set_ylabel(\"Switching frequency\\n(events/sec)\")\n ax.set_xlabel(\"\")\n\n num_cells = [0, 0]\n for idx in range(len(strains)):\n for kymo in self.strains[idx].kymographs:\n if kymo.poles != []:\n tt = kymo.poles[0].time[-1] - kymo.poles[0].time[0]\n if tt > 10:\n num_cells[idx] += 1\n\n original_stdout = sys.stdout # Save a reference to the original standard output\n with open(\"stats.txt\", \"a\") as f:\n sys.stdout = f # Change the standard output to the file we created.\n print(\"------------------------------\")\n print(\"\\nSwitching Frequency\\n\")\n for idx, strain in enumerate(strains):\n print(\"Strain: {0}\".format(strain))\n print(\" Num Cells: {0}\".format(num_cells[idx]))\n print(\" Poleward Exit\")\n print(\" N Events: {0}\".format(n_events[idx, 0]))\n print(\" Total Time: {0:.3f}\".format(dt[idx, 0]))\n print(\n \" Switching Freq: {0:.5f} sec^-1\".format(\n events_per_min[idx, 0]\n )\n )\n print(\n \" Error in switching freq: {0:.5f} sec^-1\".format(\n events_per_min_err[idx, 0]\n )\n )\n print(\" AntiPoleward\")\n print(\" N Events: {0}\".format(n_events[idx, 1]))\n print(\" Total Time: {0:.3f}\".format(dt[idx, 1]))\n print(\n \" Switching Freq: {0:.5f} sec^-1\".format(\n events_per_min[idx, 1]\n )\n )\n print(\n \" Error in switching freq: {0:.5f} sec^-1\".format(\n events_per_min_err[idx, 1]\n )\n )\n\n print(\"------------------------------\")\n sys.stdout = original_stdout # Reset the standard output to its original value # Display\n\n # Set y axis limit and ticks (ceil to nearest 0.02)\n try:\n if self.config[\"paperFigure\"] == 2:\n # ax.set_ylim(top=2.4)\n ax.set_ylim(top=0.024)\n elif self.config[\"paperFigure\"] == 3:\n # ax.set_ylim(top=5.0)\n ax.set_ylim(top=0.06)\n elif self.config[\"paperFigure\"] == 4:\n # ax.set_ylim(top=5.0)\n ax.set_ylim(top=0.06)\n elif self.config[\"paperFigure\"] == 5:\n # ax.set_ylim(top=2.4)\n ax.set_ylim(top=0.024)\n else:\n raise exception(\"unkown value for paperfigure parameter\")\n ymax = ax.get_ylim()[1]\n except:\n ymax = np.max((data[:, :2] + data[:, 2:]).flatten())\n # ymax = math.ceil(ax.get_ylim()[1]*50)/50\n ymax = math.ceil(ymax * 50) / 50\n ax.set_ylim(top=1.5 * ymax)\n ax.set_yticks([0, ymax / 2, ymax])\n ax.set_ylim(bottom=0.0)\n ax.set(xlabel=None)\n # Scientific notation\n ax.ticklabel_format(style=\"sci\", axis=\"y\", scilimits=(0, 0), useMathText=True)\n\n # Set custom patch colors (Poleward_strain1, Poleward_strain2, AntiP_streain1, AntiP_strain2)\n if len(self.strains) == 1:\n c1 = self.strains[0].color\n # c1 = [68, 111, 200]\n cols = [c1, c1]\n # cols = [tuple(np.array(x)/255) for x in cols]\n for idx, (pp, col) in enumerate(zip(ax.patches, cols)):\n pp.set_facecolor(col)\n pp.set_alpha(0.6)\n pp.set_edgecolor(\"white\")\n if idx < len(strains):\n pp.set_hatch(\"////\")\n\n cols = [c1, c1]\n cols = [tuple(np.array(x) / 255) for x in cols]\n labels = [\"Poleward\", \"Antipoleward\"]\n hatching = [\"////\", \"\"]\n handles = [\n matplotlib.patches.Rectangle(\n (0, 0),\n 1,\n 1,\n facecolor=cols[idx],\n alpha=0.6,\n label=labels[idx],\n hatch=hatching[idx],\n edgecolor=\"white\",\n )\n for idx in range(len(labels))\n ]\n\n elif len(self.strains) == 2:\n\n c1 = self.strains[0].color\n c2 = self.strains[1].color\n # c1 = [68, 111, 200]\n # c2 = [220, 95, 60]\n cols = [c1, c2, c1, c2]\n # cols = [tuple(np.array(x)/255) for x in cols]\n for idx, (pp, col) in enumerate(zip(ax.patches, cols)):\n pp.set_facecolor(col)\n pp.set_alpha(0.6)\n pp.set_edgecolor(\"white\")\n if idx < len(strains):\n pp.set_hatch(\"////\")\n\n cols = [c1, c1, c2, c2]\n # cols = [tuple(np.array(x)/255) for x in cols]\n labels = [\"Poleward\", \"Antipoleward\", \"Poleward\", \"Antipoleward\"]\n hatching = [\"////\", \"\", \"////\", \"\"]\n handles = [\n matplotlib.patches.Rectangle(\n (0, 0),\n 1,\n 1,\n facecolor=cols[idx],\n alpha=0.6,\n label=labels[idx],\n hatch=hatching[idx],\n edgecolor=\"white\",\n )\n for idx in range(len(labels))\n ]\n\n else:\n raise Exception(\"only coded for 1 or 2 strains\")\n\n # ax.legend(handles, labels, loc='upper left', frameon=False)\n ax.legend(\"\", frameon=False)\n plt.tight_layout()\n fig.savefig(figname)\n plt.close()\n\n # }}}\n\n # GraphStrain_EventsPerMinute2 {{{\n def GraphStrain_EventsPerMinute2(self, figname=\"graph_events_per_second.pdf\"):\n # Graph comparison bar plot for events per minute\n\n strains = [strain.label for strain in self.strains]\n\n # Data\n n_events = np.zeros((len(self.strains), 2))\n dt = 0 * n_events\n\n for idx, strain in enumerate(self.strains):\n events, times = strain.GetDirectionalEventsPerMinutePerCell()\n for je, jt in zip(events[\"P\"], times[\"P\"]):\n n_events[idx, 0] += je\n # convert times to seconds\n dt[idx, 0] += jt * 60\n for je, jt in zip(events[\"AP\"], times[\"AP\"]):\n n_events[idx, 1] += je\n dt[idx, 1] += jt * 60\n events_per_min = n_events / dt\n events_per_min_err = np.sqrt(n_events) / dt\n\n df = pd.DataFrame(\n {\"Poleward\": events_per_min[:, 0], \"AntiPoleward\": events_per_min[:, 1]},\n index=strains,\n )\n\n # Plot\n fig, ax = plt.subplots(figsize=(4, 3))\n ax = df.plot(\n kind=\"bar\",\n ax=ax,\n color=[\"Green\", \"Red\"],\n rot=0,\n yerr=events_per_min_err,\n error_kw=dict(ecolor=\"k\"),\n legend=False,\n )\n ax.set_ylabel(\"Directional events \\n per second\")\n ax.set_xlabel(\"\")\n\n num_cells = [0, 0]\n for idx in range(len(strains)):\n for kymo in self.strains[idx].kymographs:\n if kymo.poles != []:\n tt = kymo.poles[0].time[-1] - kymo.poles[0].time[0]\n if tt > 10:\n num_cells[idx] += 1\n\n original_stdout = sys.stdout # Save a reference to the original standard output\n with open(\"stats.txt\", \"a\") as f:\n sys.stdout = f # Change the standard output to the file we created.\n print(\"------------------------------\")\n print(\"\\nEvents per second\\n\")\n for idx, strain in enumerate(strains):\n print(\"Strain: {0}\".format(strain))\n print(\" Num Cells: {0}\".format(num_cells[idx]))\n print(\" Poleward\")\n print(\" N Events: {0}\".format(n_events[idx, 0]))\n print(\" Total Time: {0:.3f} sec\".format(dt[idx, 0]))\n print(\n \" Events per sec: {0:.5f} sec^-1\".format(\n events_per_min[idx, 0]\n )\n )\n print(\n \" Error in events per sec: {0:.5f} sec^-1\".format(\n events_per_min_err[idx, 0]\n )\n )\n print(\" AntiPoleward\")\n print(\" N Events: {0}\".format(n_events[idx, 1]))\n print(\" Total Time: {0:.3f} sec\".format(dt[idx, 1]))\n print(\n \" Events per sec: {0:.5f} sec^-1\".format(\n events_per_min[idx, 1]\n )\n )\n print(\n \" Error in events per sec: {0:.5f} sec^-1\".format(\n events_per_min_err[idx, 1]\n )\n )\n print(\"------------------------------\")\n sys.stdout = original_stdout # Reset the standard output to its original value # Display\n\n # Set y axis limit and ticks (ceil to nearest 0.02)\n try:\n if self.config[\"paperFigure\"] == 2:\n # ax.set_ylim(top=0.8)\n ax.set_ylim(top=0.014)\n elif self.config[\"paperFigure\"] == 3:\n # ax.set_ylim(top=1.8)\n ax.set_ylim(top=0.03)\n elif self.config[\"paperFigure\"] == 4:\n # ax.set_ylim(top=1.8)\n ax.set_ylim(top=0.03)\n elif self.config[\"paperFigure\"] == 5:\n # ax.set_ylim(top=0.8)\n ax.set_ylim(top=0.014)\n else:\n raise exception(\"unkown value for paperfigure parameter\")\n ymax = ax.get_ylim()[1]\n except:\n ymax = np.max((data[:, :2] + data[:, 2:]).flatten())\n # ymax = math.ceil(ax.get_ylim()[1]*50)/50\n ymax = math.ceil(ymax * 50) / 50\n ax.set_ylim(top=1.5 * ymax)\n\n ax.set_yticks([0, ymax / 2, ymax])\n ax.set_ylim(bottom=0.0)\n ax.set(xlabel=None)\n # Scientific notation\n ax.ticklabel_format(style=\"sci\", axis=\"y\", scilimits=(0, 0), useMathText=True)\n\n if len(self.strains) == 1:\n c1 = self.strains[0].color\n # c1 = [68, 111, 200]\n cols = [c1, c1]\n # cols = [tuple(np.array(x)/255) for x in cols]\n for idx, (pp, col) in enumerate(zip(ax.patches, cols)):\n pp.set_facecolor(col)\n pp.set_alpha(0.6)\n pp.set_edgecolor(\"white\")\n if idx < len(strains):\n pp.set_hatch(\"////\")\n\n cols = [c1, c1]\n cols = [tuple(np.array(x) / 255) for x in cols]\n labels = [\"Poleward\", \"Antipoleward\"]\n hatching = [\"////\", \"\"]\n handles = [\n matplotlib.patches.Rectangle(\n (0, 0),\n 1,\n 1,\n facecolor=cols[idx],\n alpha=0.6,\n label=labels[idx],\n hatch=hatching[idx],\n edgecolor=\"white\",\n )\n for idx in range(len(labels))\n ]\n\n elif len(self.strains) == 2:\n\n c1 = self.strains[0].color\n c2 = self.strains[1].color\n # c1 = [68, 111, 200]\n # c2 = [220, 95, 60]\n cols = [c1, c2, c1, c2]\n # cols = [tuple(np.array(x)/255) for x in cols]\n for idx, (pp, col) in enumerate(zip(ax.patches, cols)):\n pp.set_facecolor(col)\n pp.set_alpha(0.6)\n pp.set_edgecolor(\"white\")\n if idx < len(strains):\n pp.set_hatch(\"////\")\n\n cols = [c1, c1, c2, c2]\n # cols = [tuple(np.array(x)/255) for x in cols]\n labels = [\"Poleward\", \"Antipoleward\", \"Poleward\", \"Antipoleward\"]\n hatching = [\"////\", \"\", \"////\", \"\"]\n handles = [\n matplotlib.patches.Rectangle(\n (0, 0),\n 1,\n 1,\n facecolor=cols[idx],\n alpha=0.6,\n label=labels[idx],\n hatch=hatching[idx],\n edgecolor=\"white\",\n )\n for idx in range(len(labels))\n ]\n\n else:\n raise Exception(\"only coded for 1 or 2 strains\")\n\n ax.legend(handles, labels, loc=\"upper left\", frameon=False)\n plt.tight_layout()\n fig.savefig(figname)\n plt.close()\n\n # }}}\n\n # GraphStrain_FractionMovement {{{\n def GraphStrain_FractionMovement(self, figname=\"graph_fraction_kymo_movement.pdf\"):\n # Graph comparison bar plot for events per minute\n\n fracMove = [\n strain.GetFractionKymographsWithMovement() for strain in self.strains\n ]\n n_total = [len(strain.kymographs) for strain in self.strains]\n n_move = [int(jp * np) for jp, np in zip(fracMove, n_total)]\n strains = [strain.label for strain in self.strains]\n\n # Colors\n cols1 = [cstrain.color for cstrain in self.strains]\n\n num_cells = [0, 0]\n for idx in range(len(strains)):\n for kymo in self.strains[idx].kymographs:\n if kymo.poles != []:\n tt = kymo.poles[0].time[-1] - kymo.poles[0].time[0]\n if tt > 10:\n num_cells[idx] += 1\n\n original_stdout = sys.stdout # Save a reference to the original standard output\n with open(\"stats.txt\", \"a\") as f:\n sys.stdout = f # Change the standard output to the file we created.\n print(\"------------------------------\")\n print(\"\\nFraction kymograph movement\\n\\n\")\n for idx, strain in enumerate(strains):\n print(\" Strain: {0}\".format(strain))\n print(\" Percentage: {0:.3f}\".format(fracMove[idx]))\n print(\" N: {0}\\n\".format(num_cells[idx]))\n print(\"------------------------------\")\n sys.stdout = original_stdout # Reset the standard output to its original value # Display\n\n # Bar plot\n fig, ax = plt.subplots(figsize=(4, 3))\n ax.bar(strains, fracMove, color=cols1, width=0.5, alpha=0.6)\n # ax.set_xlabel(\"Strain\")\n ax.set_ylabel(\"Fraction of cells\\nwith movement\")\n ax.set_ylim(top=1.0)\n ax.set_yticks([0.0, 0.5, 1.0])\n ax.set_xlim(left=-0.75, right=len(strains) - 1 + 0.75)\n\n handles = [\n plt.Rectangle((0, 0), 1, 1, color=cols1[idx], alpha=0.6)\n for idx in range(len(strains))\n ]\n # plt.legend(handles, strains, loc='upper left', frameon=False)\n plt.tight_layout()\n fig.savefig(figname)\n plt.close()\n\n # }}}\n\n # GraphStrainMedianValues{{{\n def GraphStrainMedianValues(self, figname=\"graph_median_lifetime.pdf\"):\n # Graph comparison bar plot for median lifetime\n\n graphhistvars = (\n [\n \"GetRunLengths\",\n \"Run displacement\",\n r\"$\\mu$\" + \"m\",\n \"strain_median_runlength.pdf\",\n ],\n [\n \"GetVelocities_nm_per_sec\",\n \"Velocity\",\n \"nm/s\",\n \"strain_median_velocity.pdf\",\n ],\n [\"GetLifetimes_min\", \"Lifetime\", r\"min\", \"strain_median_lifetime.pdf\"],\n [\n \"GetAverageDistances\",\n \"Average distance from SPB\",\n r\"$\\mu$\" + \"m\",\n \"strain_median_avg_pos.pdf\",\n ],\n )\n\n for fcn, ylab, unit, figname in graphhistvars:\n # Data\n # Row: strains\n # Col: Poleward Mean, AntiPoleward Mean, Poleward STD, Antipoleward STD\n data = np.zeros((len(self.strains), 4))\n count = np.zeros(len(self.strains))\n for idx, strain in enumerate(self.strains):\n funcData = getattr(strain, fcn)\n events = funcData()\n count[idx] = len(strain.kymographs)\n data[idx, 0] = np.mean(events[0])\n data[idx, 2] = np.std(events[0]) / np.sqrt(count[idx])\n data[idx, 1] = np.mean(events[1])\n data[idx, 3] = np.std(events[1]) / np.sqrt(count[idx])\n\n strains = [strain.label for strain in self.strains]\n\n # Create pd Dataframe for plotting\n df = pd.DataFrame(\n data,\n columns=[\"Poleward\", \"Antipoleward\", \"std_P\", \"std_AP\"],\n index=strains,\n )\n\n # Plot\n fig, ax = plt.subplots(figsize=(4, 3))\n # convert the std columns to an array\n yerr = df[[\"std_P\", \"std_AP\"]].to_numpy().T\n ax = df[[\"Poleward\", \"Antipoleward\"]].plot(\n kind=\"bar\",\n ax=ax,\n color=[\"Green\", \"Red\"],\n rot=0,\n # yerr=yerr, error_kw=dict(ecolor='k'),legend=False, xlabel=None)\n legend=False,\n xlabel=None,\n )\n # ax.set_xlabel(\"Strain\")\n ax.set_ylabel(\"Median\\n{0}\\n({1})\".format(ylab, unit))\n\n # Set y axis limit and ticks (ceil to nearest 0.02)\n if ylab == \"Velocity\": # nearest 4\n ymax = np.max((data[:, :2] + data[:, 2:]).flatten())\n ymax = math.ceil(ymax / 4) * 4\n else:\n ymax = np.max((data[:, :2] + data[:, 2:]).flatten())\n # ymax = math.ceil(ax.get_ylim()[1]*50)/50\n ymax = math.ceil(ymax * 50) / 50\n ax.set_ylim(top=1.4 * ymax)\n ax.set_yticks([0, ymax / 2, ymax])\n # for jj in range(2):\n # ax.text(jj, ymax, 'N cells = {0}'.format(count[jj]),\n # ha='center', color='black', fontsize=8)\n\n # Set custom patch colors (Poleward_strain1, Poleward_strain2, AntiP_streain1, AntiP_strain2)\n if len(self.strains) == 1:\n c1 = self.strains[0].color\n # c1 = [68, 111, 200]\n cols = [c1, c1]\n # cols = [tuple(np.array(x)/255) for x in cols]\n for idx, (pp, col) in enumerate(zip(ax.patches, cols)):\n pp.set_facecolor(col)\n pp.set_alpha(0.6)\n pp.set_edgecolor(\"white\")\n if idx < len(strains):\n pp.set_hatch(\"////\")\n\n cols = [c1, c1]\n # cols = [tuple(np.array(x)/255) for x in cols]\n labels = [\"Poleward\", \"Antipoleward\"]\n hatching = [\"////\", \"\"]\n handles = [\n matplotlib.patches.Rectangle(\n (0, 0),\n 1,\n 1,\n facecolor=cols[idx],\n alpha=0.6,\n label=labels[idx],\n hatch=hatching[idx],\n edgecolor=\"white\",\n )\n for idx in range(len(labels))\n ]\n\n elif len(self.strains) == 2:\n\n c1 = self.strains[0].color\n c2 = self.strains[1].color\n # c1 = [68, 111, 200]\n # c2 = [220, 95, 60]\n cols = [c1, c2, c1, c2]\n # cols = [tuple(np.array(x)/255) for x in cols]\n for idx, (pp, col) in enumerate(zip(ax.patches, cols)):\n pp.set_facecolor(col)\n pp.set_alpha(0.6)\n pp.set_edgecolor(\"white\")\n if idx < len(strains):\n pp.set_hatch(\"////\")\n\n cols = [c1, c1, c2, c2]\n # cols = [tuple(np.array(x)/255) for x in cols]\n labels = [\n \"Poleward, {0}\".format(strains[0]),\n \"Antipoleward, {0}\".format(strains[0]),\n \"Poleward, {0}\".format(strains[1]),\n \"Antipoleward, {0}\".format(strains[1]),\n ]\n hatching = [\"////\", \"\", \"////\", \"\"]\n handles = [\n matplotlib.patches.Rectangle(\n (0, 0),\n 1,\n 1,\n facecolor=cols[idx],\n alpha=0.6,\n label=labels[idx],\n hatch=hatching[idx],\n edgecolor=\"white\",\n )\n for idx in range(len(labels))\n ]\n\n else:\n raise Exception(\"only coded for 1 or 2 strains\")\n\n ax.legend(handles, labels, loc=\"upper left\", frameon=False)\n plt.tight_layout()\n fig.savefig(figname)\n plt.close()\n\n # }}}\n\n # GraphStrain_AvgStartEnd {{{\n def GraphStrain_AvgStartEnd(self, figname=\"graph_fraction_kymo_movement.pdf\"):\n\n freqP = [strain.GetFractionKymographsWithMovement() for strain in self.strains]\n\n strains = [strain.label for strain in self.strains]\n # Create pd Dataframe for plotting\n seriesP = pd.Series(freqP, index=strains)\n\n # Plot\n fig, ax = plt.subplots(figsize=(6, 4))\n\n df = pd.DataFrame({\"Movements\": seriesP})\n df.plot.bar(ax=ax, color=[\"RebeccaPurple\"], rot=0)\n ax.set_xlabel(\"Strain\")\n ax.set_ylabel(\"Fraction of Cells\\nwith Movement\")\n\n plt.tight_layout()\n fig.savefig(figname)\n plt.close()\n\n # }}}\n\n # GraphStrainScatter {{{\n def GraphStrainScatter(\n self,\n strains,\n x,\n y,\n xlab=None,\n ylab=None,\n xunit=\"\",\n yunit=\"\",\n figname=\"scatter.pdf\",\n ):\n\n # Special x limits\n xmaxes = {\n \"Run displacement\": 1600,\n \"Velocity\": 60.0,\n \"Lifetime\": 80,\n \"Intensity\": 1000,\n }\n\n # 2 axes. Poleward and antipoleward\n fig, axs = plt.subplots(1, 2, figsize=(6, 3), sharey=True)\n cols = sns.color_palette(\"husl\", len(strains))\n directions = [\"Poleward\", \"Antipoleward\"]\n\n for strain, c in zip(strains, cols):\n if x == \"Intensity\":\n xx = strain.GetIntensities()\n elif x == \"Run displacement\":\n xx = strain.GetRunLengths()\n elif x == \"Velocity\":\n xx = strain.GetVelocities()\n elif x == \"Lifetime\":\n xx = strain.GetLifetimes()\n # elif x == \"Average distance from SPB\":\n # xx = strain.GetAverageDistances()\n if y == \"Intensity\":\n yy = strain.GetIntensities()\n elif y == \"Run displacement\":\n yy = strain.GetRunLengths()\n elif y == \"Velocity\":\n yy = strain.GetVelocities()\n elif y == \"Lifetime\":\n yy = strain.GetLifetimes()\n # elif y == \"Average distance from SPB\":\n # yy = strain.GetAverageDistances()\n\n for idx, ax in enumerate(axs):\n ax.scatter(\n xx[idx],\n yy[idx],\n s=12,\n alpha=0.8,\n color=c,\n edgecolors=\"none\",\n label=strain.label,\n )\n ax.set_title(directions[idx])\n # ax.grid(True)\n\n if xlab is not None:\n axs[0].set_xlabel(\"{0} ({1})\".format(xlab, xunit))\n axs[1].set_xlabel(\"{0} ({1})\".format(xlab, xunit))\n if ylab is not None:\n axs[0].set_ylabel(\"{0} ({1})\".format(ylab, yunit))\n for ax in axs:\n ax.legend()\n ax.set_xlim(left=0, right=xmaxes[x])\n ax.set_ylim(bottom=0, top=xmaxes[y])\n\n plt.tight_layout()\n plt.savefig(\"scatter_{0}_{1}.pdf\".format(x, y))\n plt.close()\n\n # }}}\n\n # GraphSpindleIntensity {{{\n def GraphSpindleIntensity(self, strains, lrange=[1, 10], gname=None):\n # Graph spindle intensity between poles\n\n intStrain = np.zeros((len(strains), 100))\n cols = sns.color_palette(\"husl\", len(strains))\n xran = np.linspace(0, 1, 100)\n for k, strain in enumerate(strains):\n\n fig, ax = plt.subplots(figsize=(9, 6))\n # Find spindle intensities for all kymographs\n intensities = None\n for i, kymo in enumerate(strain.kymographs):\n intense = kymo.FindIntensityAlongSpindle(lrange=lrange)\n if intense is not None:\n if intensities is None:\n intensities = np.mean(intense, axis=0)\n else:\n intensities = np.vstack((intensities, np.mean(intense, axis=0)))\n\n try:\n intStrain[k, :] = np.mean(intensities, axis=0)\n except:\n pdb.set_trace()\n print(\"1\")\n # Plot\n for row in intensities:\n ax.plot(xran, row, color=\"blue\")\n ax.plot(xran, np.mean(intensities, axis=0), color=\"red\", linewidth=4)\n ax.set_ylabel(\"Intensity (AU)\")\n ax.set_xlabel(\"Position along spindle (normalized)\")\n ax.set_title(\"Cut7 intensity - {0}\".format(strain.label))\n fig.savefig(\"spindle_intensity_{0}.pdf\".format(strain.label))\n plt.close()\n\n # Make a comparison figure\n fig, ax = plt.subplots(figsize=(9, 6))\n for strn, row, c in zip(strains, intStrain, cols):\n ax.plot(xran, row, color=c, linewidth=4, label=strn.label)\n ax.set_ylabel(\"Intensity (AU)\")\n ax.set_xlabel(\"Position along spindle (normalized)\")\n ax.set_title(\"Cut7 intensity\")\n ax.legend()\n figname = \"spindle_intensity_all.pdf\"\n if gname is not None:\n figname = figname[:-4] + \"_{0}.pdf\".format(gname)\n fig.suptitle(gname)\n fig.savefig(figname)\n plt.close()\n\n # }}}\n\n # PlotTracksByState {{{\n def PlotTracksByState(self, k=5):\n # Plot individual curved tracks with poles\n\n # Plot all tracks overlayed without poles\n cols = {\n \"Inactive\": \"blue\",\n \"Poleward\": \"green\",\n \"Antipoleward\": \"red\",\n }\n\n for strain in self.strains:\n strain.PlotTrackByStates(cols, k=k)\n\n # }}}\n\n # PlotAllTracks {{{\n def PlotAllTracks(self):\n # Plot all tracks\n\n cols = {\n \"Inactive\": \"blue\",\n \"Poleward\": \"green\",\n \"Antipoleward\": \"red\",\n }\n\n for strain in self.strains:\n strain.PlotAllTracks(cols)\n\n # }}}\n\n # DisplayTracksStatistics {{{\n def DisplayTracksStatistics(self):\n # Display statistics about the tracks\n\n print(\"------------------------------------------\")\n print(\"------------------------------------------\")\n print(\"------------ Track Statistics ------------\")\n print(\"------------------------------------------\\n\")\n print(\"Number of tracks:\")\n for strain in self.strains:\n print(\" {0} : {1}\\n\".format(strain.label, len(strain.tracks)))\n\n print(\"------------------------------------------\")\n print(\"------------------------------------------\")\n\n # }}}\n\n\ndef weighted_avg_and_std(values, weights):\n \"\"\"\n Return the weighted average and standard deviation.\n\n values, weights -- Numpy ndarrays with the same shape.\n \"\"\"\n average = np.average(values, weights=weights)\n # Fast and numerically precise:\n variance = np.average((values - average) ** 2, weights=weights)\n std = np.sqrt(variance)\n serr = std / np.sqrt(len(values))\n return average, std, serr\n\n\n#########################################################\nif __name__ == \"__main__\":\n x = KymographAnalysis()\n" }, { "alpha_fraction": 0.5322422385215759, "alphanum_fraction": 0.542725682258606, "avg_line_length": 35.226776123046875, "blob_id": "6c807652f4b019c3b4b68f58ff9e9d65bad28dc3", "content_id": "a418850562f555700626effa2677a81dfbd02fb7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13259, "license_type": "permissive", "max_line_length": 167, "num_lines": 366, "path": "/src/Track.py", "repo_name": "saadjansari/KymoAnalysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os, pdb\nimport numpy as np\nfrom scipy import interpolate, signal\nfrom .node_graph import Graph\nimport matplotlib.pyplot as plt\nimport math\nimport uuid\n\n# Superclass for Poles and tracks that stores positional and intensity information\nclass Feature:\n def __init__(self, time, position, image, time_step=1):\n self.time = np.array( time )\n self.position = np.array( position )\n self.id = uuid.uuid1()\n self.time_step = time_step\n self.pixel_time = self.time / self.time_step\n self.image = image\n\n # Resample data\n self.ResampleData()\n\n def ResampleData( self, sample_factor=3):\n # resample data based on time pixels\n\n # Define an interpolation function for positions\n ifunc_pos = interpolate.interp1d( self.time, self.position, kind='linear')\n\n # Define a grid of resampled time points \n self.time = np.linspace( self.time[0], self.time[-1], int( np.floor(max([ 2, sample_factor*(self.time[-1]-self.time[0])])) ))\n if len(self.time) == 1:\n pdb.set_trace()\n print('oops')\n self.position = ifunc_pos( self.time) \n\n# Class for a Pole\nclass Pole(Feature):\n def __init__(self, time, position, image=[], time_step=1):\n Feature.__init__(self, time, position, image, time_step=time_step)\n\n # Define an interpolation/extrapolation function\n # self.ifunc = interpolate.interp1d(self.time, self.position, kind='linear', fill_value='extrapolate')\n self.ifunc = interpolate.interp1d(self.time, self.position, kind='linear', fill_value=(self.position[0], self.position[-1]), bounds_error=False)\n\n def Print(self):\n print('Pole :')\n print(' ID : {}'.format(self.id))\n print(' Time : {}'.format( self.time))\n print(' Position : {}'.format( self.position))\n print('--------------------------------- ')\n\n def TrimBasedOnTime(self, time_keep):\n # Trim the pole to be inside the time range specified\n \n if np.all(time_keep == -1):\n return np.nan\n\n # Check if track exists between those times\n start_before = (self.time[0] < time_keep[0])\n start_after = (self.time[0] > time_keep[1])\n end_before = (self.time[-1] < time_keep[0])\n end_after = (self.time[-1] > time_keep[1])\n if start_before and end_before:\n return np.nan\n elif start_after and end_after:\n return np.nan\n\n # Get indices of times \n idx = np.argwhere( (self.time > time_keep[0]) & (self.time < time_keep[1]) ).T[0].tolist()\n if len(idx) < 3:\n return None \n idx = range( idx[0], idx[-1]+1) \n\n # Create the new trimmed pole \n polenew = Pole( self.time[idx], self.position[idx], self.image, time_step=self.time_step)\n # print(time_keep)\n # print(polenew.time[0])\n # print(polenew.time[-1])\n return polenew\n\n# Class for a Track: additionally stores associated poles and track direction\nclass Track(Feature):\n def __init__(self, time, position, image, poles, direction, line_type, time_step=1, pos_step=1, kymo_file=None):\n Feature.__init__(self, time, position, image, time_step=time_step)\n\n self.poles = poles\n self.direction = direction\n self.line_type = line_type\n self.pos_step = pos_step\n self.kymo_file = kymo_file\n\n def CalcPositionPoleCurrent(self):\n # Get pole position at the current time (i.e at the times of the track) by using the interpolation/extrapolation function of the pole\n pos = np.zeros( (len(self.poles), np.size(self.position) ) )\n for idx, pole in enumerate( self.poles) :\n pos[idx,:] = np.array( pole.ifunc( self.time) )\n return pos \n\n def CalcPositionRelative(self):\n # Calculate track position relative to the pole \n\n pole = self.CalcPositionPoleCurrent()\n pos = np.zeros( np.shape(pole) )\n for idx, ele in enumerate( pole):\n pos[idx,:] = np.abs( np.array( self.position - ele) )\n return pos\n\n def CalcVelocity(self):\n # Calculate the velocity of this linear track\n \n pos = self.CalcPositionRelative()\n # Find Velocity\n vel = np.zeros( (len(self.poles)) )\n for idx in range( len(self.poles)):\n vel[idx] = np.average( np.absolute( np.divide( np.diff( pos[idx,:]) , np.diff( self.time) ) ), weights = np.diff(self.time) )\n\n return vel\n\n def CalcSpindleLength(self):\n # Calculate the spindle length\n\n if len(self.poles) != 2: \n return\n # Find the distance between the poles for the extent of this track\n leng = np.absolute( self.poles[0].ifunc( self.time) - self.poles[1].ifunc( self.time) )\n return leng\n\n def CalcIntensity( self):\n # Interpolate to find the mean intensity of the track\n\n dimT = np.shape( self.image)[0]\n dimX = np.shape( self.image)[1]\n f = interpolate.interp2d( self.pos_step*np.arange(0,dimX), self.time_step*np.arange(0,dimT), self.image)\n intense = f(self.position, self.time)\n return np.mean(intense)\n\n def CheckViability(self):\n # Check track time is always increasing\n if np.any( np.diff( self.time) <= 0 ):\n return 0 \n return 1 \n\n def OrderPoles(self):\n # Order the poles with the first one being the closest one to the start of the track\n if len(self.poles) != 2:\n return\n\n pos = self.CalcPositionRelative()\n if np.absolute( pos[1,0] ) < np.absolute( pos[0,0]):\n self.poles = [self.poles[1], self.poles[0]]\n\n def Trim(self, lrange):\n # Trim the track to be inside the range specified\n \n if len( self.poles) == 1:\n return self\n if lrange is None:\n return self\n\n # Get indices of times when spindle length is between the given range values\n lens = self.CalcSpindleLength()\n idx = np.argwhere( (lens > lrange[0]) & (lens < lrange[1]) ).T[0].tolist()\n if len(idx) < 3:\n return None \n idx = range( idx[0], idx[-1]+1) \n\n # Create the new trimmed track\n tracknew = Track( self.time[idx], self.position[idx], self.image, self.poles, self.direction, self.line_type, time_step=self.time_step, pos_step=self.pos_step)\n return tracknew\n\n def TrimBasedOnTime(self, time_keep):\n # Trim the track to be inside the time range specified\n \n if np.all(time_keep == -1):\n return np.nan\n\n # Check if track exists between those times\n start_before = (self.time[0] < time_keep[0])\n start_after = (self.time[0] > time_keep[1])\n end_before = (self.time[-1] < time_keep[0])\n end_after = (self.time[-1] > time_keep[1])\n if start_before and end_before:\n return np.nan\n elif start_after and end_after:\n return np.nan\n\n # Get indices of times \n idx = np.argwhere( (self.time > time_keep[0]) & (self.time < time_keep[1]) ).T[0].tolist()\n if len(idx) < 3:\n return None \n idx = range( idx[0], idx[-1]+1) \n\n # Create the new trimmed track\n tracknew = Track( self.time[idx], self.position[idx], self.image, self.poles, self.direction, self.line_type, time_step=self.time_step, pos_step=self.pos_step)\n if tracknew is None:\n pdb.set_trace()\n print('b')\n return tracknew\n\n def SplitTrack(self, ipole=0, cutoff=0.003):\n # Spit curved track into multiple mini unidirectional segments \n # cutoff : units micron/sec\n\n switches = {\n 'P' : { 'P' : 0, 'AP': 0, 'I' : 0,},\n 'AP' : { 'P' : 0, 'AP': 0, 'I' : 0,},\n 'I' : { 'P' : 0, 'AP': 0, 'I' : 0,},\n }\n\n # If linear directional track, cant split, so exit\n if self.direction != 'Ambiguous':\n return [self], switches\n\n # If linear ambiguous track, figure out direction, then exit \n if self.line_type == 'Line' and self.direction == 'Ambiguous':\n if len(self.CalcPositionRelative()) == 0:\n pdb.set_trace()\n print('a')\n position = np.absolute( self.CalcPositionRelative()[ipole,:] )\n vel = np.mean( np.divide( np.diff( position) , np.diff(self.time) ) )\n if abs( vel) < cutoff:\n self.direction = 'Inactive'\n elif vel > 0:\n self.direction = 'Antipoleward'\n elif vel < 0:\n self.direction = 'Poleward'\n return [self], switches\n\n # Get track position relative to the pole\n position = np.absolute( self.CalcPositionRelative()[ipole,:] )\n\n # Use a rolling window to find velocities\n vel = FindGradientRollingWindow( position, self.time, window=16)\n\n # Assign states based on value of velocity at each timestep\n states = []\n for v in vel:\n if abs( v) < cutoff:\n states += ['I']\n elif v > 0:\n states += ['AP']\n elif v < 0:\n states += ['P']\n # set first state to second state. last state to second last state\n states[0] = states[1]\n states[-1] = states[-2]\n # Remove singly occuring states\n for i, state in enumerate(states):\n if i>0 and i< len(states)-1:\n if state != states[i-1] and state != states[i+1]:\n states[i] = states[i-1]\n\n # Count switches and get track indices\n p_state = 'XXX' \n track = { 'pos': [], 'time': [], 'dir':[] }\n idx = [0 , 0]\n for cnt, st in enumerate(states):\n \n if cnt == 0:\n p_state = st\n idx[0] = 0\n continue\n\n if st == p_state:\n idx[1] += 1 \n \n if st != p_state:\n\n # store old stuff\n pos = self.position[ idx[0]: idx[1]+2]\n # pos.tolist()\n time = self.time[ idx[0]: idx[1]+2]\n # time.tolist()\n track['pos'] += [pos]\n track['time'] += [time]\n track['dir'] += [p_state]\n p_state = st\n\n # begin new\n idx[0] = cnt\n idx[1] = cnt\n\n # Store the last info\n if cnt == len(states)-1:\n\n pos = self.position[ idx[0]: idx[1]+1]\n # pos.tolist()\n time = self.time[ idx[0]: idx[1]+1]\n # time.tolist()\n track['pos'] += [pos]\n track['time'] += [time]\n track['dir'] += [p_state]\n\n # record switches\n for cnt, dd in enumerate( track['dir']):\n if cnt == 0:\n continue\n switches[ track['dir'][cnt-1]][track['dir'][cnt]] += 1\n \n # Create track objects from the information\n segments = []\n for time, pos, direc in zip( track['time'], track['pos'], track['dir']):\n if direc is 'P':\n direction = 'Poleward'\n elif direc is 'AP':\n direction = 'Antipoleward'\n elif direc is 'I':\n direction = 'Inactive'\n pos = pos.tolist()\n time = time.tolist()\n segments += [Track( time, pos, self.image, self.poles, direction, 'Line', time_step=self.time_step, pos_step=self.pos_step, kymo_file=self.kymo_file)]\n \n return segments, switches\n\n def DisplayTrack(self, ax=None):\n\n if ax is None:\n fig, ax = plt.subplots(figsize=(6,6))\n\n # Display kymograph image\n ax.imshow( self.image)\n ax.plot( self.position/self.pos_step, self.time/self.time_step, color='red')\n\n def Print(self):\n print('Feature :')\n print(' ID : {}'.format(self.id))\n print(' Direction : {}'.format( self.direction))\n print(' Line type : {}'.format( self.line_type))\n print(' Time : {}'.format( self.time))\n print(' Position : {}'.format( self.position))\n print('--------------------------------- ')\n\ndef CountSwitches( states, switches):\n # Given a list of \n\n dt = np.mean( np.diff( t) ) \n nHalfWindow = int( np.ceil( t_window / (2*dt)) )\n\n for i in range(len(t)):\n # get upper lower indices of window\n i_lb = max( [ 0, i-nHalfWindow])\n i_ub = min( [ len(t), i+nHalfWindow])\n\n # Find gradient\n diff = lambda xx : np.diff( xx[i_lb:i_ub])\n grad = np.mean( np.divide( diff(x), diff(t) ) )\n return grad \n\ndef FindGradientRollingWindow( x, t, window=6):\n\n dt = np.mean( np.diff( t) ) \n nHalfWindow = int( np.ceil( window / (2*dt)) )\n grads = []\n for i in range(len(t)):\n # get upper lower indices of window\n i_lb = max( [ 0, i-nHalfWindow])\n i_ub = min( [ len(t), i+nHalfWindow])\n\n # Find gradient\n diff = lambda xx : np.diff( xx[i_lb:i_ub])\n grads += [np.mean( np.divide( diff(x), diff(t) ) )]\n return grads\n\nif __name__ == \"__main__\":\n print('Not implemented')\n" }, { "alpha_fraction": 0.4977225661277771, "alphanum_fraction": 0.5043478012084961, "avg_line_length": 24.11458396911621, "blob_id": "0ee156ddda79f36bc308df18708a95f319a9b1ed", "content_id": "f06423def7493546a795a0d8f2d20f8caf193955", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2415, "license_type": "permissive", "max_line_length": 62, "num_lines": 96, "path": "/src/node_graph.py", "repo_name": "saadjansari/KymoAnalysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# Python program to print connected \n# components in an undirected graph \n\n# This code is contributed by Abhishek Valsan\n# Updated by Saad Ansari for a directed graph application\n\nimport pdb\n\nclass Graph: \n \n # init function to declare class variables \n def __init__(self,V): \n self.V = V \n self.next = [[] for i in range(V)] \n self.prev = [[] for i in range(V)] \n \n def VisitNext(self, temp, v, visited): \n \n # Visited this node\n visited[v] = True\n\n # Store the vertex to list \n try:\n if temp[-1] != v:\n temp.append(v) \n except:\n temp.append(v) \n \n # Repeat for all vertices adjacent \n # to this vertex v \n for i in self.next[v]: \n if visited[i] == False: \n \n # Update the list \n temp= self.VisitNext(temp, i, visited) \n\n return temp\n \n def VisitPrev(self, temp, v, visited): \n \n # Visited this node\n visited[v] = True\n\n # Store the vertex to list \n try:\n if temp[0] != v:\n temp.insert(0, v) \n except:\n temp.insert(0, v) \n \n # Repeat for all vertices adjacent \n # to this vertex v \n for i in self.prev[v]: \n if visited[i] == False: \n \n # Update the list \n temp= self.VisitPrev(temp, i, visited) \n\n return temp\n\n # method to add an directed edge \n def addEdge(self, v, w): \n self.next[v].append(w) \n self.prev[w].append(v) \n \n # Method to retrieve connected components \n # in a directed graph \n def connectedComponents(self): \n visited = [] \n cc = [] \n for i in range(self.V): \n visited.append(False) \n for v in range(self.V): \n if visited[v] == False: \n\n temp = [] \n temp= self.VisitNext( temp, v, visited) \n cc.append( self.VisitPrev( temp, v, visited) )\n\n return cc \n \n# Driver Code \nif __name__==\"__main__\": \n \n # Create a graph given in the above diagram \n # 5 vertices numbered from 0 to 4 \n g = Graph(7); \n g.addEdge(1, 0) \n g.addEdge(3, 4) \n g.addEdge(0, 6) \n g.addEdge(5, 1) \n cc = g.connectedComponents() \n print(\"Following are connected components\") \n print(cc) \n \n" }, { "alpha_fraction": 0.5247725248336792, "alphanum_fraction": 0.5293225646018982, "avg_line_length": 29.766536712646484, "blob_id": "3647bcb60d9741224fcd279ca946a8313e10d07c", "content_id": "851fe83824dfe9774de6341b3a633edf3fd56175", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7912, "license_type": "permissive", "max_line_length": 141, "num_lines": 257, "path": "/src/ReadFiles.py", "repo_name": "saadjansari/KymoAnalysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os, pdb\nimport math\nimport numpy as np\nfrom .Track import *\nimport matplotlib.pyplot as plt\n\ndef ReadTxt( fname, verbose=0):\n # Read data from files and parse into general, poles and feature information\n\n if verbose:\n PrintFile( fname)\n\n # Initialize lists\n geninfo = []\n polesinfo = []\n featureinfo = []\n\n # Add General Information\n with open(fname) as fp:\n \n addLine = None \n for cnt, line in enumerate(fp):\n \n if line.find( 'General Information') > -1:\n addLine = 'G' \n if line.find( 'Poles Information') > -1:\n addLine = 'P' \n if line.find( 'Feature Information') > -1:\n addLine = 'F' \n\n # Add General Information\n if addLine == 'G':\n geninfo.append( line)\n\n # Add Poles Information\n elif addLine == 'P':\n polesinfo.append( line)\n\n # Add Feature Information\n elif addLine == 'F':\n featureinfo.append( line)\n \n # Parse information\n general = ParseGeneralInfo( fname, geninfo)\n poles = ParsePolesInfo( polesinfo, general)\n tracks = ParseTracksInfo( featureinfo, poles, general)\n if polesinfo == []:\n pdb.set_trace()\n hi = 1\n\n return general, poles, tracks\n\ndef ParseGeneralInfo( fname, geninfo):\n # Parse information about general information\n \n general = {\n 'path_tiff' : [],\n 'type' : [],\n 'time_start' : [],\n 'time_end' : [],\n 'time_step' : [],\n 'n_poles' : [],\n 'n_tracks': [],\n 'image': [],\n }\n\n\n for line in geninfo:\n\n # Tiff Path\n path_tiff = FindSingleSubstring( line, 'Tiff path : ') \n if path_tiff is not None:\n general['path_tiff'] = path_tiff\n # Spindle Type\n typ = FindSingleSubstring( line, 'Spindle type : ') \n if typ is not None:\n general['type'] = typ \n # Time Start \n time_start = FindNumbers( line, 'Start time (s) : ') \n if time_start is not None:\n general['time_start'] = time_start \n # Time End \n time_end = FindNumbers( line, 'End time (s) : ') \n if time_end is not None:\n general['time_end'] = time_end \n # Time Step \n time_step = FindNumbers( line, 'Time step (s) : ') \n if time_step is not None:\n general['time_step'] = time_step[0]\n # Num Poles \n npoles = FindNumbers( line, 'Num poles : ') \n if npoles is not None:\n general['n_poles'] = int( npoles[0]) \n # Num Tracks \n ntracks = FindNumbers( line, 'Num tracks : ') \n if ntracks is not None:\n general['n_tracks'] = int( ntracks[0])\n\n general['image'] = LoadTiff( fname[:-9]+'.tif')\n return general \n\ndef ParsePolesInfo( polesinfo, general):\n # Parse information about poles \n\n if not polesinfo or len(polesinfo) == 0:\n print('No poles information here')\n return\n\n # Determine number of poles and split information\n polelist = []\n idxPole = None\n nPoles = 0\n for line in polesinfo:\n\n # Look for the next pole\n if line.find( 'Pole number : {}'.format( nPoles+1)) > -1:\n nPoles += 1 \n if nPoles == 0:\n continue\n\n if nPoles != len(polelist):\n polelist += [[line]]\n else:\n polelist[ nPoles-1] += [line]\n\n # print('Found {} poles'.format( nPoles) )\n\n # for each split pole, get useful information and initialize a Pole object\n poles = []\n for pole in polelist:\n\n for line in pole:\n\n # Time pixels\n if FindNumbers( line, 'Time pixel : ') is not None:\n time = FindNumbers( line, 'Time pixel : ')\n time = [x * general['time_step'] for x in time]\n\n # # Times \n # if FindNumbers( line, 'Time (s) : ') is not None:\n # time = FindNumbers( line, 'Time (s) : ') \n \n # Position \n if FindNumbers( line, 'Position (um) : ') is not None:\n position = FindNumbers( line, 'Position (um) : ') \n\n # Intensity \n if FindNumbers( line, 'Intensity : ') is not None:\n intensity = FindNumbers( line, 'Intensity : ') \n \n poles += [Pole( time, position, general['image'], time_step=general['time_step']) ]\n\n return poles\n\n\ndef ParseTracksInfo( featureinfo, poles, general):\n # Parse information about tracks \n\n if not featureinfo or len(featureinfo) == 0:\n print('No tracks information here')\n return\n\n # Determine number of tracks and split information\n tracklist = []\n idxTrack = None\n nTracks = 0\n for line in featureinfo:\n\n # Look for the next track \n if line.find( 'Feature number : {}'.format( nTracks+1)) > -1:\n nTracks += 1 \n if nTracks == 0:\n continue\n\n if nTracks != len(tracklist):\n tracklist += [[line]]\n else:\n tracklist[ nTracks-1] += [line]\n\n # print('Found {} tracks'.format( nTracks) )\n\n # for each split track, get useful information and initialize a Track object\n tracks = []\n for trck in tracklist:\n\n for line in trck:\n\n # Time pixels\n if FindNumbers( line, 'Time pixel : ') is not None:\n time = FindNumbers( line, 'Time pixel : ')\n timePix = time\n time = [x * general['time_step'] for x in time]\n\n # # Time \n # if FindNumbers( line, 'Time (s) : ') is not None:\n # time = FindNumbers( line, 'Time (s) : ') \n \n # Position \n if FindNumbers( line, 'Position pixel : ') is not None:\n positionPix = FindNumbers( line, 'Position pixel : ') \n\n # Position \n if FindNumbers( line, 'Position (um) : ') is not None:\n position = FindNumbers( line, 'Position (um) : ') \n\n # Intensity \n if FindNumbers( line, 'Intensity : ') is not None:\n intensity = FindNumbers( line, 'Intensity : ') \n \n # Direction\n if FindSingleSubstring( line, 'Feature direction : ') is not None:\n direction = FindSingleSubstring( line, 'Feature direction : ') \n direction = direction[0:-1]\n\n # Line type \n if FindSingleSubstring( line, 'Feature type : ') is not None:\n line_type = FindSingleSubstring( line, 'Feature type : ') \n line_type = line_type[0:-1]\n\n tracks += [Track( time, position, general['image'], poles, 'Ambiguous', line_type, time_step=general['time_step'], pos_step=0.1067) ]\n return tracks\n\ndef LoadTiff( fname):\n # load tiff file\n arr = plt.imread( fname)\n if len( arr.shape) == 3:\n arr = np.mean(arr,axis=2)\n return arr\n\ndef FindSingleSubstring(strSearch, strLabel):\n # Find a single substring that contains strLabel. We delete the strLabel. \n \n if strSearch.find( strLabel) > -1:\n strMatch = strSearch.replace( strLabel, '')\n return strMatch\n return None\n\ndef FindNumbers(strSearch, strLabel):\n # Find numbers from a string that starts with strLabel\n \n if strSearch.find( strLabel) > -1:\n strMatch = strSearch.replace( strLabel, '')\n strList = strMatch.split(',')\n nums = [float(i) for i in strList]\n return nums \n return None\n\ndef PrintFile(fname):\n # Print all the information from a file to screen \n with open( fname) as f:\n print( f.read() )\n\n##########################################\nif __name__ == \"__main__\":\n print(\"no default implementation\")\n \n" }, { "alpha_fraction": 0.4936632513999939, "alphanum_fraction": 0.4954737424850464, "avg_line_length": 29.675926208496094, "blob_id": "6192c5a8102b87fa39b46d337c167b35df403cb0", "content_id": "64c96adc5bca66b494b6ea8dfab79bba222a59f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3314, "license_type": "permissive", "max_line_length": 151, "num_lines": 108, "path": "/src/Load.py", "repo_name": "saadjansari/KymoAnalysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os, pdb\nimport yaml\nimport glob\n\n'''\nName: Load.py\nDescription: loads and splits the tracks saved by the trackBuilder (kyman.mlapp) into general, poles and feature sections to be parsed by Kymograph.py \n'''\n\n\n# Class to load data from files \nclass Load:\n def __init__(self, verbose=0):\n\n file_name = 'track_files.yaml'\n\n with open(file_name) as infile:\n self.data = yaml.load(infile)\n\n self.verbose = verbose \n\n self.GetFilenames()\n self.ReadFromFiles()\n\n def GetFilenames(self):\n # Expand filenames in the case of special characters\n\n for strain, dat in self.data['strain'].items():\n for idx,fpath in enumerate( dat['path']):\n files = []\n for fname in dat['files'][idx]:\n \n temp = glob.glob( os.path.join(fpath,fname) ) \n for fil in temp:\n head_tail = os.path.split(fil)\n files += [ head_tail[1] ]\n self.data['strain'][strain]['files'][idx] = files\n \n def ReadFromFiles(self):\n # Read information from all files given yaml data \n \n for strain, dat in self.data['strain'].items():\n for idx,fpath in enumerate( dat['path']):\n\n self.data['strain'][strain]['geninfo'] = []\n self.data['strain'][strain]['polesinfo'] = []\n self.data['strain'][strain]['featureinfo'] = []\n\n for fname in dat['files'][idx]:\n\n gen, poles, feats = self.ReadFromFile( fpath, fname)\n self.data['strain'][strain]['geninfo'] += [gen]\n self.data['strain'][strain]['polesinfo'] += [poles]\n self.data['strain'][strain]['featureinfo'] += [feats]\n\n\n def ReadFromFile(self, fpath, fname):\n # Read data from files and parse into general, poles and feature information\n\n # Initialize lists\n geninfo = []\n polesinfo = []\n featureinfo = []\n\n if self.verbose:\n self.PrintFile( fname)\n\n # Add General Information\n with open(fpath + fname) as fp:\n \n addLine = None \n for cnt, line in enumerate(fp):\n \n if line.find( 'General Information') > -1:\n addLine = 'G' \n if line.find( 'Poles Information') > -1:\n addLine = 'P' \n if line.find( 'Feature Information') > -1:\n addLine = 'F' \n\n # Add General Information\n if addLine == 'G':\n geninfo.append( line)\n\n # Add Poles Information\n elif addLine == 'P':\n polesinfo.append( line)\n\n # Add Feature Information\n elif addLine == 'F':\n featureinfo.append( line)\n\n return geninfo, polesinfo, featureinfo\n\n def PrintFile(self, fname):\n # Print all the information from a file to screen \n\n fp = open( self.fpath + fname)\n fc = fp.read()\n print(fc)\n fp.close()\n\n##########################################\nif __name__ == \"__main__\":\n \n x = Load(verbose=1)\n\n" }, { "alpha_fraction": 0.5637927651405334, "alphanum_fraction": 0.5835621356964111, "avg_line_length": 32.50920104980469, "blob_id": "360ca785750fc19e20efaecef4919a5a7e163ddf", "content_id": "0e361e29f4c2e2a9c648d5bea9a89094e3db4a8d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10926, "license_type": "permissive", "max_line_length": 108, "num_lines": 326, "path": "/src/breakBipolar.py", "repo_name": "saadjansari/KymoAnalysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os, pdb\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom pathlib import Path\nfrom .Kymograph import *\nimport shutil\nfrom random import sample\nimport seaborn as sns\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.cluster import KMeans\nfrom sklearn.mixture import GaussianMixture\nfrom sklearn.metrics import silhouette_score\nimport pickle\n\n'''\nName: breakBipolar.py\nDescription: Plots the pole separation of a bipolar file\n'''\n\nparent_path = Path('/Users/saadjansari/Documents/Projects/ImageAnalysis/KymoAnalysis/data/temp')\n\n# Strain folders\nfolds = ['wild type']\n# folds = ['cut7-989TD,pkl1D,klp2D']\n# folds = ['wild type','cut7-989TD,pkl1D,klp2D']\n\n# savepath = Path('/Users/saadjansari/Documents/Projects/ImageAnalysis/KymoAnalysis/Analysis/result_wt')\n# savepath = Path('/Users/saadjansari/Documents/Projects/ImageAnalysis/KymoAnalysis/Analysis/result_mutant')\nsavepath = Path('/Users/saadjansari/Documents/Projects/ImageAnalysis/KymoAnalysis/Analysis/blahblah')\n\n# slope_window = 25\n# nsamples = 10\n# thresh = [0.008, 0.005]\n\n\n# get_data_from_files {{{\ndef get_data_from_files(parent_path, folds):\n\n # lists\n times = []\n length = []\n velocity = []\n acceleration = []\n strain_tag = []\n file_tag = []\n\n # folds is list containing different strain names\n for jj,jfold in enumerate(folds):\n\n # txt files\n mainpath = parent_path / jfold\n files2break = mainpath.glob('*txt')\n\n for jfile, fil in enumerate(files2break):\n kymo = Kymograph(fname=str(fil))\n\n # Only do stuff if its bipolar \n if len(kymo.poles) == 2:\n\n # Times\n time = np.array( sorted( np.hstack( (kymo.poles[0].time, kymo.poles[1].time) ) )[1::10] )\n time = np.linspace(time[0], time[-1], int(np.ceil(time[-1]-time[0])))\n # times.append(time)\n\n # Calculate spindle length, velocity, acceleration\n clen = np.absolute( kymo.poles[1].ifunc( time)- kymo.poles[0].ifunc(time))\n cvel = list( (clen[1:]-clen[:-1]) / (time[1:] - time[:-1]) )\n cvel.insert(0, cvel[0])\n cvel = np.array(cvel)\n cacc = list( (cvel[1:]-cvel[:-1]) / (time[1:] - time[:-1]) )\n cacc.insert(0, cacc[0])\n cacc = np.array(cacc)\n for jt in range(len(time)):\n times.append(time[jt])\n length.append(clen[jt])\n velocity.append(cvel[jt])\n acceleration.append(cacc[jt])\n strain_tag.append( jfold)\n file_tag.append( os.path.basename(kymo.label) )\n df = pd.DataFrame({'strain':strain_tag,\n 'index':file_tag,\n 'time':times,\n 'length':length, \n 'velocity':velocity,\n 'acceleration':acceleration,\n })\n return df\n# }}}\n\n# pair_plot {{{\ndef pair_plot(datframe, vars_compare, label=None, savePath=None, title=''):\n \n fig,ax = plt.subplots(figsize=(12,9))\n if label is None:\n sns.pairplot(datframe, vars=vars_compare,\n plot_kws=dict(marker=\"+\", s=50,linewidth=3, alpha=0.1),\n diag_kind='kde',\n palette='Dark2', height=3)\n else:\n sns.pairplot(datframe, vars=vars_compare, hue=label,\n plot_kws=dict(marker=\"+\", s=50,linewidth=3, alpha=0.1),\n diag_kind='kde',\n palette='Dark2', height=3)\n plt.tight_layout()\n plt.title(title)\n if savePath is not None:\n plt.savefig(savePath)\n plt.close()\n# }}}\n\n# Kmeans {{{\ndef do_KMeans(df, vars_compare, n_clusters=2, display=True, savePath=None):\n\n data = df[vars_compare].to_numpy()\n # scaler = StandardScaler()\n # X_std = scaler.fit_transform(data)\n X_std = data\n\n print('KMeans clustering: N_clusters = {}'.format(n_clusters))\n kmeans = KMeans(n_clusters=n_clusters, \n init='k-means++', \n max_iter=300, \n n_init=10, \n random_state=10)\n model = kmeans.fit(X_std)\n labels = model.predict(X_std)\n sil_score = silhouette_score(X_std,labels)\n print('Silhouette Score = {0:.3f}'.format(sil_score))\n df['label'] = labels\n df = labels_ordered(df,'length')\n\n if display and savePath is not None:\n pair_plot(df, vars_compare, label=\"label\",title='kmeans',\n savePath=savePath)\n return df, model\n# }}}\n\n# GMM {{{\ndef do_GaussianMixtureModel(df, vars_compare, n_clusters=2, display=True, savePath=None):\n\n data=df[vars_compare].to_numpy()\n scaler = StandardScaler()\n X_std = scaler.fit_transform(data)\n\n # define the model\n print('Gaussian Mixture Model: N_components = {}'.format(n_clusters))\n model = GaussianMixture(n_components=n_clusters).fit(X_std)\n labels = model.predict(X_std)\n sil_score = silhouette_score(X_std,labels)\n print('Silhouette Score = {0:.3f}'.format(sil_score))\n df['label'] = labels\n df = labels_ordered(df,'length')\n\n if display and savePath is not None:\n pair_plot(df, vars_compare, label=\"label\",title='kmeans',\n savePath=savePath)\n return df, model\n# }}}\n\n# LabelsOrdered {{{\ndef labels_ordered( df, ref_name):\n\n label_list_new = []\n\n # Get unique labels and the mean values of the reference variable\n labels = sorted(df.label.unique())\n mu = np.zeros( len(labels) )\n for jlab in range(len(labels)):\n mu[jlab] = df[df.label == labels[jlab]][ref_name].mean()\n \n # Create mapping from old_label to new\n labels_new = [x for _,x in sorted( list(zip(mu,labels)), key=lambda x:x[0])]\n # pdb.set_trace()\n mapping = {k:v for k,v in zip(labels,labels_new)}\n print(mapping)\n \n for jlab in df.label:\n label_list_new.append( mapping[jlab])\n df.label = label_list_new\n return df\n# }}}\n\n# plotClassifiedTracks {{{\ndef plotClassifiedTracks(df, saveParent=None, nSamples=50, model=None):\n\n # for each unique strain, make a plot\n # extract tracks\n strains = df.strain.unique().tolist()\n for strain in strains:\n fig,(ax0,ax1,ax2) = plt.subplots(1,3,figsize=(18,4.5), sharey=True)\n \n indices = df[df.strain == strain]['index'].unique()\n # Pick nSamples indices at random\n # indices2plot = sample(list(indices), nSamples)\n indices2plot = indices[:nSamples]\n \n # plot each track\n for ind in indices2plot:\n\n # get track to plot\n track = df[ (df['strain'] == strain) & (df['index'] == ind)]\n time = np.array(track.time)\n length = np.array(track.length)\n label = np.array(track.label)\n\n # Plot Axis 0\n ax0.plot(time, length, alpha=0.5, color='k', lw=2)\n\n # Plot Axis 1\n # len_group0 and len_group1 \n len_0 = length.copy()\n len_1 = length.copy()\n idx0 = np.where(label == 0)[0]\n idx1 = np.where(label == 1)[0]\n len_0[idx1] = np.nan \n len_1[idx0] = np.nan \n ax1.plot(time, len_0, alpha=0.5, lw=2, color='green')\n ax1.plot(time, len_1, alpha=0.5, lw=2,color='purple')\n\n # Plot Axis 2\n label_new = np.array(ForceLabelsOneWay( SmoothClassifiedLabels(label, span=100) ) )\n len_0 = length.copy()\n len_1 = length.copy()\n idx0 = np.where(label_new == 0)[0]\n idx1 = np.where(label_new == 1)[0]\n len_0[idx1] = np.nan \n len_1[idx0] = np.nan \n # pdb.set_trace()\n ax2.plot(time, len_0, alpha=0.5, lw=2,color='green')\n ax2.plot(time, len_1, alpha=0.5, lw=2,color='purple')\n\n # Labels/Legend Axis 0\n ax0.set(ylabel=r'Spindle Length $(\\mu m)$', xlabel='Time (s)')\n\n # Labels/Legend Axis 1\n ax1.plot([],[], alpha=0.7, color='green', label='Group 0')\n ax1.plot([],[], alpha=0.7, color='purple', label='Group 1')\n ax1.legend()\n ax1.set(xlabel='Time (s)')\n \n # Labels/Legend Axis 2\n ax2.plot([],[], alpha=0.7, color='green', label='Group 0')\n ax2.plot([],[], alpha=0.7, color='purple', label='Group 1')\n ax1.legend()\n ax2.set(xlabel='Time (s)')\n\n plt.suptitle(strain)\n plt.tight_layout()\n\n if saveParent is not None:\n if model is None:\n plt.savefig( saveParent / 'tracks_{0}.pdf'.format(strain))\n else:\n plt.savefig( saveParent / 'tracks_{0}_{1}.pdf'.format(model,strain))\n plt.close()\n# }}}\n\n# SmoothClassifiedLabels {{{\ndef SmoothClassifiedLabels(label, span=100): \n\n # smooth_data {{{\n def smooth_data(arr, span):\n re = np.convolve(arr, np.ones(span * 2 + 1) / (span * 2 + 1), mode=\"same\")\n\n # The \"my_average\" part: shrinks the averaging window on the side that\n # reaches beyond the data, keeps the other side the same size as given\n # by \"span\"\n re[0] = np.average(arr[:span])\n for i in range(1, span + 1):\n re[i] = np.average(arr[:i + span])\n re[-i] = np.average(arr[-i - span:])\n return re\n # }}}\n\n # Smoothed Labels\n label_new = np.where(np.array( smooth_data( label,min([span, int(len(label)/2)]))) >= 0.5, 1, 0)\n\n # Once 1, always 1\n # label_perm = [max(label_new[:1+jj]) for jj in range(len(label_new))]\n return label_new\n# }}}\n\n# ForceLabelsOneWay {{{\ndef ForceLabelsOneWay( label):\n labels = [np.max(label[:1+idx]) for idx in range(len(label))]\n return np.array(labels)\n# }}}\n\nif not Path.exists( savepath):\n os.mkdir( savepath)\n\n# Load data into dataframe\ndf = get_data_from_files(parent_path, folds)\nnames = ['velocity']\n\n# Display (pre clustering)\npair_plot(df, names, savePath=savepath/'features_grid_raw.png')\n\n# Kmeans\ndf_kmean, model_kmean = do_KMeans(df.copy(),names, savePath=savepath/'features_grid_kmeans.png')\nprint(df_kmean.groupby('label').mean() )\n\nplotClassifiedTracks(df_kmean, model='kmeans',saveParent=savepath)\n\n# Save model\nwith open(parent_path / 'kmeans.pickle', 'wb') as f:\n pickle.dump(model_kmean, f)\n\n# GMM\n# df_gmm, model_gmm = do_GaussianMixtureModel(df.copy(),names, savePath=savepath/'features_grid_gmm.png')\n# print(df_gmm.groupby('label').mean() )\n# plotClassifiedTracks(df_gmm, model='gmm',saveParent=savepath)\n\n\n # if vel_thresh[0]==1:\n # anaphase_time = 'Always'\n # elif vel_thresh[0]==0 and vel_thresh[-1]==1:\n # anaphase_time = timelist[ np.where(np.array(vel_thresh)>0.5)[0][0] ]\n # elif vel_thresh[-1]==0:\n # anaphase_time = 'Never'\n \n # # anaphase_time = timelist[ np.where(np.array(vel_thresh)>0.5)[0][0] ]\n # print( '{0} --> Anaphase B Transition = {1} sec'.format( files2break[idx].stem,anaphase_time))\n\n\n" } ]
11
EdDanileyko/DataStructures
https://github.com/EdDanileyko/DataStructures
f442938b60f3aae95c551115852873c38d23f4f5
9713765bf6ee4751c102da481496ad0f3ad697be
1da3d09bf42afdabe0f352241e561d307cf9b66e
refs/heads/master
2020-03-19T13:39:39.615498
2018-06-11T06:37:28
2018-06-11T06:37:28
136,589,270
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5401599407196045, "alphanum_fraction": 0.5435778498649597, "avg_line_length": 34.596107482910156, "blob_id": "3f18131b54548a20f14f973194cf37f163373db6", "content_id": "fa2f31779683e0e80a1bfad03ed73f047905f267", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14629, "license_type": "no_license", "max_line_length": 104, "num_lines": 411, "path": "/DataStructures.py", "repo_name": "EdDanileyko/DataStructures", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 9 02:32:25 2018\n\n@author: edwar\n\"\"\"\nclass ListNode(object):\n \"\"\"A linked list node.\"\"\"\n def __init__(self, val=None, nextnode=None):\n self._val, self._next = val, nextnode\n \n def __del__(self): print(\"destroying {}\".format(self))\n \n @property\n def val(self): return self._val\n @val.setter\n def val(self, val):\n self._val = val\n\n @property\n def next(self): return self._next\n @next.setter\n def next(self, node):\n if isinstance(node, ListNode): self._next = node\n else: raise TypeError\\\n ('next node must be of type ListNode. Found {}'.format(type(node)))\\\n \n def __str__(self):\n return str(self._val)\n \n def __lt__(self, other):\n if isinstance(other, ListNode): return self.val < other.val\n if not isinstance(other, type(self.val)):\n raise TypeError\\\n (\"'<' not supported between instances of '{}' and '{}'\".format(type(self.val), type(other)))\n else: return self.val < other\n \n def __len__(self): \n try:\n return len(self.val)\n except TypeError:\n raise TypeError\\\n (\"object of type '{}' has no len()\".format(type(self.val)))\n \n \nclass TreeNode(object):\n \"\"\"A Binary Tree Node. Height is base 0. an asterisk (val*) indicates\n that the node is the root node\"\"\"\n def __init__(self, val=None):\n self._val, self._height, self._isroot = val, 0, False\n self._rchild = self._lchild = None\n \n def __del__(self):\n print(\"{} destroyed\".format(self))\n \n @property\n def val(self): return self._val\n \n @property\n def lchild(self): return self._lchild\n \n @property\n def rchild(self): return self._rchild\n \n @property\n def children(self): return self.lchild, self.rchild\n \n @property\n def isLeaf(self): return self.children == (None, None)\n \n @property\n def isRoot(self): return self._isroot\n \n @property\n def height(self):\n \"\"\"Max of the child heights plus 1\"\"\"\n if self.lchild is not None and self.rchild is not None:\n self._height = max(self.rchild._height, self.lchild._height) + 1\n elif self.lchild: self._height = self.lchild.height + 1\n elif self.rchild: self._height = self.rchild.height + 1\n else: pass\n return self._height\n \n def __add__(self, other):\n if isinstance(other, type(self._val)): return self.val + other\n elif isinstance(other, TreeNode): return self.val + other.val\n else: return NotImplemented\n \n def __sub__(self, other): return self.val - other\n def __rsub__(self, other): return other - self.val\n def __mul__(self, other): return self.val*other\n #def __div__(self, other): return self.val/other\n #def __rdiv__(self, other): return other/self.val\n __rmul__ = __mul__\n __radd__ = __add__\n \n def __lt__(self, other):\n if isinstance(other, TreeNode): return self.val < other.val\n #if not isinstance(other, type(self.val)):raise TypeError\\\n #(\"'<' not supported between instances of '{}' and '{}'\".format(type(self.val), type(other)))\n else: return self.val < other\n \n def __gt__(self, other):\n if isinstance(other, TreeNode): return self.val > other.val\n if not isinstance(other, type(self.val)):raise TypeError\\\n (\"'>' not supported between instances of '{}' and '{}'\".format(type(self.val), type(other)))\n else: return self.val > other\n \n def __eq__(self, other):\n if isinstance(other, TreeNode): return self.val == other.val\n else: return self.val == other\n \n def __str__(self):\n tag = '*' if self.isRoot else ''\n return \"{}{}\".format(str(self.val), tag)\n def __repr__(self): return str(self)\n def __hash__(self): return hash(str(self))\n \n def __iter__(self):\n \"\"\"Depth First Iteration\"\"\"\n if self.lchild is not None: yield from self.lchild\n if self.val is not None: yield self\n if self.rchild is not None: yield from self.rchild\n \n def __getitem__(self, key):\n if not isinstance(key, int): raise TypeError\n return self[key].val\n \n def __reversed__(self):\n \"\"\"Reversed Depth First Iteration\"\"\"\n if self.rchild is not None: yield from self.rchild\n if self.val is not None: yield self\n if self.lchild is not None: yield from self.lchild\n \n \nclass LinkedList(object):\n \"\"\"A Singly-Linked List.\"\"\"\n def __init__(self, l=[]):\n \n self._head = self._tail = self._curr = None\n self._size = 0\n \n while self._size < len(l):\n if self._size == 0:\n newNode = ListNode(l[self._size])\n self._head = newNode\n self._curr = self._head\n else:\n newNode = self._curr._next\n self._curr = newNode\n try: newNode._next = ListNode(l[self._size+1])\n except IndexError:\n self._tail = newNode\n self._size+=1\n self.reset()\n \n def __str__(self):\n return str(self._curr)\n \n @property\n def __len__(self): return self._size\n \n @property\n def head(self): return self._head\n \n @property\n def tail(self): return self._tail\n \n @property\n def curr(self): return self._curr\n \n def traverse(self, n, reset=False):\n \"\"\"Traverses n places toward the tail from the active node.\n if reset is True, then traversal will commence from the head.\"\"\"\n i = 0\n if reset: self.reset()\n try:\n while i < n:\n self.curr = self.curr.next \n i+=1\n return self.curr.val\n except AttributeError:\n self.reset() # Not sure if resetting is appropriate\n raise IndexError\n \n def pop(self):\n \"\"\"Retrieves the last element of the list and removes it from the list.\n Decrements the size.\"\"\"\n pass\n \n def top(self):\n \"\"\"Retrieves the head element of the list and removes it from the list.\n Sets 2nd element as the new head and decrements the size.\"\"\"\n pass\n \n def reset(self):\n self.curr = self.head\n \n \nclass CircularList(LinkedList):\n \"\"\"A Circular Linked List.\"\"\"\n def __init__(self, l):\n super().__init__(l)\n \n def _populate(self, l):\n while self.size < len(l):\n if self.size == 0:\n newNode = ListNode(l[self.size])\n self.head = newNode\n self.curr = self.head\n else:\n newNode = self.curr.next\n self.curr = newNode\n try: newNode.next = ListNode(l[self.size+1])\n except IndexError:\n newNode.next = self.head\n self.curr = self.head\n self.size+=1\n \n \nclass DoubleLinkedList(LinkedList):\n \"\"\"A Doubly-Linked List.\"\"\"\n class ExtendedNode(ListNode):\n \"\"\"Extended node (stores prev)\"\"\"\n def __init__(self, val):\n super().__init__(val)\n self.prev = None\n \n def __init__(self, l):\n super().__init__(l)\n \n def _populate(self, l):\n while self.size < len(l):\n if self.size == 0:\n newNode = self.ExtendedNode(l[self.size])\n self.head = newNode\n self.curr = self.head\n else:\n newNode = self.curr.next\n newNode.prev = self.curr\n self.curr = newNode\n try: newNode.next = self.ExtendedNode(l[self.size+1])\n except IndexError: self.tail = newNode\n self.size+=1\n self.reset()\n \n def traverse(self, n, reset=False):\n i = 0\n if reset and n > 0: self.reset()\n elif reset and n < 0: self.reset(True)\n try:\n while i < abs(n):\n if n > 0: self.curr = self.curr.next\n elif n < 0: self.curr = self.curr.prev\n i+=1\n return self.curr.val\n except AttributeError:\n self.reset()\n return 'NIL'\n \n def reset(self, tail=False):\n if not tail: self.curr = self.head\n else: self.curr = self.tail\n \n \nclass Bst(object):\n \"\"\"A Binary Search Tree\"\"\"\n def __init__(self, val=None):\n self._size, self._root = 0, None\n if val != None:\n if type(val) == int or type(val) == str: self.add(val)\n else:\n for i in val:\n self.add(i)\n \n #def __del__(self):\n #self._root = self.root._lchild = self.root._rchild = None\n \n def __len__(self): return self._size\n \n @property\n def root(self): return self._root\n \n @property\n def height(self):\n \"\"\"Returns the height of the tree\"\"\"\n if isinstance(self.root, TreeNode): return self.root.height\n else: return None\n \n def isEmpty(self): return self.root is None\n \n def add(self, val):\n \"\"\"Adds an item to the tree recursively starting from the root\"\"\"\n if self.isEmpty():\n newNode = TreeNode(val)\n self._root, newNode._isroot = newNode, True\n if type(val) == type(self.root.val):\n self._add(val, self.root)\n self._size +=1\n else: raise TypeError\\\n ('Value must be of type {}. Found {}'.format(type(self.root.val),type(val)))\n \n def _add(self, val, currNode):\n \"\"\"Actual private recursive insert for non-root nodes\"\"\"\n if val > currNode:\n if currNode.rchild is None:\n currNode._rchild = TreeNode(val)\n if currNode.lchild is not None:\n currNode._height = max(currNode.lchild.height, currNode.rchild.height) + 1\n else: currNode._height +=1\n else: self._add(val, currNode.rchild)\n elif val < currNode:\n if currNode.lchild is None:\n currNode._lchild = TreeNode(val)\n if currNode.rchild is not None:\n currNode._height = max(currNode.lchild.height, currNode.rchild.height) + 1\n else: currNode._height +=1\n else: self._add(val, currNode.lchild)\n \n def __repr__(self):\n \"\"\"Prints all tree node values Depth First in list form\"\"\"\n return str({node: node.children for node in self})\n \n def __iter__(self):\n if self.root is not None: return iter(self.root)\n else: return iter([])\n \n def __contains__(self, val) -> bool:\n if type(val) == type(self.root.val):\n try: return self._find(val, self.root)\n except KeyError: return False\n else: raise TypeError\\\n ('Search value must be of type {}.'.format(type(self.root.val)))\n \n def __getitem__(self, key) -> TreeNode:\n \"\"\"Retrieves a subtree. If the target node is not found\n or if the key is of the wrong type, we raise a KeyError.\"\"\"\n node = self._find(key, self.root)\n if node is not None: return node\n else: raise KeyError(str(key))\n \n def _find(self, val, currNode):\n \"\"\"Recursive search. Returns the target node\"\"\"\n if currNode.val == val:\n return currNode\n elif val > currNode and currNode.rchild != None:\n return self._find(val, currNode.rchild)\n elif val < currNode and currNode.lchild != None:\n return self._find(val, currNode.lchild)\n else: return None\n \n def _childAndParent(self, val, currNode) -> tuple:\n \"\"\"Recursive search. Returns the target node and its parent\"\"\"\n if val in currNode.children:\n return self[val], currNode\n elif val > currNode and currNode.rchild != None:\n return self._childAndParent(val, currNode.rchild)\n elif val < currNode and currNode.lchild != None:\n return self._childAndParent(val, currNode.lchild)\n else: return (self[val], None)\n \n def remove(self, val):\n \"\"\"Removes a tree node containing a specified value\n should find the target node. If it is a leaf, destroy the leaf.\n if not, then travel down the left branch to find a node without a\n right child (max of the left sub-tree), then we reset the child node's\n children to that of the target node and redefine the target node as\n that child node. If there is no left sub-tree, we travel right and find\n a node with no left child (min of the right sub-tree) and perform substitution.\"\"\"\n targetNode, parent = self._childAndParent(val, self.root)\n if targetNode is not None:\n # if we are deleting a leaf, set the parent's child to none\n if targetNode.isLeaf and parent is not None:\n if parent._lchild == targetNode: parent._lchild = None\n elif parent._rchild == targetNode: parent._rchild = None\n \n else:\n # - SubNode finding logic\n # check if the target node is not minimum,\n # if so, then the substitute is min\n if targetNode != min(targetNode):\n subNode = min(targetNode)\n \n # if the target node is the minimum (lchild=None),\n # then the substitute is the minimum of the right subTree\n else: subNode = min(targetNode.rchild)\n \n # - Replacement Logic (parent)\n if parent is not None:\n if parent._lchild == targetNode: parent._lchild = subNode\n elif parent._rchild == targetNode: parent._rchild = subNode\n \n # - Replacement Logic (children)\n if subNode not in targetNode.children:\n subNode._lchild, max(subNode)._rchild = targetNode.lchild, targetNode.rchild\n elif subNode == targetNode.lchild:\n max(subNode)._rchild = targetNode.rchild\n \n if targetNode.isRoot: subNode._isroot = True\n \n bst._size -=1\n\nif __name__ == '__main__':\n \n bst = Bst()\n def fillTree(tree, num_elems=10, max_int=100):\n from random import randint\n for _ in range(num_elems): tree.add(randint(0, max_int))\n return tree\n \n fillTree(bst)" } ]
1
SlavaAZM/python
https://github.com/SlavaAZM/python
93ed6039e316271a798a8d725cda636504622041
347df72fbcaeeca08987052af5f6d26c4ae043f5
324c3312e7939780c741b7255f466d0df209f115
refs/heads/master
2021-05-21T17:40:26.745335
2020-04-05T06:33:39
2020-04-05T06:33:39
252,738,887
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5896504521369934, "alphanum_fraction": 0.6250567436218262, "avg_line_length": 24.61627960205078, "blob_id": "f040d2de49fb96fd9edbf1e47557c0d8287d88b6", "content_id": "b9258f8b8ef366d9223ec6fcf558f5ca2a433665", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2366, "license_type": "no_license", "max_line_length": 86, "num_lines": 86, "path": "/lab3/smylik.py", "repo_name": "SlavaAZM/python", "src_encoding": "UTF-8", "text": "from graph import *\nfrom math import *\n\ndef brow(with_brow, height_brow, k, angle_brow, x_eye, y_eye, r_eye):\n '''рисует бровь как касательную к глазу'''\n # находим точку на окружности чараз которую проходит касательная с задонным углом\n #\n alfa = radians(angle_brow)\n beta = radians(angle_brow - 180)\n xa = x_eye + r_eye * cos(alfa) # координата точки на окруности\n ya = y_eye + r_eye * sin(alfa)\n\n x1 = xa + k * with_brow * sin(beta)\n y1 = ya + k * with_brow * cos(alfa)\n x2 = xa + (1 - k) * with_brow * sin(alfa)\n y2 = ya + (1 - k) * with_brow * cos(beta)\n\n xb = x_eye + (r_eye + height_brow) * cos(alfa) # координата точки на окруности\n yb = y_eye + (r_eye + height_brow) * sin(alfa)\n\n x3 = xb + k * with_brow * sin(beta)\n y3 = yb + k * with_brow * cos(alfa)\n x4 = xb + (1 - k) * with_brow * sin(alfa)\n y4 = yb + (1 - k) * with_brow * cos(beta)\n polygon([(x1, y1), (x3, y3), (x4, y4), (x2, y2), (x1, y1), ])\n\n\n\nwith_w = 350\nheight_w = 350\nwindowSize(with_w, height_w)\n\ncenter_x = height_w // 2\ncenter_y = with_w // 2\n\npenColor(\"black\")\npenSize(1)\n\n# овал лица\nR_faice = 150\nbrushColor(\"yellow\")\ncircle(center_x, center_y, R_faice)\n\n# рот\nwith_lips = 130\nheight_lips = 50\nbrushColor(\"black\")\nx_lips = center_x - with_lips // 2\ny_lips = center_y + R_faice // 2 - height_lips // 2\nrectangle(x_lips, y_lips, x_lips + with_lips, y_lips + height_lips)\n\nr_eye_right = 20\nr_pupil_right = 15\nr_eye_left = 30\nr_pupil_left = 10\nwith_eye = 50\nheight_eye = 70\n\n# right eye\nx_eye_right = center_x - with_eye\ny_eye_right = center_y - height_eye // 2\npenColor(\"red\")\nbrushColor(\"red\")\ncircle(x_eye_right, y_eye_right, r_eye_right)\n# right eye pupil\nbrushColor(\"black\")\ncircle(x_eye_right, y_eye_right, r_pupil_right)\n\n# left eye\nx_eye_left = center_x + with_eye\ny_eye_left = center_y - height_eye // 2\npenColor(\"red\")\nbrushColor(\"red\")\ncircle(x_eye_left, y_eye_left, r_eye_left)\n# right eye pupil\npenColor(\"white\")\nbrushColor(\"white\")\npenSize(1)\ncircle(x_eye_left, y_eye_left, r_pupil_left)\n\npenColor(\"black\")\nbrushColor(\"black\")\nbrow(80, 15, 0.3, 290, x_eye_right, y_eye_right, r_eye_right)\nbrow(80, 15, 0.7, 250, x_eye_left, y_eye_left, r_eye_left)\n\nrun()\n" }, { "alpha_fraction": 0.7407407164573669, "alphanum_fraction": 0.7407407164573669, "avg_line_length": 13, "blob_id": "43676682fcdff590babaa91627e9eadf357485e4", "content_id": "9d33145cfaa410ba586332087de9b7151295d580", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 27, "license_type": "no_license", "max_line_length": 18, "num_lines": 2, "path": "/README.md", "repo_name": "SlavaAZM/python", "src_encoding": "UTF-8", "text": "# python\n#it's test project" } ]
2
anjhoon/CS313E
https://github.com/anjhoon/CS313E
ce71a607bbb85121daa2363bfb2b551d9a65eb3a
80ea6de855323d9ea1f78fe468e28ff84a57e81a
3ec19de9ed1ae7ba65dcf35a37877219c70633b8
refs/heads/master
2020-08-12T10:50:48.449647
2020-01-24T21:39:01
2020-01-24T21:39:01
214,753,783
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5362827181816101, "alphanum_fraction": 0.556124210357666, "avg_line_length": 25.5880069732666, "blob_id": "2215812873c552b86ba3823d147f8290a718850d", "content_id": "cf7ec289322001424a7fc56272f840e2a789163a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14263, "license_type": "no_license", "max_line_length": 104, "num_lines": 517, "path": "/TestLinkedList.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# File: TestLinkedList.py\r\n\r\n# Description: Make a single linked list and create some methods\r\n\r\n# Student Name: Andrew Chen\r\n\r\n# Student UT EID: ac68644\r\n\r\n# Partner Name: Saaketh Palchuru\r\n\r\n# Partner UT EID: srp2992\r\n\r\n# Course Name: CS 313E\r\n\r\n# Unique Number: 50210\r\n\r\n# Date Created: 10/28/19\r\n\r\n# Date Last Modified: 11/1/19\r\n\r\n\r\nclass Link(object):\r\n def __init__(self, data, next=None):\r\n self.data = data\r\n self.next = next\r\n\r\n\r\nclass LinkedList(object):\r\n def __init__(self):\r\n self.first = None\r\n\r\n # get number of links\r\n def get_num_links(self):\r\n current = self.first\r\n length = 0\r\n\r\n if current == None:\r\n return length\r\n\r\n while current != None:\r\n length += 1\r\n current = current.next\r\n\r\n return length\r\n\r\n # add an item at the beginning of the list\r\n def insert_first(self, data):\r\n new_link = Link(data)\r\n new_link.next = self.first\r\n self.first = new_link\r\n\r\n # add an item at the end of a list\r\n def insert_last(self, data):\r\n new_link = Link(data)\r\n current = self.first\r\n\r\n # if list is empty\r\n if current == None:\r\n self.first = new_link\r\n return\r\n\r\n # traverse linked list until the last link\r\n while current.next != None:\r\n current = current.next\r\n\r\n current.next = new_link\r\n\r\n # add an item in an ordered list in ascending order\r\n def insert_in_order(self, data):\r\n new_link = Link(data)\r\n current = self.first\r\n previous = self.first\r\n\r\n # if list is empty\r\n if current == None:\r\n self.first = new_link\r\n return\r\n # if first link is larger than item\r\n if current.data > data:\r\n new_link.next = self.first\r\n self.first = new_link\r\n return\r\n\r\n # traverse linked list to last link\r\n while current.next != None:\r\n # if link is smaller than item\r\n if current.data <= data:\r\n previous = current\r\n current = current.next\r\n # else link item to current then link previous to item\r\n else:\r\n new_link.next = previous.next\r\n previous.next = new_link\r\n return\r\n\r\n # if at last link and link is less than item item is new last link\r\n if current.data <= data:\r\n current.next = new_link\r\n # if at last link and link is greater than item insert item before last link\r\n else:\r\n new_link.next = previous.next\r\n previous.next = new_link\r\n return\r\n\r\n # search in an unordered list, return None if not found\r\n def find_unordered(self, data):\r\n current = self.first\r\n\r\n if current == None:\r\n return None\r\n\r\n # traverse until data is found or not found\r\n while current.data != data:\r\n if current.next == None:\r\n return None\r\n else:\r\n current = current.next\r\n\r\n return current\r\n\r\n # Search in an ordered list, return None if not found\r\n def find_ordered(self, data):\r\n current = self.first\r\n\r\n if current == None:\r\n return None\r\n\r\n # traverse list until list's data is greater than data to find\r\n while current.data != data:\r\n if current.data > data:\r\n return None\r\n else:\r\n current = current.next\r\n\r\n return current\r\n\r\n # Delete and return Link from an unordered list or None if not found\r\n def delete_link(self, data):\r\n previous = self.first\r\n current = self.first\r\n\r\n if current == None:\r\n return None\r\n\r\n # traverse until you find or don't find data\r\n while current.data != data:\r\n if current.next == None:\r\n return None\r\n else:\r\n previous = current\r\n current = current.next\r\n\r\n # if linked list is on first link\r\n if current == self.first:\r\n self.first = self.first.next\r\n # else delete the link\r\n else:\r\n previous.next = current.next\r\n\r\n return current\r\n\r\n # String representation of data 10 items to a line, 2 spaces between data\r\n def __str__(self):\r\n\r\n current = self.first\r\n string = ''\r\n item = 0\r\n counter = 0\r\n\r\n if current == None:\r\n return string\r\n\r\n while current != None:\r\n\r\n string += str(current.data)\r\n current = current.next\r\n item += 1\r\n counter += 1\r\n\r\n if item == 10:\r\n string += '\\n'\r\n item = 0\r\n elif counter == self.get_num_links():\r\n return string\r\n else:\r\n string += ' '\r\n\r\n # Copy the contents of a list and return new list\r\n def copy_list(self):\r\n new_list = LinkedList()\r\n current = self.first\r\n\r\n # traverse until the current is None to insert every link\r\n while current != None:\r\n new_list.insert_last(current.data)\r\n current = current.next\r\n\r\n return new_list\r\n\r\n # Reverse the contents of a list and return new list\r\n def reverse_list(self):\r\n new_list = LinkedList()\r\n current = self.first\r\n\r\n # insert the data into linked list in first position every time\r\n while current != None:\r\n new_list.insert_first(current.data)\r\n current = current.next\r\n\r\n return new_list\r\n\r\n # Sort the contents of a list in ascending order and return new list\r\n def sort_list(self):\r\n new_list = LinkedList()\r\n current = self.first\r\n\r\n while current != None:\r\n new_list.insert_in_order(current.data)\r\n current = current.next\r\n\r\n return new_list\r\n\r\n # Return True if a list is sorted in ascending order or False otherwise\r\n def is_sorted(self):\r\n current = self.first\r\n\r\n # check if next link's data is greater than current links data\r\n while current.next != None:\r\n if current.next.data <= current.data:\r\n return False\r\n else:\r\n current = current.next\r\n\r\n return True\r\n\r\n # Return True if a list is empty or False otherwise\r\n def is_empty(self):\r\n\r\n # check if first link is None\r\n if self.first == None:\r\n return True\r\n return False\r\n\r\n # Merge two sorted lists and return new list in ascending order\r\n def merge_list(self, other):\r\n new_list = LinkedList()\r\n current1 = self.first\r\n current2 = other.first\r\n\r\n # if first is empty return a copy of the other list\r\n if self.is_empty():\r\n return other.copy_list()\r\n # if second is empty return a copy of the first list\r\n elif other.is_empty():\r\n return self.copy_list()\r\n elif self.is_empty() and other.is_empty():\r\n return new_list\r\n\r\n # if both linked lists have links\r\n while current1 != None and current2 != None:\r\n\r\n if current1.data <= current2.data:\r\n new_list.insert_last(current1.data)\r\n current1 = current1.next\r\n elif current2.data < current1.data:\r\n new_list.insert_last(current2.data)\r\n current2 = current2.next\r\n\r\n # if only one linked list still has links\r\n while current1 != None:\r\n new_list.insert_last(current1.data)\r\n current1 = current1.next\r\n\r\n # if only the other linked list still has links\r\n while current2 != None:\r\n new_list.insert_last(current2.data)\r\n current2 = current2.next\r\n\r\n return new_list\r\n\r\n # Test if two lists are equal, item by item and return True\r\n def is_equal(self, other):\r\n current1 = self.first\r\n current2 = other.first\r\n\r\n # if one is empty and the other is not return False\r\n if current1 == None and current2 != None:\r\n return False\r\n elif current1 != None and current2 == None:\r\n return False\r\n\r\n # if both have links traverse and see if each is equal\r\n while current1 != None and current2 != None:\r\n if current1.data != current2.data:\r\n return False\r\n else:\r\n current1 = current1.next\r\n current2 = current2.next\r\n return True\r\n\r\n # Return a new list, keeping only the first occurrence of an element\r\n # and removing all duplicates. Do not change the order of the elements.\r\n def remove_duplicates(self):\r\n new_list = LinkedList()\r\n current = self.first\r\n\r\n # if list is empty return empty linked list\r\n if self.is_empty():\r\n return new_list\r\n\r\n # if linked list is not empty check if the new list has the data, if not then add it to the list\r\n while current != None:\r\n if new_list.find_unordered(current.data) == None:\r\n new_list.insert_last(current.data)\r\n current = current.next\r\n\r\n return new_list\r\n\r\n\r\ndef main():\r\n testList = [56, 84, 32, 91, 27, 45, 88, 36, 19, 23, 48, 54]\r\n testList2 = [21, 36, 1, 34, 86, 34, 90, 85, 64, 21, 21]\r\n testList3 = [31, 51, 5, 31, 90, 87, 58, 44, 39, 68, 75]\r\n\r\n # Test methods insert_first() and __str__() by adding more than\r\n # 10 items to a list and printing it.\r\n lst1 = LinkedList()\r\n for item in testList:\r\n lst1.insert_first(item)\r\n print('test insert_first')\r\n print(lst1)\r\n print()\r\n\r\n # Test method insert_last()\r\n lst2 = LinkedList()\r\n for item in testList:\r\n lst2.insert_last(item)\r\n print('test insert_last')\r\n print(lst2)\r\n print()\r\n\r\n # Test method insert_in_order()\r\n lst3 = LinkedList()\r\n for item in testList:\r\n lst3.insert_in_order(item)\r\n print('test insert_in_order')\r\n print(lst3)\r\n print()\r\n\r\n # Test method get_num_links()\r\n lst4 = LinkedList()\r\n lst5 = LinkedList()\r\n for item in testList:\r\n lst4.insert_last(item)\r\n print(\"test method get_num_links\")\r\n print(lst4.get_num_links())\r\n print(lst5.get_num_links())\r\n print()\r\n\r\n # Test method find_unordered()\r\n # Consider two cases - data is there, data is not there\r\n lst5 = LinkedList()\r\n\r\n for item in testList:\r\n lst5.insert_last(item)\r\n print(\"Test method findUnordered\")\r\n print(lst5.find_unordered(95) != None)\r\n print(lst5.find_unordered(95) == None)\r\n print()\r\n\r\n # Test method find_ordered()\r\n # Consider two cases - data is there, data is not there\r\n lst6 = LinkedList()\r\n\r\n for item in testList:\r\n lst6.insert_in_order(item)\r\n print(\"Test method findOrdered\")\r\n print(lst6.find_ordered(28) != None)\r\n # item there\r\n print(lst6.find_ordered(28) == None)\r\n print()\r\n\r\n # Test method delete_link()\r\n # Consider two cases - data is there, data is not there\r\n\r\n lst7 = LinkedList()\r\n\r\n for item in testList:\r\n lst7.insert_last(item)\r\n\r\n print(\"Test method delete\")\r\n # Consider two cases - item is there, item is not there\r\n # item not there\r\n print('Current list')\r\n print(lst7)\r\n print('Can delete 23?')\r\n print(lst7.delete_link(23) != None)\r\n print(lst7)\r\n # item there\r\n print('Can delete 23?')\r\n print(lst7.delete_link(23) != None)\r\n print('No, 23 is not there anymore')\r\n print(lst7)\r\n print()\r\n\r\n # Test method copy_list()\r\n lst8 = LinkedList()\r\n\r\n for item in testList:\r\n lst8.insert_first(item)\r\n print('testing copy_list')\r\n print(lst8)\r\n print('next is copy')\r\n print(lst8.copy_list())\r\n print()\r\n\r\n # Test method reverse_list()\r\n lst9 = LinkedList()\r\n\r\n for item in testList:\r\n lst9.insert_first(item)\r\n print('testing reverse_list')\r\n print(lst9)\r\n print('next is reversed')\r\n print(lst9.reverse_list())\r\n print()\r\n\r\n # Test method sort_list()\r\n lst10 = LinkedList()\r\n\r\n for item in testList:\r\n lst10.insert_first(item)\r\n print('testing sort_list')\r\n print(lst10)\r\n print('next is sorted')\r\n print(lst10.sort_list())\r\n print()\r\n\r\n # Test method is_sorted()\r\n # Consider two cases - list is sorted, list is not sorted\r\n lst11 = LinkedList()\r\n lst12 = LinkedList()\r\n\r\n for item in testList:\r\n lst11.insert_first(item)\r\n lst12.insert_in_order(item)\r\n\r\n print('testing is_sorted')\r\n print(lst11)\r\n print(lst11.is_sorted())\r\n print(lst12)\r\n print(lst12.is_sorted())\r\n print()\r\n # Test method is_empty()\r\n lst13 = LinkedList()\r\n lst14 = LinkedList()\r\n\r\n for item in testList:\r\n lst13.insert_first(item)\r\n\r\n print('testing is_empty')\r\n print(lst13.is_empty())\r\n print(lst14.is_empty())\r\n print()\r\n\r\n # Test method merge_list()\r\n\r\n list19 = LinkedList()\r\n for item in testList:\r\n list19.insert_in_order(item)\r\n\r\n merge = LinkedList()\r\n for item in testList3:\r\n merge.insert_in_order(item)\r\n\r\n print(\"Test method mergeList\")\r\n print(list19.merge_list(merge))\r\n print()\r\n\r\n # Test method is_equal()\r\n # Consider two cases - lists are equal, lists are not equal\r\n lst15 = LinkedList()\r\n for item in testList:\r\n lst15.insert_in_order(item)\r\n\r\n lst16 = LinkedList()\r\n for item in testList:\r\n lst16.insert_in_order(item)\r\n\r\n lst17 = LinkedList()\r\n lst18 = LinkedList()\r\n\r\n # Test method isEqual()\r\n print(\"testing method is_equal\")\r\n print(lst15)\r\n print(lst16)\r\n\r\n # Consider two cases - lists are equal, lists are not equal\r\n print(lst15.is_equal(lst16))\r\n print(lst15.is_equal(lst17))\r\n print(lst16.is_equal(lst17))\r\n print(lst17.is_equal(lst18))\r\n print()\r\n\r\n # Test remove_duplicates()\r\n lst18 = LinkedList()\r\n for item in testList2:\r\n lst18.insert_last(item)\r\n print('testing remove duplicates')\r\n print(lst18)\r\n print('after removing duplicates')\r\n print(lst18.remove_duplicates())\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n" }, { "alpha_fraction": 0.534956157207489, "alphanum_fraction": 0.5437305569648743, "avg_line_length": 22.19862937927246, "blob_id": "8802d68f59e1704bf7c7230ca92d4487c5fcb857", "content_id": "c9add2653d80a79c5addf43bd110de662bd4ceb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3533, "license_type": "no_license", "max_line_length": 105, "num_lines": 146, "path": "/Josephus.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# File: Josephus.py\r\n\r\n# Description: Utilize a circular linked list to find the last link left after deleting links one by one\r\n\r\n# Student Name: Andrew Chen\r\n\r\n# Student UT EID: ac68644\r\n\r\n# Partner Name: Saaketh Palchuru\r\n\r\n# Partner UT EID: srp2992\r\n\r\n# Course Name: CS 313E\r\n\r\n# Unique Number: 50210\r\n\r\n# Date Created: 10/31/19\r\n\r\n# Date Last Modified: 11/4/19\r\n\r\n\r\nclass Link(object):\r\n def __init__(self, data, next=None):\r\n self.data = data\r\n self.next = next\r\n\r\n\r\nclass CircularList(object):\r\n # Constructor\r\n def __init__(self):\r\n self.first = None\r\n\r\n # Insert an element (value) in the list\r\n def insert(self, data):\r\n new_link = Link(data)\r\n current = self.first\r\n\r\n if current == None:\r\n self.first = new_link\r\n self.first.next = new_link\r\n return\r\n\r\n while current.next != self.first:\r\n current = current.next\r\n\r\n current.next = new_link\r\n new_link.next = self.first\r\n\r\n # Find the link with the given data (value)\r\n def find(self, data):\r\n\r\n current = self.first\r\n\r\n if current == None:\r\n return False\r\n\r\n while current.data != data:\r\n current = current.next\r\n\r\n return current\r\n\r\n # Delete a link with a given data (value)\r\n def delete(self, data):\r\n current = self.first\r\n previous = self.first\r\n\r\n if current == None:\r\n return\r\n\r\n # if data is in the first link\r\n if self.first.data == data:\r\n while previous.next != self.first:\r\n previous = previous.next\r\n previous.next = current.next\r\n self.first = previous.next\r\n return current\r\n # if data is not in the first link\r\n else:\r\n while current.next != self.first:\r\n previous = current\r\n current = current.next\r\n if current.data == data:\r\n previous.next = current.next\r\n\r\n return current\r\n\r\n # Delete the nth link starting from the Link start\r\n # Return the next link from the deleted Link\r\n def delete_after(self, start, n):\r\n\r\n current = self.find(start)\r\n\r\n if current.data == current.next.data:\r\n print(current.data)\r\n self.delete(current.data)\r\n return\r\n\r\n for i in range(n-1):\r\n current = current.next\r\n\r\n print(current.data)\r\n self.delete(current.data)\r\n\r\n return current.next\r\n\r\n # Return a string representation of a Circular List\r\n def __str__(self):\r\n\r\n current = self.first\r\n string = ''\r\n if current == None:\r\n return\r\n\r\n # traverse until we reach the starting link\r\n while current.next != self.first:\r\n string += str(current.data)\r\n string += '\\n'\r\n current = current.next\r\n\r\n if current.next == self.first:\r\n string += str(current.data)\r\n\r\n return string\r\n\r\n\r\ndef main():\r\n infile = open('josephus.txt', 'r')\r\n\r\n number = int(infile.readline())\r\n start = int(infile.readline())\r\n elimination = int(infile.readline())\r\n infile.close()\r\n\r\n soldiers = CircularList()\r\n\r\n for i in range(1, number+1):\r\n soldiers.insert(i)\r\n\r\n start = soldiers.delete_after(start, elimination)\r\n while soldiers.first.next != soldiers.first:\r\n start = soldiers.delete_after(start.data, elimination)\r\n\r\n print(soldiers)\r\n\r\n\r\nmain()\r\n" }, { "alpha_fraction": 0.5089011788368225, "alphanum_fraction": 0.5280539989471436, "avg_line_length": 34.36160659790039, "blob_id": "7a7ccd5519610c2d8275d4bd1ed364be8ba5e860", "content_id": "f666e70d81323cdbdf9bbc5bbe59f3c1a3906926", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8145, "license_type": "no_license", "max_line_length": 108, "num_lines": 224, "path": "/BabyNames.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# File: BabyNames.py\r\n# Description: Creates a menu that gives info on baby name rankings through a dictionary\r\n# Student Name: Andrew Chen\r\n# Student UT EID: ac68644\r\n# Course Name: CS 313E\r\n# Unique Number: 50210\r\n# Date Created: 9/9/19\r\n# Date Last Modified: 9/13/19\r\n\r\n\r\n# search up a name in the dictionary\r\ndef search_name(name, dictionary):\r\n name = name.capitalize()\r\n return name in dictionary\r\n\r\n\r\n# returns a list of all ranks for a particular name\r\ndef name_rank(name, dictionary):\r\n name = name.capitalize()\r\n rank_list = []\r\n # if name is in dictionary add rank to list\r\n if name in dictionary:\r\n for i in dictionary[name]:\r\n # turn 1001 back to 0\r\n if i == 1001:\r\n rank_list.append(\"0\")\r\n # add rank\r\n else:\r\n rank_list.append(str(i))\r\n return rank_list\r\n else:\r\n return\r\n\r\n\r\n# return a list of sorted names that appear in a particular decade\r\ndef one_decade(decade, dictionary):\r\n # get index of value for particular decade\r\n year = decade % 1900 // 10\r\n names = {}\r\n ranks = [value[year] for value in dictionary.values() if value[year] != 1001]\r\n\r\n # add key value pair to names dictionary if the rank is in top 1000\r\n for name, value in dictionary.items():\r\n if value[year] != 1001:\r\n names[name] = value[year]\r\n\r\n # sort dictionary keys in ascending order by values\r\n sorted_names = sorted(names.items(), key=lambda rank: rank[1])\r\n\r\n for names in sorted_names:\r\n print(names[0] + ':', names[1])\r\n\r\n\r\n# return names if values were in top 1000 every decade\r\ndef all_decades(dictionary):\r\n names = []\r\n for name, value in dictionary.items():\r\n count = 0\r\n for rank in value:\r\n # if rank was not outside 1000\r\n if rank != 1001:\r\n count += 1\r\n # if there were values for all decades add name to list\r\n if count == 11:\r\n names.append(name)\r\n names.sort()\r\n return names\r\n\r\n\r\n# return a list of names that got more popular over time\r\ndef more_popular(dictionary):\r\n names = []\r\n\r\n for name, values in dictionary.items():\r\n for i in range(len(values) - 1):\r\n # if rank of first was less than rank of second (higher rank means less popular) stop for loop\r\n if values[i] <= values[i + 1]:\r\n break\r\n # if iterated all the way to second to last one add to list\r\n # don't need to iterate to last since it would eventually go out of index by comparing i + 1\r\n if i == (len(values) - 2):\r\n names.append(name)\r\n\r\n return names\r\n\r\n\r\n# return a list of names that got less popular over time\r\ndef less_popular(dictionary):\r\n names = []\r\n\r\n for name, values in dictionary.items():\r\n for i in range(len(values) - 1):\r\n # if rank of first was greater than rank of second (lower rank means more popular) stop for loop\r\n if values[i] >= values[i + 1]:\r\n break\r\n # if iterated all the way to second to last one add to list\r\n # don't need to iterate to last since it would eventually go out of index by comparing i + 1\r\n if i == (len(values) - 2):\r\n names.append(name)\r\n return names\r\n\r\n\r\ndef main():\r\n name_dict = {}\r\n\r\n # open file\r\n infile = open(\"names.txt\", \"r\")\r\n\r\n # read file line by line\r\n for line in infile:\r\n name = line.strip().split()\r\n\r\n # iterate through list and change where element == 0 to 1001\r\n for i in range(1, len(name)):\r\n name[i] = int(name[i])\r\n if name[i] == 0:\r\n name[i] = 1001\r\n\r\n # add key value pair into empty dictionary\r\n name_dict.update({name[0]: name[1:]})\r\n\r\n infile.close()\r\n\r\n menu = True\r\n\r\n # loop menu\r\n while menu:\r\n print(\"Enter 1 to search for baby names. \")\r\n print(\"Enter 2 to display all rankings for one name.\")\r\n print(\"Enter 3 to display all names that appear in a decade.\")\r\n print(\"Enter 4 to display names that appear in all decades.\")\r\n print(\"Enter 5 to display names that are more popular in every decade.\")\r\n print(\"Enter 6 to display all names that are less popular in every decade.\")\r\n print(\"Enter 7 to quit the program.\")\r\n\r\n # try the input\r\n try:\r\n choice = int(input(\"Choose an option: \"))\r\n\r\n # if user wants to see if name is in dictionary\r\n if choice == 1:\r\n name = input(\"Enter a name to search: \").capitalize()\r\n # if search_name returns True print that the name is in dictionary\r\n if search_name(name, name_dict):\r\n year = 1900\r\n # list comprehension for finding index of value when value equals highest rank\r\n high = [i for i, value in enumerate(name_dict[name]) if value == min(name_dict[name])]\r\n # list comprehension for making a list of decades\r\n maximum = [year + index * 10 for index in high]\r\n print(\"\\nThe matches with their highest ranking decade are:\")\r\n print(name, end=' ')\r\n for number in maximum:\r\n print(number, end=' ')\r\n\r\n print()\r\n print()\r\n # if search_name returns False print that the name is not in dictionary\r\n else:\r\n print(name, \"does not appear in any decade.\\n\")\r\n\r\n # if user wants to show all data for one name\r\n elif choice == 2:\r\n name = input(\"Enter a name to search: \").capitalize()\r\n print()\r\n rank = name_rank(name, name_dict)\r\n years = [1900, 1910, 1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000]\r\n i = 0\r\n\r\n # if name is not in dictionary\r\n if not rank:\r\n print(name, \"is not in the dictionary.\")\r\n # join together list of strings from name_rank\r\n else:\r\n ranking = \" \".join(rank)\r\n name_ranking = name + \": \" + ranking\r\n print(name_ranking)\r\n\r\n # print the year and rank\r\n for year in years:\r\n print(str(year) + \": \" + rank[i])\r\n i += 1\r\n print()\r\n\r\n # if user wants to show names in order by rank for particular decade\r\n elif choice == 3:\r\n decade = int(input(\"Enter decade: \"))\r\n print(\"The names are in order of rank:\")\r\n one_decade(decade, name_dict)\r\n\r\n # if user wants names that appear during every decade\r\n elif choice == 4:\r\n all_names = all_decades(name_dict)\r\n print(len(all_names), \"names that appear in every decade. They are: \")\r\n for name in all_names:\r\n print(name)\r\n print()\r\n\r\n # if user wants the names that got more popular every decade\r\n elif choice == 5:\r\n popular = more_popular(name_dict)\r\n print(len(popular), \"names are getting more popular in every decade: \")\r\n for name in popular:\r\n print(name)\r\n print()\r\n\r\n # if user wants the names that got less popular every decade\r\n elif choice == 6:\r\n not_popular = less_popular(name_dict)\r\n print(len(not_popular), \"names are getting less popular: \")\r\n for name in not_popular:\r\n print(name)\r\n print()\r\n\r\n # if user wants to quit\r\n elif choice == 7:\r\n print(\"\\nGoodbye.\")\r\n menu = False\r\n\r\n # catch if value entered was not a number\r\n except ValueError:\r\n print(\"Not a number. Please enter a number. \\n\")\r\n\r\n\r\nmain()\r\n" }, { "alpha_fraction": 0.5293872356414795, "alphanum_fraction": 0.5458524227142334, "avg_line_length": 25.11864471435547, "blob_id": "a9ed938842d279f635e9ad67ffcf9aad6fbbf42e", "content_id": "d9109248fc40aef8ec94c53e72b2f2270809d0ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4798, "license_type": "no_license", "max_line_length": 104, "num_lines": 177, "path": "/ConvexHull.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# File: ConvexHull.py\r\n\r\n# Description: A file that takes in a list of points and returns the convex hull points of those points\r\n\r\n# Student Name: Andrew Chen\r\n\r\n# Student UT EID: ac68644\r\n\r\n# Partner Name: Saaketh Palchuru\r\n\r\n# Partner UT EID: srp2992\r\n\r\n# Course Name: CS 313E\r\n\r\n# Unique Number: 50210\r\n\r\n# Date Created: 9/25/19\r\n\r\n# Date Last Modified: 9/26/19\r\n\r\n\r\nimport math\r\n\r\n\r\nclass Point(object):\r\n # constructor\r\n def __init__(self, x=0, y=0):\r\n self.x = x\r\n self.y = y\r\n\r\n # get the distance to another Point object\r\n def dist(self, other):\r\n return math.hypot(self.x - other.x, self.y - other.y)\r\n\r\n # string representation of a Point\r\n def __str__(self):\r\n return '(' + str(self.x) + ', ' + str(self.y) + ')'\r\n\r\n # equality tests of two Points\r\n def __eq__(self, other):\r\n tol = 1.0e-8\r\n return (abs(self.x - other.x) < tol) and (abs(self.y - other.y) < tol)\r\n\r\n def __ne__(self, other):\r\n tol = 1.0e-8\r\n return (abs(self.x - other.x) >= tol) or (abs(self.y - other.y) >= tol)\r\n\r\n def __lt__(self, other):\r\n tol = 1.0e-8\r\n if abs(self.x - other.x) < tol:\r\n if abs(self.y - other.y) < tol:\r\n return False\r\n else:\r\n return self.y < other.y\r\n return self.x < other.x\r\n\r\n def __le__(self, other):\r\n tol = 1.0e-8\r\n if abs(self.x - other.x) < tol:\r\n if abs(self.y - other.y) < tol:\r\n return True\r\n else:\r\n return self.y <= other.y\r\n return self.x <= other.x\r\n\r\n def __gt__(self, other):\r\n tol = 1.0e-8\r\n if abs(self.x - other.x) < tol:\r\n if abs(self.y - other.y) < tol:\r\n return False\r\n else:\r\n return self.y > other.y\r\n return self.x > other.x\r\n\r\n def __ge__(self, other):\r\n tol = 1.0e-8\r\n if abs(self.x - other.x) < tol:\r\n if abs(self.y - other.y) < tol:\r\n return True\r\n else:\r\n return self.y >= other.y\r\n return self.x >= other.x\r\n\r\n\r\n# compute and return the determinant of the coordinates of three points\r\n# p, q, and r are Point objects\r\ndef det(p, q, r):\r\n return p.x * q.y + q.x * r.y + r.x * p.y - p.y * q.x - q.y * r.x - r.y * p.x\r\n\r\n\r\n# computes and returns the convex hull of a sorted list of Points\r\n# convex hull is a list of Point objects starting at the extreme\r\n# left point and going clockwise in order\r\ndef convex_hull(sorted_points):\r\n num_lines = len(sorted_points)\r\n upper_hull = [sorted_points[0], sorted_points[1]]\r\n\r\n for i in range(2, num_lines):\r\n upper_hull.append(sorted_points[i])\r\n while len(upper_hull) >= 3 and det(upper_hull[-3], upper_hull[-2], upper_hull[-1]) >= 0:\r\n upper_hull.pop(-2)\r\n\r\n lower_hull = [sorted_points[-1], sorted_points[-2]]\r\n\r\n for i in range(num_lines - 2, 1, -1):\r\n lower_hull.append(sorted_points[i])\r\n\r\n while len(lower_hull) >= 3 and det(lower_hull[-3], lower_hull[-2], lower_hull[-1]) >= 0:\r\n lower_hull.pop(-2)\r\n\r\n lower_hull.pop(-1)\r\n lower_hull.pop(0)\r\n\r\n for point in lower_hull:\r\n upper_hull.append(point)\r\n\r\n return upper_hull\r\n\r\n\r\n# compute and return the area of a convex polygon\r\n# convex_poly is a list of Point objects that define the vertices\r\n# of a convex polygon in order\r\ndef area_poly(convex_poly):\r\n pos_total = 0\r\n neg_total = 0\r\n\r\n convex_poly.append(convex_poly[0])\r\n\r\n for num in range(len(convex_poly) - 1):\r\n pos_total += convex_poly[num].x * convex_poly[num + 1].y\r\n\r\n neg_total += convex_poly[num].y * convex_poly[num + 1].x\r\n\r\n area = (1 / 2) * abs(pos_total - neg_total)\r\n\r\n return area\r\n\r\n\r\ndef main():\r\n # create an empty list of Point objects\r\n point_object_list = []\r\n\r\n # open file points.txt for reading\r\n file = open(\"points.txt\", 'r')\r\n num_lines = int(file.readline())\r\n\r\n # read file line by line, create Point objects and store in file\r\n for line in file:\r\n line = line.strip().split()\r\n x = int(line[0])\r\n y = int(line[1])\r\n point = Point(x, y)\r\n point_object_list.append(point)\r\n\r\n file.close()\r\n # sort the list according to x-coordinates\r\n point_object_list.sort(key=lambda point: point.x)\r\n\r\n # get the convex hull\r\n\r\n actual_hull = convex_hull(point_object_list)\r\n\r\n # print the convex hull\r\n print(\"Convex Hull\")\r\n for num in actual_hull:\r\n print(num)\r\n\r\n # get the area of the convex xull\r\n area = area_poly(actual_hull)\r\n\r\n # print the area of the convex hull\r\n print(\"\\nArea of convex hull = \", area)\r\n\r\n\r\n# YOU MUST WRITE THIS LINE AS IS\r\nif __name__ == \"__main__\":\r\n main()" }, { "alpha_fraction": 0.583791196346283, "alphanum_fraction": 0.5937009453773499, "avg_line_length": 32.555931091308594, "blob_id": "9de63feb191424c7ab739279cb86c8327139329a", "content_id": "8f25e79d39882bc320b9b9ffacebbd721460da73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10192, "license_type": "no_license", "max_line_length": 109, "num_lines": 295, "path": "/Geom.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# File: Geom.py\r\n# Description: Create classes of geometric shapes and points in OOP\r\n# Student Name: Andrew Chen\r\n# Student UT EID: ac68644\r\n# Partner Name: Saaketh Palchuru\r\n# Partner UT EID: srp2992\r\n# Course Name: CS 313E\r\n# Unique Number: 50210\r\n# Date Created: 9/16/19\r\n# Date Last Modified: 9/20/19\r\n\r\nimport math\r\n\r\n\r\nclass Point(object):\r\n # constructor\r\n # x and y are floats\r\n def __init__(self, x=0, y=0):\r\n self.x = x\r\n self.y = y\r\n\r\n # get distance\r\n # other is a Point object\r\n def dist(self, other):\r\n return math.hypot(self.x - other.x, self.y - other.y)\r\n\r\n # get a string representation of a Point object\r\n # takes no arguments\r\n # returns a string\r\n def __str__(self):\r\n return '(' + str(self.x) + \", \" + str(self.y) + \")\"\r\n\r\n # test for equality\r\n # other is a Point object\r\n # returns a Boolean\r\n def __eq__(self, other):\r\n tol = 1.0e-8\r\n return (abs(self.x - other.x) < tol) and (abs(self.y - other.y) < tol)\r\n\r\n\r\nclass Circle(object):\r\n # constructor\r\n # x, y, and radius are floats\r\n def __init__(self, radius=1, x=0, y=0):\r\n self.radius = radius\r\n self.center = Point(x, y)\r\n\r\n # compute circumference\r\n def circumference(self):\r\n return 2.0 * math.pi * self.radius\r\n\r\n # compute area\r\n def area(self):\r\n return math.pi * self.radius * self.radius\r\n\r\n # determine if point is strictly inside circle\r\n def point_inside(self, p):\r\n return self.center.dist(p) < self.radius\r\n\r\n # determine if a circle is strictly inside this circle\r\n def circle_inside(self, c):\r\n distance = self.center.dist(c.center)\r\n return (distance + c.radius) < self.radius\r\n\r\n # determine if a circle c overlaps this circle (non-zero area of overlap)\r\n # but neither is completely inside the other\r\n # the only argument c is a Circle object\r\n # returns a boolean\r\n def circle_overlap(self, c):\r\n distance = self.center.dist(c.center)\r\n return distance < (self.radius + c.radius) and not (self.circle_inside(c) or c.circle_inside(self))\r\n\r\n # determine the smallest circle that circumscribes a rectangle\r\n # the circle goes through all the vertices of the rectangle\r\n # the only argument, r, is a rectangle object\r\n def circle_circumscribe(self, r):\r\n self.radius = r.ul.dist(r.lr) / 2\r\n return Circle(self.radius, r.length() / 2, r.width() / 2)\r\n\r\n # string representation of a circle\r\n # takes no arguments and returns a string\r\n def __str__(self):\r\n return \"Radius: \" + str(self.radius) + \", Center: \" + str(self.center)\r\n\r\n # test for equality of radius\r\n # the only argument, other, is a circle\r\n # returns a boolean\r\n def __eq__(self, other):\r\n tol = 1.0e-8\r\n return abs(self.radius - other.radius) < tol\r\n\r\n\r\nclass Rectangle(object):\r\n # constructor\r\n def __init__(self, ul_x=0, ul_y=1, lr_x=1, lr_y=0):\r\n if (ul_x < lr_x) and (ul_y > lr_y):\r\n self.ul = Point(ul_x, ul_y)\r\n self.lr = Point(lr_x, lr_y)\r\n else:\r\n self.ul = Point(0, 1)\r\n self.lr = Point(1, 0)\r\n\r\n # determine length of Rectangle (distance along the x axis)\r\n # takes no arguments, returns a float\r\n def length(self):\r\n return abs(self.ul.x - self.lr.x)\r\n\r\n # determine width of Rectangle (distance along the y axis)\r\n # takes no arguments, returns a float\r\n def width(self):\r\n return abs(self.ul.y - self.lr.y)\r\n\r\n # determine the perimeter\r\n # takes no arguments, returns a float\r\n def perimeter(self):\r\n return abs(self.length() * 2 + self.width() * 2)\r\n\r\n # determine the area\r\n # takes no arguments, returns a float\r\n def area(self):\r\n return self.length() * self.width()\r\n\r\n # determine if a point is strictly inside the Rectangle\r\n # takes a point object p as an argument, returns a boolean\r\n def point_inside(self, p):\r\n return (self.ul.x < p.x < self.lr.x) and (self.lr.y < p.y < self.ul.y)\r\n\r\n # determine if another Rectangle is strictly inside this Rectangle\r\n # takes a rectangle object r as an argument, returns a boolean\r\n # should return False if self and r are equal\r\n def rectangle_inside(self, r):\r\n normalInside = self.point_inside(r.ul) and (self.point_inside(r.lr))\r\n edgeCase1 = self.ul == r.ul and (self.lr.y == r.lr.y or self.lr.x == r.lr.x)\r\n edgeCase2 = self.lr == r.lr and (self.ul.y == r.ul.y or self.ul.x == r.ul.x)\r\n return normalInside or edgeCase1 or edgeCase2\r\n # r.ul.x > self.ul.x and r.ul.y < self.ul.y and r.lr.x < self.lr.x and r.lr.y > self.lr.y\r\n\r\n # determine if two Rectangles overlap (non-zero area of overlap)\r\n # takes a rectangle object r as an argument returns a boolean\r\n def rectangle_overlap(self, r):\r\n outside = self.ul.x > r.lr.x or r.ul.x > self.lr.x or self.lr.y > r.ul.y or r.lr.y > self.ul.y\r\n edgeCase1 = self.ul == r.ul and (self.lr.y == r.lr.y or self.lr.x == r.lr.x)\r\n edgeCase2 = self.lr == r.lr and (self.ul.y == r.ul.y or self.ul.x == r.ul.x)\r\n return not(self.rectangle_inside(r) or r.rectangle_inside(self) or outside or edgeCase1 or edgeCase2)\r\n # self.lr.x <= r.ul.x or r.lr.x <= self.ul.x or self.lr.y >= r.ul.y or r.lr.y >= self.ul.y\r\n\r\n # determine the smallest rectangle that circumscribes a circle\r\n # sides of the rectangle are tangents to circle c\r\n # takes a circle object c as input and returns a rectangle object\r\n def rectangle_circumscribe(self, c):\r\n self.ul.x = c.center.x - c.radius\r\n self.ul.y = c.center.y + c.radius\r\n self.lr.x = c.center.x + c.radius\r\n self.lr.y = c.center.y - c.radius\r\n return Rectangle(self.ul.x, self.ul.y, self.lr.x, self.lr.y)\r\n\r\n # give string representation of a rectangle\r\n # takes no arguments, returns a string\r\n def __str__(self):\r\n return \"UL: \" + str(self.ul) + \", LR: \" + str(self.lr)\r\n\r\n # determine if two rectangles have the same length and width\r\n # takes a rectangle other as argument and returns a boolean\r\n def __eq__(self, other):\r\n tol = 1.0e-8\r\n return (abs(self.length() - other.length()) < tol) and (abs(self.width() - other.width()) < tol)\r\n\r\n\r\ndef main():\r\n # open the file geom.txt\r\n infile = open(\"geom.txt\", \"r\")\r\n\r\n # create Point objects P and Q\r\n my_list = []\r\n\r\n for line in infile:\r\n ind_list = []\r\n line = line.partition('#')[0]\r\n line = line.rstrip().split()\r\n for num in line:\r\n num = float(num)\r\n ind_list.append(num)\r\n my_list.append(ind_list)\r\n\r\n p = Point(my_list[0][0], my_list[0][1])\r\n q = Point(my_list[1][0], my_list[1][1])\r\n\r\n # print the coordinates of the points P and Q\r\n print(\"Coordinates of P:\", p)\r\n print(\"Coordinates of Q:\", q)\r\n\r\n # find the distance between the points P and Q\r\n print(\"Distance between P and Q:\", p.dist(q))\r\n\r\n # create two Circle objects C and D\r\n c = Circle(my_list[2][0],my_list[2][1],my_list[2][2])\r\n d = Circle(my_list[3][0],my_list[3][1],my_list[3][2])\r\n # print C and D\r\n print(\"Circle C:\", c)\r\n print(\"Circle D:\", d)\r\n\r\n # compute the circumference of C\r\n print(\"Circumference of C:\", c.circumference())\r\n\r\n # compute the area of D\r\n print(\"Area of D:\", d.area())\r\n\r\n # determine if P is strictly inside C\r\n if c.point_inside(p):\r\n print(\"P is inside C.\")\r\n else:\r\n print(\"P is not inside C.\")\r\n\r\n # determine if C is strictly inside D\r\n if d.circle_inside(c):\r\n print(\"C is inside D.\")\r\n else:\r\n print(\"C is not inside D.\")\r\n\r\n # determine if C and D intersect (non zero area of intersection)\r\n if c.circle_overlap(d):\r\n print(\"C does intersect D.\")\r\n else:\r\n print(\"C does not intersect D.\")\r\n\r\n # determine if C and D are equal (have the same radius)\r\n if c.__eq__(d):\r\n print(\"C is equal to D.\")\r\n else:\r\n print(\"C is not equal to D.\")\r\n\r\n # create two rectangle objects G and H\r\n g = Rectangle(my_list[4][0],my_list[4][1],my_list[4][2],my_list[4][3])\r\n h = Rectangle(my_list[5][0],my_list[5][1],my_list[5][2],my_list[5][3])\r\n\r\n # print the two rectangles G and H\r\n print(\"Rectangle G:\", g)\r\n print(\"Rectangle H:\", h)\r\n\r\n # determine the length of G (distance along x axis)\r\n print(\":ength of G:\", g.length())\r\n\r\n # determine the width of H (distance along y axis)\r\n print(\"Width of H:\", h.width())\r\n\r\n # determine the perimeter of G\r\n print(\"Perimeter of G:\", g.perimeter())\r\n\r\n # determine the area of H\r\n print(\"Area of H:\", h.area())\r\n\r\n # determine if point P is strictly inside rectangle G\r\n if g.point_inside(p):\r\n print(\"P is inside G.\")\r\n else:\r\n print(\"P is not inside G.\")\r\n\r\n # determine if rectangle G is strictly inside rectangle H\r\n if h.rectangle_inside(g):\r\n print(\"G is inside H.\")\r\n else:\r\n print(\"G is not inside H.\")\r\n\r\n # determine if rectangles G and H overlap (non-zero area of overlap)\r\n if g.rectangle_overlap(h):\r\n print(\"G does not overlap H.\")\r\n else:\r\n print(\"G does overlap H.\")\r\n\r\n # find the smallest circle that circumscribes rectangle G\r\n # goes through the four vertices of the rectangle\r\n a = Circle()\r\n print(\"Circle that circumscribes rectangle G:\", a.circle_circumscribe(g))\r\n\r\n # find the smallest rectangle that circumscribes circle D\r\n # all four sides of the rectangle are tangents to the circle\r\n b = Rectangle()\r\n print(\"Rectangle that circumscribes circle D:\", b.rectangle_circumscribe(d))\r\n\r\n # determine if the two rectangles have the same length and width\r\n if g.__eq__(h):\r\n print(\"Rectangle G is equal to H.\")\r\n else:\r\n print(\"Rectangle G is not equal to H.\")\r\n\r\n # close the file geom.txt\r\n infile.close()\r\n\r\n\r\n# This line above main is for grading purposes. It will not affect how\r\n# your code will run while you develop and test it.\r\n# DO NOT REMOVE THE LINE ABOVE MAIN\r\nif __name__ == \"__main__\":\r\n main()\r\nk" }, { "alpha_fraction": 0.5623376369476318, "alphanum_fraction": 0.5753246545791626, "avg_line_length": 28.19607925415039, "blob_id": "83b58321ec9d5618313afaee3a04c2900bc69dd0", "content_id": "ee7b33550a7b61fb9a8150153aa68be39d4a8298", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1540, "license_type": "no_license", "max_line_length": 80, "num_lines": 51, "path": "/Point.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# think of 10 neighbors handshaking each other, there are 45 total handshakes\r\n\r\nimport math\r\n\r\n\r\nclass Point(object):\r\n # constructor\r\n def __init__(self, x=0, y=0):\r\n self.x = x\r\n self.y = y\r\n\r\n # get the distance to another Point object\r\n def dist(self, other):\r\n return math.hypot(self.x - other.x, self.y - other.y)\r\n\r\n # string representation of a Point\r\n def __str__(self):\r\n return '(' + str(self.x) + ', ' + str(self.y) + ')'\r\n\r\n # test for equality of two Point objects\r\n def __eq__(self, other):\r\n tol = 1.0e-16\r\n return ((abs(self.x - other.x) < tol) and (abs(self.y - other.y) < tol))\r\n\r\n\r\ndef main():\r\n # create an empty list of Point objects\r\n points = []\r\n # open file points.txt for reading\r\n infile = open(\"points.txt\", \"r\")\r\n # read the file line by line, create Point objects and add to the list\r\n for line in infile:\r\n n = line.strip().split()\r\n point = Point(int(n[0]), int(n[1]))\r\n points.append(point)\r\n\r\n # initialize a variable to hold the shortest distance\r\n shortest = 999999\r\n # Use a pair of nested loops to go through all pairs of Point objects\r\n for i in range(len(points)):\r\n for j in range(len(points) - 1):\r\n distance = (points[i].dist(points[j]))\r\n\r\n # Find the minimum distance between all pairs\r\n if distance < shortest and distance != 0:\r\n shortest = distance\r\n # print the shortest distance\r\n print(shortest)\r\n\r\n\r\nmain()\r\n" }, { "alpha_fraction": 0.5270336270332336, "alphanum_fraction": 0.5523623824119568, "avg_line_length": 23.060976028442383, "blob_id": "f02b679e62a9faab9f7cf5a4b7b034e990988e75", "content_id": "c54e038523e792b149f0d20507a24228be829929", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2053, "license_type": "no_license", "max_line_length": 118, "num_lines": 82, "path": "/Grid.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# File: Grid.py\r\n\r\n# Description: Recursion\r\n\r\n# Student Name: Andrew Chen\r\n\r\n# Student UT EID: ac68644\r\n\r\n# Partner Name: Saaketh Palchuru\r\n\r\n# Partner UT EID: srp2992\r\n\r\n# Course Name: CS 313E\r\n\r\n# Unique Number: 50210\r\n\r\n# Date Created: 10/10/19\r\n\r\n# Date Last Modified: 10/12/19\r\n\r\n\r\n# counts all the possible paths in a grid recursively\r\ndef count_paths(n, row, col):\r\n if row == n-1 and col == n-1:\r\n return 1\r\n elif row == n-1:\r\n return count_paths(n, row, col + 1)\r\n elif col == n-1:\r\n return count_paths(n, row + 1, col)\r\n else:\r\n return count_paths(n, row + 1, col) + count_paths(n, row, col + 1)\r\n\r\n\r\n# recursively gets the greatest sum of all the paths in the grid\r\ndef path_sum(grid, n, row, col):\r\n if row == n-1 and col == n-1:\r\n return grid[row][col]\r\n elif row == n-1:\r\n return grid[row][col] + path_sum(grid, n, row, col + 1)\r\n elif col == n-1:\r\n return grid[row][col] + path_sum(grid, n, row + 1, col)\r\n else:\r\n return max(grid[row][col] + path_sum(grid, n, row + 1, col), grid[row][col] + path_sum(grid, n, row, col + 1))\r\n\r\n\r\ndef main():\r\n # open file for reading\r\n in_file = open (\"grid.txt\", \"r\")\r\n\r\n # read the dimension of the grid\r\n dim = in_file.readline()\r\n dim = dim.strip()\r\n dim = int(dim)\r\n\r\n # create an empty grid\r\n grid = []\r\n\r\n # populate the grid\r\n for i in range (dim):\r\n line = in_file.readline()\r\n line = line.strip()\r\n row = line.split()\r\n for j in range (dim):\r\n row[j] = int (row[j])\r\n grid.append(row)\r\n\r\n # close the file\r\n in_file.close()\r\n\r\n # get the number of paths in the grid and print\r\n num_paths = count_paths (dim, 0, 0)\r\n print ('Number of paths in a grid of dimension', dim, 'is', num_paths)\r\n print ()\r\n\r\n # get the maximum path sum and print\r\n max_path_sum = path_sum (grid, dim, 0, 0)\r\n print ('Greatest path sum is', max_path_sum)\r\n\r\n path = path_sum_helper(grid, dim, 0, 0, path_list)\r\n print(path)\r\n\r\nmain()" }, { "alpha_fraction": 0.6159680485725403, "alphanum_fraction": 0.6323353052139282, "avg_line_length": 27.821428298950195, "blob_id": "6db11088b1d856dd4dba3a09fcce93a7aa5e73e2", "content_id": "e3a7d8dc9e037ffb9e0d96ae13a63518936f7ae4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2505, "license_type": "no_license", "max_line_length": 80, "num_lines": 84, "path": "/Intervals.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# File: Intervals.py\r\n# Description: Collapse intersecting intervals in a text file\r\n# Student Name: Andrew Chen\r\n# Student UT EID: ac68644\r\n# Partner Name: Saaketh Palchuru\r\n# Partner UT EID: srp2992\r\n# Course Name: CS 313Ez\r\n# Unique Number: 50210\r\n# Date Created: 9/5/19\r\n# Date Last Modified: 9/9/19\r\n\r\n\r\ndef createList(file):\r\n\r\n interval_list = []\r\n\r\n # get rid of whitespace and make strings into lists\r\n for line in file:\r\n if not line.strip():\r\n continue\r\n num = line.strip().split()\r\n interval_list.append(num)\r\n # make strings into ints in 2-D list\r\n interval_list = [[int(string) for string in line] for line in interval_list]\r\n print(interval_list)\r\n # make tuples out of intervals in 2-D list\r\n tuple_list = [tuple(interval) for interval in interval_list]\r\n print(tuple_list)\r\n # sort the tuples in 2-D list\r\n sorted_list = sorted(tuple_list)\r\n print(sorted_list)\r\n\r\n return sorted_list\r\n\r\n\r\ndef collapseInterval(tuple_list):\r\n # establish list with first interval to compare\r\n collapsed_list = [tuple_list[0]]\r\n print(collapsed_list)\r\n\r\n for next_int in tuple_list:\r\n first = collapsed_list[-1]\r\n # if next interval is already inside the current interval, continue\r\n if next_int[0] >= first[0] and next_int[1] <= first[1]:\r\n continue\r\n # if next interval is partially outside the current interval,\r\n # make a new interval and assign that as current interval\r\n elif next_int[0] <= first[1]:\r\n # list literal\r\n new_interval = [first[0], next_int[1]]\r\n collapsed_list[-1] = tuple(new_interval)\r\n # if next interval cannot be collapsed add that to collapsed_list\r\n else:\r\n collapsed_list.append(next_int)\r\n\r\n return collapsed_list\r\n\r\n\r\ndef printCollapsedList(collapsed_list):\r\n # print out tuples in collapsed list every line\r\n print(\"Non-intersecting Intervals:\")\r\n for tup in collapsed_list:\r\n print(tup)\r\n\r\n\r\ndef printSizeList(collapsed_list):\r\n\r\n collapsed_list.sort(key=lambda interval: abs(interval[0] - interval[1]))\r\n print(\"Non-intersecting Intervals in order of size:\")\r\n for tup in collapsed_list:\r\n print(tup)\r\n\r\n\r\ndef main():\r\n input_file = open(\"Intervals.txt\", \"r\")\r\n first_list = createList(input_file)\r\n second_list = collapseInterval(first_list)\r\n printCollapsedList(second_list)\r\n print()\r\n printSizeList(second_list)\r\n\r\n\r\n\r\nmain()\r\n" }, { "alpha_fraction": 0.6176470518112183, "alphanum_fraction": 0.7941176295280457, "avg_line_length": 16, "blob_id": "3953dcd20ad8e0e57c952620e7ad9990f1fd2cf8", "content_id": "c492622c7bd60820de86f496f032c5a7ea3b0a16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 34, "license_type": "no_license", "max_line_length": 24, "num_lines": 2, "path": "/README.md", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# CS313E\nPrograms done for CS313E\n" }, { "alpha_fraction": 0.6028188467025757, "alphanum_fraction": 0.6152957677841187, "avg_line_length": 29.36231803894043, "blob_id": "4d6c4fb74f14b206f507f5b7db637d917fe32781", "content_id": "20d634d68a8dd119c9fadb13e2997de9d3bd1977", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4328, "license_type": "no_license", "max_line_length": 119, "num_lines": 138, "path": "/Triangle.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# File: Triangle.py\r\n\r\n# Description: Use brute force, greedy, divide & conquer, and dynamic programming algorithms to find greatest sum path\r\n\r\n# Student's Name: Andrew Chen\r\n\r\n# Student's UT EID: ac68644\r\n\r\n# Partner's Name: Edoardo Palazzi\r\n\r\n# Partner's UT EID: emp2587\r\n\r\n# Course Name: CS 313E\r\n\r\n# Unique Number: 50210\r\n\r\n# Date Created: 12/3/19\r\n\r\n# Date Last Modified: 12/7/19\r\n\r\nimport time\r\n\r\n\r\n# returns the greatest path sum using exhaustive search\r\ndef exhaustive_search(grid):\r\n sums = []\r\n exhaustive_search_helper(grid, 0, 0, sums, 0)\r\n return max(sums)\r\n\r\n\r\ndef exhaustive_search_helper(grid, row, col, sums, value):\r\n if row == len(grid):\r\n sums.append(value)\r\n return\r\n else:\r\n exhaustive_search_helper(grid, row + 1, col, sums, value + grid[row][col])\r\n exhaustive_search_helper(grid, row + 1, col + 1, sums, value + grid[row][col])\r\n\r\n\r\n# returns the greatest path sum using greedy approach\r\ndef greedy(grid):\r\n greed_sum = grid[0][0]\r\n index = 0\r\n for i in range(1, len(grid)):\r\n if grid[i][index + 1] > grid[i][index]:\r\n index += 1\r\n greed_sum += grid[i][index]\r\n return greed_sum\r\n\r\n\r\n# returns the greatest path sum using divide and conquer (recursive) approach\r\ndef rec_search(grid):\r\n left = 0\r\n right = 0\r\n return divide_and_conquer(grid, left, right)\r\n\r\n\r\ndef divide_and_conquer(grid, row, col):\r\n # if at the end return the value at the end\r\n if row == len(grid) - 1:\r\n return grid[row][col]\r\n else:\r\n # add the first and the max of each recursive call going down triangle\r\n return grid[row][col] + max(divide_and_conquer(grid, row + 1, col), divide_and_conquer(grid, row + 1, col + 1))\r\n\r\n\r\n# returns the greatest path sum and the new grid using dynamic programming\r\ndef dynamic_prog(grid):\r\n # bottom up approach starting from second to last row\r\n for i in range(len(grid) - 2, -1, -1):\r\n # go through each column and add max of either the one below or the one next to it\r\n for j in range(len(grid[i])):\r\n grid[i][j] += max(grid[i + 1][j], grid[i + 1][j + 1])\r\n # eventually the max will be at the top\r\n return grid[0][0]\r\n\r\n\r\n# reads the file and returns a 2-D list that represents the triangle\r\ndef read_file():\r\n # read triangular grid from file\r\n infile = open('triangle.txt', 'r')\r\n triangle = []\r\n\r\n # we don't really need the first line, so throw it out\r\n num = int(infile.readline())\r\n\r\n # build our triangle\r\n for i in range(num):\r\n line = infile.readline()\r\n line = line.strip().split()\r\n for j in range(len(line)):\r\n line[j] = int(line[j])\r\n triangle.append(line)\r\n # close file\r\n infile.close()\r\n\r\n return triangle\r\n\r\n\r\ndef main():\r\n # read triangular grid from file\r\n triangle = read_file()\r\n\r\n ti = time.time()\r\n # output greatest path from exhaustive search\r\n print('The greatest path sum through exhaustive search is ' + str(exhaustive_search(triangle)) + '.')\r\n tf = time.time()\r\n del_t = tf - ti\r\n # print time taken using exhaustive search\r\n print('The time taken for exhaustive approach is ' + str(del_t) + ' seconds.\\n')\r\n\r\n ti = time.time()\r\n # output greatest path from greedy approach\r\n print('The greatest path sum through greedy search is ' + str(greedy(triangle)) + '.')\r\n tf = time.time()\r\n del_t = tf - ti\r\n # print time taken using greedy approach\r\n print('The time taken for greedy approach is ' + str(del_t) + ' seconds.\\n')\r\n\r\n ti = time.time()\r\n # output greatest path from divide-and-conquer approach\r\n print('The greatest path sum through recursive search is ' + str(rec_search(triangle)) + '.')\r\n tf = time.time()\r\n del_t = tf - ti\r\n # print time taken using divide-and-conquer approach\r\n print('The time taken for recursive search is ' + str(del_t) + ' seconds.\\n')\r\n\r\n ti = time.time()\r\n # output greatest path from dynamic programming\r\n print('The greatest path sum through dynamic programming is ' + str(dynamic_prog(triangle)) + '.')\r\n tf = time.time()\r\n del_t = tf - ti\r\n # print time taken using dynamic programming\r\n print('The time taken for dynamic programming is ' + str(del_t) + ' seconds.')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n" }, { "alpha_fraction": 0.55255126953125, "alphanum_fraction": 0.56365966796875, "avg_line_length": 37.0047607421875, "blob_id": "d55475b3f630f1ce7411cf27c29b4d4f0252e121", "content_id": "da281a032dca6a90f305d9386e3cb9c914439688", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16384, "license_type": "no_license", "max_line_length": 119, "num_lines": 420, "path": "/WordSearch.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# File: WordSearch.py\r\n# Description: A program that finds words in a nxn matrix and returns the index position of the word into a text file\r\n# Student Name: Andrew Chen\r\n# Student UT EID: ac68644\r\n# Partner Name: Saaketh Palchuru\r\n# Partner UT EID: srp2992\r\n# Course Name: CS 313E\r\n# Unique Number: 50210\r\n# Date Created: 9/9/19\r\n# Date Last Modified: 9/16/19\r\n\r\n\r\n# creates strings of each row of the matrix for other functions to find the word\r\ndef make_strings(matrix):\r\n row_list = []\r\n # joins together each letter of the row into one spot of a list\r\n for row in matrix:\r\n temp_row = ''.join(row)\r\n row_list.append(temp_row)\r\n return row_list\r\n\r\n\r\n# read the file and makes dimensions, a list out of the word search, and a list out of the words to be found\r\ndef make_list():\r\n # read file and get dimensions\r\n file = open(\"hidden.txt\", 'r')\r\n first_line = file.readline()\r\n dimensions = first_line.strip().split()\r\n file.readline()\r\n\r\n i = 0\r\n word_matrix = []\r\n # read word search and turn into a list\r\n while i < int(dimensions[0]):\r\n line = file.readline()\r\n line = line.strip().split()\r\n word_matrix.append(line)\r\n i += 1\r\n\r\n file.readline()\r\n # number of words to be found\r\n number_of_words = file.readline()\r\n number_of_words = int(number_of_words)\r\n\r\n word_list = []\r\n # put words to be found into a list\r\n for i in range(number_of_words):\r\n line = file.readline().strip()\r\n word_list.append(line)\r\n\r\n file.close()\r\n\r\n return dimensions, word_matrix, word_list\r\n\r\n\r\n# find word inside a row going one way\r\ndef row_finder(row_matrix, words):\r\n # make strings for rows in word search\r\n row_list = make_strings(row_matrix)\r\n\r\n found_words_row = []\r\n # go through words needed to be found\r\n for word in words:\r\n i = 0\r\n # go through the strings made from make_strings\r\n for string in row_list:\r\n # if word is there .find returns index and append word, i + 1 for row, index + 1 for columns\r\n if string.find(word) != -1:\r\n index = string.find(word)\r\n found_words_row.append(word)\r\n found_words_row.append(i + 1)\r\n found_words_row.append(index + 1)\r\n i += 1\r\n return found_words_row\r\n\r\n\r\n# find word inside the strings going the other way\r\ndef backwards_row_finder(row_matrix, words):\r\n # make strings for row in word search\r\n row_list = make_strings(row_matrix)\r\n\r\n # reverse the words that need to be found\r\n reversed_found_words_row = []\r\n reverse_word_list = [word[::-1] for word in words]\r\n\r\n # go through words that are reversed\r\n for word in reverse_word_list:\r\n i = 0\r\n # go through strings made from make_strings\r\n for string in row_list:\r\n # if word is found, add original word, row found + 1, and index + length of word\r\n if string.find(word) != -1:\r\n index = string.find(word)\r\n reversed_found_words_row.append(word[::-1])\r\n reversed_found_words_row.append(i + 1)\r\n reversed_found_words_row.append(index + len(word))\r\n i += 1\r\n return reversed_found_words_row\r\n\r\n\r\n# make the strings necessary to find words in columns\r\ndef make_column_matrix(beginning_matrix):\r\n col_list = []\r\n\r\n # iterate for how long word seach is\r\n for i in range(len(beginning_matrix)):\r\n col = []\r\n # append the i index element of each row\r\n for row in beginning_matrix:\r\n col.append(row[i])\r\n\r\n # append the row of column indexes into col_list\r\n col_list.append(col)\r\n\r\n return col_list\r\n\r\n\r\n# find words in the columns\r\ndef col_finder(col_matrix, words):\r\n # make strings out of column list\r\n col_list = make_strings(col_matrix)\r\n\r\n found_words_column = []\r\n found_words_column = []\r\n # iterate through words needed to be found\r\n for word in words:\r\n i = 0\r\n # iterate through the strings in the list\r\n for string in col_list:\r\n # if found append the word, the index + 1, and i + 1 for row and columns\r\n if string.find(word) != -1:\r\n index = string.find(word)\r\n found_words_column.append(word)\r\n found_words_column.append(index + 1)\r\n found_words_column.append(i + 1)\r\n i += 1\r\n return found_words_column\r\n\r\n\r\n# find the words in columns going the other way\r\ndef backwards_col_finder(col_matrix, words):\r\n # make strings out of columns\r\n col_list = make_strings(col_matrix)\r\n # reverse words to be find\r\n reversed_found_words_row = []\r\n reverse_word_list = [word[::-1] for word in words]\r\n\r\n # go through each reversed word to find\r\n for word in reverse_word_list:\r\n i = 0\r\n # go through strings for columns in word search\r\n for string in col_list:\r\n # if found append the original word, index + length of word for row, and i + 1 for columns\r\n if string.find(word) != -1:\r\n index = string.find(word)\r\n reversed_found_words_row.append(word[::-1])\r\n reversed_found_words_row.append(index + len(word))\r\n reversed_found_words_row.append(i + 1)\r\n i += 1\r\n return reversed_found_words_row\r\n\r\n\r\n# finds words going on diagonals from bottom left to top right\r\ndef diagonal_creator(big_matrix, words):\r\n # number of rows and length of rows\r\n length, row_length = len(big_matrix), len(big_matrix[0])\r\n\r\n diagonal_list = []\r\n # iterate for length of n x n -1\r\n for p in range(length + row_length - 1):\r\n inner_list = []\r\n # iterate for range from max of p - length + 1 or 0 to minimum of p + 1 or row length and append the element\r\n for q in range(max(p - length + 1, 0), min(p + 1, row_length)):\r\n inner_list.append(big_matrix[length - p + q - 1][q])\r\n # append list of diagonal elements into diagonal list\r\n diagonal_list.append(inner_list)\r\n\r\n row_list = make_strings(diagonal_list)\r\n found_words = []\r\n # iterate through words to find\r\n for word in words:\r\n counter = len(big_matrix)\r\n diff_counter = 1\r\n i = 0\r\n # iterate through strings made\r\n for string in row_list:\r\n # if i goes over half of matrix start adding onto different counter\r\n if i > (len(row_list) // 2):\r\n diff_counter += 1\r\n # if word is found\r\n if string.find(word) != -1:\r\n # if word was before or at the half diagonal of the list\r\n # append the word, counter + j_pos for i, and j_pos + 1\r\n if i <= (len(row_list) // 2):\r\n j_pos = string.find(word)\r\n found_words.append(word)\r\n found_words.append(counter + j_pos)\r\n found_words.append(j_pos + 1)\r\n # if word was after the half diagonal of the list\r\n # append the word, i_pos + 1 for i, and diff_counter + i_pos for j\r\n else:\r\n i_pos = string.find(word)\r\n found_words.append(word)\r\n found_words.append(i_pos + 1)\r\n found_words.append(diff_counter + i_pos)\r\n i += 1\r\n counter -= 1\r\n\r\n return found_words\r\n\r\n\r\n# finds words going on diagonals from left to right backwards\r\ndef reverse_diagonal_creator(big_matrix, words):\r\n # reverse the words to find\r\n reverse_word_list = [word[::-1] for word in words]\r\n # length of matrix and length of row\r\n length, row_length = len(big_matrix), len(big_matrix[0])\r\n\r\n diagonal_list = []\r\n # iterate through p which is from the range of n x n matrix - 1\r\n for p in range(length + row_length - 1):\r\n inner_list = []\r\n # iterate through q which is the max of p - length of matrix +1 or 0 to the minimum of p + 1 or row_length\r\n # and append the element at [length - p + 1 - 1] [q]\r\n for q in range(max(p - length + 1, 0), min(p + 1, row_length)):\r\n inner_list.append(big_matrix[length - p + q - 1][q])\r\n\r\n diagonal_list.append(inner_list)\r\n\r\n # make strings out of diaognal_list\r\n row_list = make_strings(diagonal_list)\r\n\r\n found_words = []\r\n # iterate through the reversed list\r\n for word in reverse_word_list:\r\n counter = len(big_matrix)\r\n diff_counter = 1\r\n i = 0\r\n # iterate through string list\r\n for string in row_list:\r\n # if row is greater than half of the diagonals add to counter\r\n if i > (len(row_list) // 2):\r\n diff_counter += 1\r\n # if string is found\r\n if string.find(word) != -1:\r\n # if word was found before or at the half of the diagonals\r\n # append the original word, coumter + index of find + len(word -1 for row\r\n # and j_pos + len(word_ for column\r\n if i <= (len(row_list) // 2):\r\n j_pos = string.find(word)\r\n found_words.append(word[::-1])\r\n found_words.append(counter + j_pos + len(word) - 1)\r\n found_words.append(j_pos + len(word))\r\n # if word was found after the half of the diagonals append the original word,\r\n # index of find + length of word for row, and counter + index of find + length of word -1 for column\r\n else:\r\n i_pos = string.find(word)\r\n found_words.append(word[::-1])\r\n found_words.append(i_pos + len(word))\r\n found_words.append(diff_counter + i_pos + len(word) - 1)\r\n i += 1\r\n counter -= 1\r\n\r\n return found_words\r\n\r\n\r\n# get the diagonals from top left to bottom right\r\ndef anti_diag(big_matrix, words):\r\n # length of matrix and of row\r\n length, row_length = len(big_matrix), len(big_matrix[0])\r\n\r\n diagonal_list = []\r\n # iterate through p which p is equal to range n + n -1\r\n for p in range(length + row_length - 1):\r\n inner_list = []\r\n # iterate through q which q is equal to the range from max of p - length + 1 or 0\r\n # and min of p + 1 and length of row\r\n for q in range(max(p - length + 1, 0), min(p + 1, row_length)):\r\n inner_list.append(big_matrix[p - q][q])\r\n diagonal_list.append(inner_list)\r\n\r\n # make strings out of diagonal list\r\n row_list = make_strings(diagonal_list)\r\n\r\n found_words = []\r\n # iterate through words to find\r\n for word in words:\r\n counter = 0\r\n diff_counter = 1\r\n i = 0\r\n # iterate through strings in list\r\n for string in row_list:\r\n # if counter is greater than the diagonal at half start adding counter\r\n if i > (len(row_list) // 2):\r\n diff_counter += 1\r\n # if word is found\r\n if string.find(word) != -1:\r\n # if it is found before the half then append the word, counter - index of find + 1 for row,\r\n # and index of find + 1 for column\r\n if i <= (len(row_list) // 2):\r\n j_pos = string.find(word)\r\n found_words.append(word)\r\n found_words.append(counter - j_pos + 1)\r\n found_words.append(j_pos + 1)\r\n # append the word, length of the matrix - index of find for row, and counter + index of find for column\r\n else:\r\n i_pos = string.find(word)\r\n found_words.append(word)\r\n found_words.append(len(big_matrix) - i_pos)\r\n found_words.append(diff_counter + i_pos)\r\n i += 1\r\n counter += 1\r\n\r\n return found_words\r\n\r\n\r\n# get the diagonals from top left to bottom right going the other way\r\ndef reverse_anti_diag(big_matrix, words):\r\n reverse_word_list = [word[::-1] for word in words]\r\n\r\n # length of matrix and of row\r\n length, row_length = len(big_matrix), len(big_matrix[0])\r\n\r\n diagonal_list = []\r\n\r\n # iterate through p which is the range from n + n -1\r\n for p in range(length + row_length - 1):\r\n inner_list = []\r\n # iterate though q which is the range from the max of p = length + 1 or 0 to the min of p + 1 or row_length\r\n for q in range(max(p - length + 1, 0), min(p + 1, row_length)):\r\n inner_list.append(big_matrix[p - q][q])\r\n diagonal_list.append(inner_list)\r\n # make strings out of the diagonal list\r\n row_list = make_strings(diagonal_list)\r\n\r\n found_words = []\r\n # iterate through reversed words to find\r\n for word in reverse_word_list:\r\n counter = 0\r\n second_counter = 1\r\n diff_counter = 1\r\n i = 0\r\n # iterate through strings in row list\r\n for string in row_list:\r\n # after going over half of the diagonals start counter\r\n if i > (len(row_list) // 2):\r\n diff_counter += 1\r\n # if word is found\r\n if string.find(word) != -1:\r\n # if word was found before or at helf append the original word,\r\n # counter - index of find - length of word + 2 for row, and index of find + length of word for column\r\n if i <= (len(row_list) // 2):\r\n j_pos = string.find(word)\r\n found_words.append(word[::-1])\r\n found_words.append(counter - j_pos - len(word) + 2)\r\n found_words.append(j_pos + len(word))\r\n # if word was found after the half append the original word, the other counter - length of the word -\r\n # index of find - counter after half + 2 for row, and other counter - length of matrix + index of find\r\n # + length of the word for column\r\n else:\r\n i_pos = string.find(word)\r\n found_words.append(word[::-1])\r\n found_words.append(second_counter - len(word) - i_pos - diff_counter + 2)\r\n found_words.append(second_counter - length + i_pos + len(word))\r\n i += 1\r\n counter += 1\r\n second_counter += 1\r\n\r\n return found_words\r\n\r\n\r\ndef output_file(searched_list, words):\r\n # split the list into three lists of word, row index, and column index\r\n found_words = searched_list[0::3]\r\n found_words_i = searched_list[1::3]\r\n found_words_j = searched_list[2::3]\r\n\r\n # if a word was not found append it to the end of the word list\r\n words_not_found = []\r\n for word in words:\r\n if word not in found_words:\r\n words_not_found.append(word)\r\n\r\n # append 0, 0 for every word that was not found\r\n for x in range(len(words_not_found)):\r\n found_words_i.append(0)\r\n found_words_j.append(0)\r\n\r\n # add both word lists together\r\n final_words = found_words + words_not_found\r\n # make a 2-D list out of each word, row, and column again then sort it by word\r\n final_matrix = []\r\n for i in range(len(final_words)):\r\n final_matrix.append([final_words[i], str(found_words_i[i]), str(found_words_j[i])])\r\n sorted_final_matrix = sorted(final_matrix, key=lambda word:word[0])\r\n\r\n # write to the file and format\r\n outfile = open(\"found.txt\", \"w\")\r\n for i in range(len(sorted_final_matrix)):\r\n outfile.write(\"{:<12}\".format(sorted_final_matrix[i][0]) + \"%5s\" % sorted_final_matrix[i][1] +\r\n \"%5s\" % sorted_final_matrix[i][2] + \"\\n\")\r\n\r\n\r\ndef main():\r\n dimension, word_matrix, word_list = make_list()\r\n row = row_finder(word_matrix, word_list)\r\n back_row = backwards_row_finder(word_matrix, word_list)\r\n make_col = make_column_matrix(word_matrix)\r\n col = col_finder(make_col, word_list)\r\n back_col = backwards_col_finder(make_col, word_list)\r\n diag1 = diagonal_creator(word_matrix, word_list)\r\n diag2 = reverse_diagonal_creator(word_matrix, word_list)\r\n diag3 = anti_diag(word_matrix, word_list)\r\n diag4 = reverse_anti_diag(word_matrix, word_list)\r\n\r\n total = row + back_row + col+ back_col+ diag1 + diag2 + diag3 + diag4\r\n output_file(total, word_list)\r\n\r\n\r\nmain()\r\n\r\n" }, { "alpha_fraction": 0.5970020890235901, "alphanum_fraction": 0.6113025546073914, "avg_line_length": 35.445159912109375, "blob_id": "b3e7ee3c5773ffb431047c4baf592dabcf3b64cf", "content_id": "7e863033d96e698f816317e6e1c05002c0dddc13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5804, "license_type": "no_license", "max_line_length": 127, "num_lines": 155, "path": "/MagicSquare.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# File: MagicSquare.py\r\n# Description: Create an odd NxN magic square using a 2-D list\r\n# Student's Name: Andrew Chen\r\n# Student's UT EID: ac68644\r\n# Partner's Name: Saaketh Palchuru\r\n# Partner's UT EID: srp2992\r\n# Course Name: CS 313E\r\n# Unique Number: 50210\r\n# Date Created: 9/1/19\r\n# Date Last Modified: 9/5/19\r\n\r\n# Create the 2-D list that will be a magic square\r\ndef make_square(n):\r\n # make a matrix NxN that is filled with 0's\r\n my_nested_list = [[0 for i in range(n)] for i in range(n)]\r\n\r\n # create coordinates for the first value of '1' to be placed in and create the number that will be placed there\r\n x_counter = len(my_nested_list) - 1\r\n y_counter = int(len(my_nested_list) / 2)\r\n number_counter = 1\r\n\r\n # fill the matrix with the first number\r\n my_nested_list[x_counter][y_counter] = number_counter\r\n\r\n # make sure the number counter only goes up to how many ever spots are in the square\r\n while number_counter < (n * n):\r\n # start by adding 1 to each coordinate and the number value then run through loops to check where to put the number\r\n x_counter += 1\r\n y_counter += 1\r\n number_counter += 1\r\n\r\n # apply the logical rules to the square: always go down and to the right and wrap around if ouside the box and go above\r\n # if diagonally down or a number is already there. Wrap arounds are accomplsohed by setting the x or y coordinate to 0\r\n\r\n if x_counter not in range(0, len(my_nested_list)) and y_counter not in range(0, len(my_nested_list[0])):\r\n x_counter -= 2\r\n y_counter -= 1\r\n elif x_counter not in range(0, len(my_nested_list)):\r\n x_counter = 0\r\n elif y_counter not in range(0, len(my_nested_list[0])):\r\n y_counter = 0\r\n elif my_nested_list[x_counter][y_counter] != 0:\r\n x_counter -= 2\r\n y_counter -= 1\r\n my_nested_list[x_counter][y_counter] = number_counter\r\n\r\n return my_nested_list\r\n\r\n\r\ndef print_square(magic_square):\r\n # print the magic square in a clean format that is 6 units apart for each number\r\n length = len(magic_square[0])\r\n print(\"\\nHere is a\", length, \"by\", length, \"matrix: \\n\")\r\n print('\\n'.join([''.join(['{:6}'.format(num) for num in data])\r\n for data in magic_square]))\r\n\r\n\r\ndef check_square(magic_square):\r\n # initialize several variables and lists to be used in the checking of the squares rows, columns, and diagonals\r\n row_sum = False\r\n col_sum = False\r\n diag_sum = False\r\n row_length = len(magic_square[0])\r\n col_length = len(magic_square)\r\n row_sum_list = []\r\n col_sum_list = []\r\n diag_sum_list = []\r\n\r\n # add the sum of each row to a list to be used later\r\n for row in magic_square:\r\n row_sum_list.append(sum(row))\r\n\r\n # add the sum of each column to a list to be used later\r\n col_sum_list = [sum(x) for x in zip(*magic_square)]\r\n\r\n # initialize variables for the diagonal test\r\n diag_total = 0\r\n reverse_diag_total = 0\r\n reverse_diag_width = 0\r\n reverse_diag_column = -1\r\n\r\n # append each number along the inital diagonal (0,0), (1,1), (2,2) to a list for later use\r\n for num in range(len(magic_square)):\r\n diag_total += magic_square[num][num]\r\n diag_sum_list.append(diag_total)\r\n\r\n # same as above but the other diagonal\r\n for num in range(len(magic_square)):\r\n reverse_diag_total += magic_square[reverse_diag_width][reverse_diag_column]\r\n reverse_diag_width += 1\r\n reverse_diag_column -= 1\r\n diag_sum_list.append(reverse_diag_total)\r\n\r\n # set up a temporary variable that equals the first number of the first row\r\n rTemp = row_sum_list[0]\r\n\r\n # check if this first item is equal to all the other items in the row_sum_list from earlier, if they\r\n # all are change row_sum to True\r\n for item in row_sum_list:\r\n if rTemp != item:\r\n row_sum = False\r\n break;\r\n else:\r\n row_sum = True\r\n\r\n # same as above but with column list\r\n cTemp = col_sum_list[0]\r\n for item1 in col_sum_list:\r\n if cTemp != item1:\r\n col_sum = False\r\n break;\r\n else:\r\n col_sum = True\r\n\r\n # same as above but with diagonal list\r\n dTemp = diag_sum_list[0]\r\n for item2 in diag_sum_list:\r\n if dTemp != item2:\r\n diag_sum = False\r\n break;\r\n else:\r\n diag_sum = True\r\n\r\n # if any of the booleans are false print that it is not a magic square\r\n if (row_sum == False) or (col_sum == False) or (diag_sum == False):\r\n print('\\nThis is not a magic square')\r\n\r\n # if all booleans are true AND and first sum in all the lists are equal then print out that the magic square is magic\r\n elif (row_sum == col_sum == diag_sum == True) and (row_sum_list[0] == col_sum_list[0] == diag_sum_list[0]):\r\n print(\"\\nThis is a magic square\")\r\n\r\n\r\ndef main():\r\n # Prompt the user to enter an odd number 1 or greater\r\n odd_number = int(input(\"Enter an odd number 1 or greater: \"))\r\n # Check the user input\r\n while odd_number % 2 == 0:\r\n odd_number = int(input(\"The number was not odd or greater than 1. Enter an odd number 1 or greater: \"))\r\n # Create the magic square\r\n make_square(odd_number)\r\n print()\r\n print(\"This is a\", odd_number,\"by\",odd_number,\"magic square\", end=\".\")\r\n print()\r\n # Print the magic square\r\n print()\r\n print_square(make_square(odd_number))\r\n print()\r\n # Verify that it is a magic square\r\n check_square(make_square(odd_number))\r\n\r\n# This line above main is for grading purposes. It will not affect how\r\n# your code will run while you develop and test it.\r\n# DO NOT REMOVE THE LINE ABOVE MAIN\r\nif __name__ == \"__main__\":\r\n main()\r\n" }, { "alpha_fraction": 0.5023099780082703, "alphanum_fraction": 0.5354892611503601, "avg_line_length": 20.462265014648438, "blob_id": "e6eed60e17a284b0370cc1c771da1df22fc71e5a", "content_id": "720c1b091364e60a0ccd1f538e59aaf1708ce120", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2381, "license_type": "no_license", "max_line_length": 102, "num_lines": 106, "path": "/Bridge.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# File: Bridge.py\r\n\r\n# Description: Find the fastest time that people can go over if only two people can go over at a time\r\n\r\n# Student Name: Andrew Chen\r\n\r\n# Student UT EID: ac68644\r\n\r\n# Partner Name: Saaketh Palchuru\r\n\r\n# Partner UT EID: srp2992\r\n\r\n# Course Name: CS 313E\r\n\r\n# Unique Number: 50210\r\n\r\n# Date Created: 10/2/19\r\n\r\n# Date Last Modified: 10/4/19\r\n\r\n\r\n# first algorithm of moving with two fastest and two slowest\r\ndef move(people):\r\n time = 0\r\n cross = []\r\n\r\n while len(people) > 2:\r\n # bring over 2 fastest and bring back fastest\r\n\r\n cross.append(people[1])\r\n time += people[0] + people[1]\r\n people.pop(1)\r\n\r\n if len(people) <= 2:\r\n break\r\n # bring over 2 slowest and bring back fastest\r\n\r\n cross.append(people[-1])\r\n people.pop(-1)\r\n cross.append(people[-1])\r\n people.pop(-1)\r\n people.append(cross[-3])\r\n people.sort()\r\n time += cross[-2] + cross[-3]\r\n cross.pop(-3)\r\n\r\n if len(people) == 1:\r\n time += people[0]\r\n elif len(people) == 2:\r\n time += people[1]\r\n\r\n return time\r\n\r\n\r\n# second algorithm with fastest and next fastest\r\ndef move2(people):\r\n time2 = 0\r\n cross = []\r\n\r\n while len(people) > 2:\r\n # bring over fastest 2 and take back fastest one\r\n\r\n cross.append(people[1])\r\n time2 += people[0] + people[1]\r\n people.pop(1)\r\n if len(people) == 1:\r\n time2 += people[0]\r\n elif len(people) == 2:\r\n time2 += people[1]\r\n\r\n return time2\r\n\r\n\r\ndef main():\r\n infile = open('bridge.txt', 'r')\r\n\r\n cases = int(infile.readline())\r\n\r\n # go through all cases\r\n for i in range(cases):\r\n infile.readline()\r\n people = int(infile.readline())\r\n # create list of times for people\r\n all_people = []\r\n for j in range(people):\r\n all_people.append(int(infile.readline().strip()))\r\n all_people.sort()\r\n # create a copy to use\r\n all_people2 = all_people[:]\r\n\r\n time2 = move2(all_people)\r\n time1 = move(all_people2)\r\n\r\n # print time depending on faster time from two algorithms\r\n if time1 < time2:\r\n print(time1)\r\n elif time2 < time1:\r\n print(time2)\r\n elif time2 == time1:\r\n print(time1)\r\n print()\r\n\r\n infile.close()\r\n\r\n\r\nmain()\r\n" }, { "alpha_fraction": 0.3762993812561035, "alphanum_fraction": 0.46500346064567566, "avg_line_length": 21.655736923217773, "blob_id": "54e756a6dc082d490eab9809747d2ea00353d78b", "content_id": "21c3c6928b20d7dbcef8152ec44b3b550ee81c41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1443, "license_type": "no_license", "max_line_length": 104, "num_lines": 61, "path": "/EvenMagicSquare.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# File: EvenMagicSquare.py\r\n\r\n# Description: Prints out first 10 even magic squares through pruning certain paths that are impossible\r\n\r\n# Student Name: Andrew Chen\r\n\r\n# Student UT EID: ac68644\r\n\r\n# Partner Name: Saaketh Palchuru\r\n\r\n# Partner UT EID: srp2992\r\n\r\n# Course Name: CS 313E\r\n\r\n# Unique Number: 50210\r\n\r\n# Date Created: 10/12/19\r\n\r\n# Date Last Modified:\r\n\r\n\r\ncounter = 0\r\n\r\n\r\ndef even_magic_square(a, lo):\r\n global counter\r\n hi = len(a)\r\n if counter == 10:\r\n return\r\n if lo == 4 and a[0] + a[1] + a[2] + a[3] != 34:\r\n return\r\n elif lo == 8 and a[4] + a[5] + a[6] + a[7] != 34:\r\n return\r\n elif lo == 12 and a[8] + a[9] + a[10] + a[11] != 34:\r\n return\r\n elif lo == 13 and a[12] + a[9] + a[6] + a[3] != 34:\r\n return\r\n elif lo == 13 and a[0] + a[4] + a[8] + a[12] != 34:\r\n return\r\n elif lo == 14 and a[1] + a[5] + a[9] + a[13] != 34:\r\n return\r\n elif lo == 15 and a[2] + a[6] + a[10] + a[14] != 34:\r\n return\r\n elif lo == hi and a[15] + a[10] + a[5] + a[0] != 34:\r\n return\r\n elif lo == hi:\r\n print(a)\r\n counter += 1\r\n else:\r\n for i in range(lo, hi):\r\n a[lo], a[i] = a[i], a[lo]\r\n even_magic_square(a, lo + 1)\r\n a[lo], a[i] = a[i], a[lo]\r\n\r\ndef main():\r\n lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]\r\n lst2 = [1, 2, 3, 4]\r\n even_magic_square(lst, 0)\r\n\r\n\r\nmain()\r\n" }, { "alpha_fraction": 0.4723365306854248, "alphanum_fraction": 0.4887974262237549, "avg_line_length": 24.059524536132812, "blob_id": "85e2bbbc036e29c94ab518327c488a03a503ba8a", "content_id": "73db2a5992b64e3ae62486326f6c7dbceb4069c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2187, "license_type": "no_license", "max_line_length": 89, "num_lines": 84, "path": "/Queens.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# File: Queens.py\r\n\r\n# Description:\r\n\r\n# Student Name: Andrew Chen\r\n\r\n# Student UT EID: ac68644\r\n\r\n# Partner Name: Saaketh Palchuru\r\n\r\n# Partner UT EID: srp2992\r\n\r\n# Course Name: CS 313E\r\n\r\n# Unique Number: 50210\r\n\r\n# Date Created: 10/19/19\r\n\r\n# Date Last Modified: 10/20/19\r\n\r\n\r\nclass Queens(object):\r\n # initialize the board\r\n def __init__(self, n=8):\r\n self.board = []\r\n self.count = 0\r\n self.n = n\r\n for i in range(self.n):\r\n row = []\r\n for j in range(self.n):\r\n row.append('*')\r\n self.board.append(row)\r\n\r\n # print the board\r\n def print_board(self):\r\n for i in range(self.n):\r\n for j in range(self.n):\r\n print(self.board[i][j], end=' ')\r\n print()\r\n\r\n # check if no queen captures another\r\n def is_valid(self, row, col):\r\n for i in range(self.n):\r\n if self.board[row][i] == 'Q' or self.board[i][col] == 'Q':\r\n return False\r\n for i in range(self.n):\r\n for j in range(self.n):\r\n row_diff = abs(row - i)\r\n col_diff = abs(col - j)\r\n if (row_diff == col_diff) and (self.board[i][j] == 'Q'):\r\n return False\r\n return True\r\n\r\n # do a recursive backtracking solution\r\n def recursive_solve(self, col):\r\n if col == self.n:\r\n self.count += 1\r\n self.print_board()\r\n print()\r\n\r\n else:\r\n for i in range(self.n):\r\n if self.is_valid(i, col):\r\n self.board[i][col] = 'Q'\r\n self.recursive_solve(col + 1)\r\n self.board[i][col] = '*'\r\n\r\n def print_count(self):\r\n print('There are ', self.count, 'solutions for a', self.n, 'x', self.n, 'board.')\r\n\r\n\r\ndef main():\r\n board_size = int(input('Enter the size of the board: '))\r\n while board_size < 1 or board_size > 8:\r\n board_size = int(input('Enter the size of the board: '))\r\n # create a regular chess board\r\n game = Queens(board_size)\r\n\r\n # place the queens on the board\r\n game.recursive_solve(0)\r\n game.print_count()\r\n\r\n\r\nmain()" }, { "alpha_fraction": 0.34992679953575134, "alphanum_fraction": 0.3689604699611664, "avg_line_length": 20.393442153930664, "blob_id": "1e31bec723859feb16e8124f39db2ca72263c024", "content_id": "9aa8169c9ae5b44aadd099071b4bdcea067236e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2732, "license_type": "no_license", "max_line_length": 71, "num_lines": 122, "path": "/Class.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "def permute_original(a, lo):\r\n hi = len(a)\r\n if lo == hi:\r\n print(a)\r\n return\r\n else:\r\n for i in range(lo, hi):\r\n a[lo], a[i] = a[i], a[lo]\r\n permute(a, lo + 1)\r\n a[lo], a[i] = a[i], a[lo]\r\n\r\n\r\n# Q1\r\ndef permute(a, lo):\r\n hi = len(a)\r\n if lo == hi:\r\n if a[0] != 'A' and a[1] != 'B' and a[2] != 'C' and a[3] != 'D':\r\n print(a)\r\n else:\r\n for i in range(lo, hi):\r\n a[lo], a[i] = a[i], a[lo]\r\n permute(a, lo + 1)\r\n a[lo], a[i] = a[i], a[lo]\r\n\r\n\r\n# Q3\r\ndef permute2(a, lo):\r\n hi = len(a)\r\n indexA = a.index('A')\r\n indexB = a.index('B')\r\n indexC = a.index('C')\r\n indexD = a.index('D')\r\n if lo == hi:\r\n if abs(indexA - indexB) == 1 and abs(indexC - indexD) > 1:\r\n print(a)\r\n else:\r\n for i in range(lo, hi):\r\n a[lo], a[i] = a[i], a[lo]\r\n permute2(a, lo + 1)\r\n a[lo], a[i] = a[i], a[lo]\r\n\r\n\r\n# Q2\r\n\r\n\r\n# Q4\r\n# def combination(c, d, lo):\r\n# hi = len(c)\r\n# if lo == hi:\r\n# if len(d) == 3:\r\n# if 'A' in d and 'B' in d:\r\n# print(d)\r\n# if 'C' in d and 'D' not in d:\r\n# print(d)\r\n# if 'D' in d and 'C' not in d:\r\n# print(d)\r\n# else:\r\n# e = d[:]\r\n# d.append(c[lo])\r\n# combination(c, d, lo + 1)\r\n# combination(c, e, lo + 1)\r\n\r\n\r\ndef combination(c, d, lo):\r\n hi = len(c)\r\n if lo == hi:\r\n if len(d) == 3:\r\n if 'A' in d and 'B' in d:\r\n print(d)\r\n if 'C' in d and 'D' not in d:\r\n print(d)\r\n if 'D' in d and 'C' not in d:\r\n print(d)\r\n else:\r\n e = d[:]\r\n d.append(c[lo])\r\n combination(c, d, lo + 1)\r\n combination(c, e, lo + 1)\r\n\r\n\r\n#def subsets(remain, chosen):\r\n# if len(remain) == 0:\r\n# print(chosen)\r\n# else:\r\n# remain = remain[1:]\r\n# subsets(remain, chosen)\r\n# subsets(remain, chosen + remain[0])\r\n\r\n\r\n# Q5\r\ndef sub_sets(a, b, lo):\r\n hi = len(a)\r\n if lo == hi:\r\n if sum(b) == 50:\r\n print(b)\r\n\r\n else:\r\n c = b[:]\r\n b.append(a[lo])\r\n sub_sets(a, b, lo + 1)\r\n sub_sets(a, c, lo + 1)\r\n\r\n\r\ndef main():\r\n a = ['A', 'B', 'C', 'D']\r\n # permute(a, 0)\r\n # print()\r\n # b = ['A', 'B', 'C', 'D', 'E']\r\n # permute2(b, 0)\r\n # print()\r\n c = ['A', 'B', 'C', 'D', 'E', 'F']\r\n d = []\r\n # print()\r\n combination(c, d, 0)\r\n print()\r\n # e = [15, 9, 30, 21, 19, 3, 12, 6, 25, 27]\r\n # f = []\r\n # print(sub_sets(e, f, 0))\r\n permute_original(a, 0)\r\n # z = []\r\n #subsets(c, z)\r\nmain()\r\n" }, { "alpha_fraction": 0.45305514335632324, "alphanum_fraction": 0.4843517243862152, "avg_line_length": 17.449275970458984, "blob_id": "c6fd9f456d640159718cd4be49cb97db4514b8c4", "content_id": "97409a8a3a02fa889935b2ba518635679a1de28a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1342, "license_type": "no_license", "max_line_length": 110, "num_lines": 69, "path": "/Work.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# File: Work.py\r\n\r\n# Description: Manipulate binary search to find out the minimum n lines of code needed to finish the program\r\n\r\n# Student Name: Andrew Chen\r\n\r\n# Student UT EID: ac68644\r\n\r\n# Course Name: CS 313E\r\n\r\n# Unique Number: 50210\r\n\r\n# Date Created: 9/29/19\r\n\r\n# Date Last Modified: 9/30/19\r\n\r\n\r\ndef binarySearch(a, x):\r\n lo = 0\r\n hi = a\r\n\r\n while lo <= hi:\r\n mid = (lo + hi) // 2\r\n number = findSum(mid, x)\r\n number2 = findSum(mid -1, x)\r\n if number > hi and number2 > hi:\r\n hi = mid - 1\r\n elif number < hi and number2 < hi:\r\n lo = mid + 1\r\n elif number >= hi and number2 == hi:\r\n return mid - 1\r\n else:\r\n return mid\r\n\r\n\r\ndef findSum(n, x):\r\n exp = 0\r\n sums = 0\r\n stop = 1\r\n\r\n while stop != 0:\r\n eq = n // x ** exp\r\n sums += eq\r\n exp += 1\r\n if eq == 0:\r\n stop = 0\r\n\r\n return sums\r\n\r\n\r\ndef main():\r\n infile = open('work.txt', 'r')\r\n\r\n loops = infile.readline()\r\n loops = int(loops)\r\n\r\n for i in range(loops):\r\n line = infile.readline()\r\n line = line.strip().split()\r\n for j in range(len(line)):\r\n line[j] = int(line[j])\r\n\r\n answer = binarySearch(line[0], line[1])\r\n print(answer)\r\n\r\n infile.close()\r\n\r\n\r\nmain()\r\n" }, { "alpha_fraction": 0.48688873648643494, "alphanum_fraction": 0.5106307864189148, "avg_line_length": 30.837209701538086, "blob_id": "d1418359890ff4a9cf59d57fbe5bdde3ccbe108a", "content_id": "b11299c4f703ecea73804308b55bc0822551ef1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2822, "license_type": "no_license", "max_line_length": 103, "num_lines": 86, "path": "/OfficeSpace.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# File: OfficeSpace.py\r\n# Description:\r\n# Student Name: Andrew Chen\r\n# Student UT EID: ac68644\r\n# Partner Name: Saaketh Palchuru\r\n# Partner UT EID: srp2992\r\n# Course Name: CS 313E\r\n# Unique Number: 50210\r\n# Date Created: 9/19/19\r\n# Date Last Modified: 9/23/19\r\n\r\n\r\ndef main():\r\n infile = open('office.txt', 'r')\r\n loop = True\r\n\r\n # keep going until loop is False\r\n while loop:\r\n # get dimensions\r\n first_line = infile.readline()\r\n if first_line == '':\r\n break\r\n first_line = first_line.strip().split()\r\n for i in range(len(first_line)):\r\n first_line[i] = int(first_line[i])\r\n\r\n # get number of employees\r\n number = infile.readline()\r\n number = number.strip()\r\n number = int(number)\r\n file_list = []\r\n # read in employee coordinates\r\n for i in range(number):\r\n line = infile.readline()\r\n line = line.strip().split()\r\n for j in range(len(line) - 1):\r\n line[j + 1] = int(line[j + 1])\r\n file_list.append(line)\r\n\r\n # make matrix of 0's for the x-y grid\r\n matrix = [[int(0) for j in range(first_line[0])] for i in range(first_line[1])]\r\n\r\n # increment 1 for for the range of employee coordinates\r\n for i in range(number):\r\n for row in range(file_list[i][2], file_list[i][4]):\r\n for col in range(file_list[i][1], file_list[i][3]):\r\n matrix[row][col] += 1\r\n\r\n unallocated_counter = 0\r\n contested_counter = 0\r\n\r\n # add up 0's for unallocated space and 1's for contested space\r\n for row in matrix:\r\n for spot in row:\r\n if spot == 0:\r\n unallocated_counter += 1\r\n elif spot > 1:\r\n contested_counter += 1\r\n\r\n # code to see who has contested space or not\r\n outer_list = []\r\n for i in range(number):\r\n inner_list = []\r\n for row in range(file_list[i][2], file_list[i][4]):\r\n for col in range(file_list[i][1], file_list[i][3]):\r\n inner_list.append(matrix[row][col])\r\n outer_list.append(inner_list)\r\n\r\n print(\"Total\", first_line[0] * first_line[1])\r\n print(\"Unallocated\", unallocated_counter)\r\n print(\"Contested\", contested_counter)\r\n\r\n # print each employee's totals depending on if they have contested space or not\r\n j = 0\r\n for item in file_list:\r\n if any(i > 1 for i in outer_list[j]):\r\n print(item[0], ((abs(item[3] - item[1]) * abs(item[4] - item[2])) - contested_counter))\r\n\r\n else:\r\n print(item[0], abs(item[3] - item[1]) * abs(item[4] - item[2]))\r\n j += 1\r\n\r\n print()\r\n\r\n\r\nmain()" }, { "alpha_fraction": 0.4628286361694336, "alphanum_fraction": 0.4873073399066925, "avg_line_length": 21.46808433532715, "blob_id": "5d58eec2c8ba4ac9e5d60b27611beed9668e97f0", "content_id": "40594cd4684e6a75b8d593f5cbd17af579adacff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2206, "license_type": "no_license", "max_line_length": 72, "num_lines": 94, "path": "/Boxes.py", "repo_name": "anjhoon/CS313E", "src_encoding": "UTF-8", "text": "# File: Boxes.py\r\n\r\n# Description: Find largest subset(s) of nests lists and print them out\r\n\r\n# Student Name: Andrew Chen\r\n\r\n# Student UT EID: ac68644\r\n\r\n# Partner Name: Saaketh Palchuru\r\n\r\n# Partner UT EID: srp2992\r\n\r\n# Course Name: CS 313E\r\n\r\n# Unique Number: 50210\r\n\r\n# Date Created: 10/15/19\r\n\r\n# Date Last Modified: 10/16/19\r\n\r\n\r\ndef does_fit(box1, box2):\r\n return box1[0] < box2[0] and box1[1] < box2[1] and box1[2] < box2[2]\r\n\r\n\r\nlst = []\r\n\r\n\r\ndef subsets(a, b, lo):\r\n global lst\r\n hi = len(a)\r\n if lo == hi:\r\n if len(b) >= 2:\r\n counter = 0\r\n for i in range(len(b) - 1):\r\n if does_fit(b[i], b[i + 1]):\r\n counter += 1\r\n if counter == len(b) - 1:\r\n lst.append(b)\r\n else:\r\n return\r\n else:\r\n c = b[:]\r\n b.append(a[lo])\r\n subsets(a, b, lo + 1)\r\n subsets(a, c, lo + 1)\r\n\r\n\r\ndef main():\r\n # open file for reading\r\n infile = open('boxes.txt', 'r')\r\n line = infile.readline()\r\n line = line.strip()\r\n num_boxes = int(line)\r\n\r\n # empty list for boxes\r\n box_list = []\r\n # read all boxes into the list\r\n for line in range(num_boxes):\r\n line = infile.readline()\r\n line = line.strip()\r\n box = line.split()\r\n for j in range(len(box)):\r\n box[j] = int(box[j])\r\n box.sort()\r\n box_list.append(box)\r\n\r\n infile.close()\r\n box_list.sort()\r\n new_list = []\r\n # find subsets of box_list\r\n subsets(box_list, new_list, 0)\r\n # sort the subsets in descending order\r\n lst.sort(key=len, reverse=True)\r\n # if no subsets in lst\r\n if len(lst) == 0:\r\n print('No Nesting Boxes')\r\n # if subsets in lst\r\n else:\r\n print('Largest Subset of Nesting Boxes')\r\n final_list = []\r\n # append the lists that are of the largest length\r\n for box in lst:\r\n max_len = len(lst[0])\r\n if len(box) == max_len:\r\n final_list.append(box)\r\n # print the nested boxes\r\n for box in final_list:\r\n for nest in box:\r\n print(nest)\r\n print()\r\n\r\n\r\nmain()\r\n" } ]
19
Hatovix/Rectangle
https://github.com/Hatovix/Rectangle
cb85aeceae6387382bd8ee8f2e44912a2e5083af
2c168e8e7c4ff218bdad7f29ef01b9e8872caf35
26403f14cc402f5b79430bccd34045eff67a09a1
refs/heads/main
2023-01-21T23:05:58.476216
2020-11-29T19:38:18
2020-11-29T19:38:18
311,446,555
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5268312096595764, "alphanum_fraction": 0.535325288772583, "avg_line_length": 28.871641159057617, "blob_id": "feb18ddf934646fd4caab3ac5e63b009fd99c479", "content_id": "c5ccb057b0eab5e4e303a411ce18e8752657c452", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10007, "license_type": "permissive", "max_line_length": 119, "num_lines": 335, "path": "/rectangle.py", "repo_name": "Hatovix/Rectangle", "src_encoding": "UTF-8", "text": "import math\n\nfrom typing import List, Tuple\n\n\nclass Rectangle:\n \"\"\"\n A class used to represent a Rectangle, using only five sine qua non parameters.\n\n Attributes\n ----------\n x_center : float\n center of the rectangle on x axis\n y_center : float\n center of the rectangle on y axis\n radius : float\n distance from the center to any vertex\n alpha_angle : float\n orientation of the first diagonal\n beta_angle : float\n orientation of the second diagonal\n p1 : Tuple[float, float]\n first vertex of the rectangle, on first diagonal\n p2 : Tuple[float, float]\n second vertex of the rectangle, on second diagonal\n p3 : Tuple[float, float]\n third vertex of the rectangle, on first diagonal\n p4 : Tuple[float, float]\n fourth vertex of the rectangle, on second diagonal\n area : float\n area of the rectangle\n \"\"\"\n\n def __init__(self, x_center: float, y_center: float, radius: float, alpha_angle: float, beta_angle: float) -> None:\n \"\"\"\n Parameters\n ----------\n x_center : float\n center of the rectangle on x axis\n y_center : float\n center of the rectangle on y axis\n radius : float\n distance from the center to any vertex\n alpha_angle : float\n orientation of the first diagonal\n beta_angle : float\n orientation of the second diagonal\n \"\"\"\n self.x_center = x_center\n self.y_center = y_center\n self.radius = abs(radius)\n self.alpha_angle = alpha_angle\n self.beta_angle = beta_angle\n self.p1 = self.vertex_calculation(self.alpha_angle)\n self.p2 = self.vertex_calculation(self.beta_angle)\n self.p3 = self.opposite_vertex(self.p1)\n self.p4 = self.opposite_vertex(self.p2)\n self.area = self.area_calculation()\n\n def vertex_calculation(self, angle: float) -> Tuple[float, float]:\n \"\"\"\n Vertex calculation following a given angle orientation from rectangle center.\n\n Parameters\n ----------\n angle : float\n angle orientation from center to vertex\n\n Returns\n ----------\n Tuple[float, float]\n the resulting vertex point coordinates (x, y)\n \"\"\"\n return (self.radius * math.cos(angle) + self.x_center,\n self.radius * math.sin(angle) + self.y_center)\n\n def opposite_vertex(self, vertex: Tuple[float, float]) -> Tuple[float, float]:\n \"\"\"\n Opposite vertex calculation (same diagonal) of a given vertex.\n\n Parameters\n ----------\n vertex : Tuple[float, float]\n the source vertex to consider\n\n Returns\n ----------\n Tuple[float, float]\n the resulting vertex point coordinates (x, y)\n \"\"\"\n return (2 * self.x_center - vertex[0],\n 2 * self.y_center - vertex[1])\n\n def distance_calculation(self, point_a: Tuple[float, float], point_b: Tuple[float, float]) -> float:\n \"\"\"\n Euclidean distance between two given points.\n\n Parameters\n ----------\n point_a : Tuple[float, float]\n the first point to consider\n point_b : Tuple[float, float]\n the second point to consider\n\n Returns\n ----------\n float\n the Euclidean distance between the two points\n \"\"\"\n return math.sqrt(pow(point_a[0] - point_b[0], 2) + pow(point_a[1] - point_b[1], 2))\n\n def area_calculation(self) -> float:\n \"\"\"\n Area calculation of the rectangle.\n\n Returns\n ----------\n float\n the area of the rectangle\n \"\"\"\n return self.distance_calculation(self.p1, self.p2) * self.distance_calculation(self.p2, self.p3)\n\n def change_x_center(self, new_x_center: float) -> None:\n \"\"\"\n Change the center of the rectangle on x axis.\n\n Parameters\n ----------\n new_x_center : float\n new center of the rectangle on x axis\n \"\"\"\n delta = new_x_center - self.x_center\n self.x_center = new_x_center\n self.p1 = (self.p1[0] + delta, self.p1[1])\n self.p2 = (self.p2[0] + delta, self.p2[1])\n self.p3 = (self.p3[0] + delta, self.p3[1])\n self.p4 = (self.p4[0] + delta, self.p4[1])\n\n def change_y_center(self, new_y_center: float) -> None:\n \"\"\"\n Change the center of the rectangle on y axis.\n\n Parameters\n ----------\n new_y_center : float\n new center of the rectangle on y axis\n \"\"\"\n delta = new_y_center - self.y_center\n self.y_center = new_y_center\n self.p1 = (self.p1[0], self.p1[1] + delta)\n self.p2 = (self.p2[0], self.p2[1] + delta)\n self.p3 = (self.p3[0], self.p3[1] + delta)\n self.p4 = self.p4[0], self.p4[1] + delta\n\n def change_radius(self, new_radius: float) -> None:\n \"\"\"\n Change the radius of the rectangle.\n\n Parameters\n ----------\n new_radius : float\n new distance from the center to any vertex\n \"\"\"\n self.radius = abs(new_radius)\n self.p1 = self.vertex_calculation(self.alpha_angle)\n self.p2 = self.vertex_calculation(self.beta_angle)\n self.p3 = self.opposite_vertex(self.p1)\n self.p4 = self.opposite_vertex(self.p2)\n self.area = self.area_calculation()\n\n def change_alpha_angle(self, new_alpha_angle: float) -> None:\n \"\"\"\n Change the alpha_angle of the rectangle.\n\n Parameters\n ----------\n new_alpha_angle : float\n new orientation of the first diagonal\n \"\"\"\n self.alpha_angle = new_alpha_angle\n self.p1 = self.vertex_calculation(self.alpha_angle)\n self.p3 = self.opposite_vertex(self.p1)\n self.area = self.area_calculation()\n\n def change_beta_angle(self, new_beta_angle: float) -> None:\n \"\"\"\n Change the beta_angle of the rectangle.\n\n Parameters\n ----------\n new_beta_angle : float\n new orientation of the second diagonal\n \"\"\"\n self.beta_angle = new_beta_angle\n self.p2 = self.vertex_calculation(self.beta_angle)\n self.p4 = self.opposite_vertex(self.p2)\n self.area = self.area_calculation()\n\n def get_vertices(self) -> List[Tuple[float, float]]:\n \"\"\"\n Gets in consecutive order the four vertices of the rectangle.\n\n Returns\n ----------\n List[Tuple[float, float]]\n list of the four vertices of the rectangle\n \"\"\"\n return [self.p1, self.p2, self.p3, self.p4]\n\n def get_center(self) -> Tuple[float, float]:\n \"\"\"\n Gets the center of the rectangle.\n\n Returns\n ----------\n Tuple[float, float]\n coordinates of the center (x, y)\n \"\"\"\n return (self.x_center,\n self.y_center)\n\n def get_x_center(self) -> float:\n \"\"\"\n Gets the center of the rectangle on x axis.\n\n Returns\n ----------\n float\n center of the rectangle on x axis\n \"\"\"\n return self.x_center\n\n def get_y_center(self) -> float:\n \"\"\"\n Gets the center of the rectangle on y axis.\n\n Returns\n ----------\n float\n center of the rectangle on y axis\n \"\"\"\n return self.y_center\n\n def get_radius(self) -> float:\n \"\"\"\n Gets the radius of the rectangle.\n\n Returns\n ----------\n float\n distance from the center to any vertex\n \"\"\"\n return self.radius\n\n def get_alpha_angle(self) -> float:\n \"\"\"\n Gets the alpha_angle of the rectangle.\n\n Returns\n ----------\n float\n orientation of the first diagonal\n \"\"\"\n return self.alpha_angle\n\n def get_beta_angle(self) -> float:\n \"\"\"\n Gets the beta_angle of the rectangle.\n\n Returns\n ----------\n float\n orientation of the second diagonal\n \"\"\"\n return self.beta_angle\n\n def pretty_point(self, name: str, point: Tuple[float, float]) -> str:\n \"\"\"\n Gets a pretty version of a given point.\n\n Parameters\n ----------\n name : str\n name of the point\n point : Tuple[float, float]\n coordinates of the point\n\n Returns\n ----------\n str\n a pretty version of the given point\n \"\"\"\n return f'{name} ({round(point[0], 3)};{round(point[1], 3)})'\n \n def __eq__(self, other: 'Rectangle') -> bool:\n \"\"\"\n Rectangle equality comparison.\n\n Returns\n ----------\n bool\n the equality comparison result\n \"\"\"\n return self.get_center() == other.get_center() \\\n and self.radius == other.get_radius() \\\n and (self.alpha_angle == other.get_alpha_angle() and self.beta_angle == other.get_beta_angle()\n or self.alpha_angle == other.get_beta_angle() and self.beta_angle == other.get_alpha_angle())\n\n def __str__(self) -> str:\n \"\"\"\n Gets the readable version of the rectangle.\n\n Returns\n ----------\n str\n the readable version of the rectangle\n \"\"\"\n return f'\\n'.join([self.pretty_point(f'P{i+1}', point) for i, point in enumerate(self.get_vertices())])\n\n def __repr__(self) -> str:\n \"\"\"\n Gets the unambiguous version of the rectangle.\n\n Returns\n ----------\n str\n the unambiguous version of the rectangle\n \"\"\"\n return f'Rectangle(' \\\n f'x_center={self.x_center}, ' \\\n f'y_center={self.y_center}, ' \\\n f'radius={self.radius}, ' \\\n f'alpha_angle={self.alpha_angle}, ' \\\n f'beta_angle={self.beta_angle}' \\\n f')\\n'\n" } ]
1
pranavvm26/HackerRankCodes
https://github.com/pranavvm26/HackerRankCodes
81b3c39dc0e49579d99e0eba178061e0384393cb
528f0181f5ae2f7b145cd39e7898947883cc6302
be22a16117f80e85726386a5dfaac85a06099a0f
refs/heads/master
2020-06-16T01:15:42.931262
2016-12-08T02:33:25
2016-12-08T02:33:25
75,253,564
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5502958297729492, "alphanum_fraction": 0.5532544255256653, "avg_line_length": 29.772727966308594, "blob_id": "f13c19a8a438bcd5a24569269bafa2a64cfac554", "content_id": "af928a46cc60253ef70c9e711373c69333750c98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 676, "license_type": "no_license", "max_line_length": 56, "num_lines": 22, "path": "/max_difference.py", "repo_name": "pranavvm26/HackerRankCodes", "src_encoding": "UTF-8", "text": "def max_difference(array_diff, len_array):\n diff_array = []\n for i_o in range(len_array):\n for i_i in range(i_o, len_array, 1):\n temp_array = array_diff[i_o:i_i+1]\n max_element = max(temp_array)\n min_element = min(temp_array)\n diff = max_element - min_element\n diff_array.append(diff)\n return sum(diff_array)\n\n\nif __name__ == '__main__':\n len_array = input()\n array_diff = input()\n array_diff = array_diff.split(' ')\n for i, elem in enumerate(array_diff):\n if elem != '':\n array_diff[i] = int(elem)\n\n sum_res = max_difference(array_diff, int(len_array))\n print(sum_res)" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 18, "blob_id": "c3411a070095e8bbf6b728ce40d1f24187ef102f", "content_id": "119a28cb02fe1f1688bb874e37bf46c2e58faefc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 20, "license_type": "no_license", "max_line_length": 18, "num_lines": 1, "path": "/README.md", "repo_name": "pranavvm26/HackerRankCodes", "src_encoding": "UTF-8", "text": "\"#HackerRankCodes\" \n" }, { "alpha_fraction": 0.5222772359848022, "alphanum_fraction": 0.5321782231330872, "avg_line_length": 25.933332443237305, "blob_id": "1eb8db354374339adf23e603e062e7a829d1b2b8", "content_id": "905a20a5006ec39579a17bd3c1adf0fc4ab447e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 404, "license_type": "no_license", "max_line_length": 66, "num_lines": 15, "path": "/trailingZeros.py", "repo_name": "pranavvm26/HackerRankCodes", "src_encoding": "UTF-8", "text": "def find_trailing_zeros(n):\n div_by = 5\n results = []\n while div_by <= n:\n _trailing_zeros = int((n -(n%5))/div_by)\n results.append(_trailing_zeros)\n div_by *= 5\n return sum(results)\n\n\nif __name__ == '__main__':\n _n = input('enter the number :')\n _n = int(_n)\n zeros = find_trailing_zeros(n=_n)\n print('Number of trailing 0s in '+str(_n)+'! is :'+str(zeros))\n" } ]
3
moisesroth/fizzbuzz
https://github.com/moisesroth/fizzbuzz
52910f727035df2bfa8ce7ea2a86a90de28d7c0e
6ddc346c149412159fbba611ff4552fc892da613
390cee839c36ba35609208f93875701655faf020
refs/heads/master
2020-07-08T09:11:24.916992
2019-08-21T18:30:40
2019-08-21T18:30:40
203,628,895
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7016393542289734, "alphanum_fraction": 0.7491803169250488, "avg_line_length": 15.052631378173828, "blob_id": "075a10abefc1bd9dfe00736ce449afc633c6fafd", "content_id": "0ceb986909b151be6ccdb1fd21546a68676477a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 610, "license_type": "no_license", "max_line_length": 233, "num_lines": 38, "path": "/README.md", "repo_name": "moisesroth/fizzbuzz", "src_encoding": "UTF-8", "text": "# fizzbuzz\nSimple fizzbuzz example\n\n# description\nThe \"Fizz-Buzz test\" is an interview question designed to help filter out the 99.5% of programming job candidates who can't seem to program their way out of a wet paper bag.\n\n# goal\nWrite a program that prints the numbers from 1 to 100. But for multiples of three print \"Fizz\" instead of the number and for the multiples of five print \"Buzz\". For numbers which are multiples of both three and five print \"FizzBuzz\".\n\n# usage\n```python\n>>> fizzbuzz(n=100)\n1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n{...}\n89\nFizzBuzz\n91\n92\nFizz\n94\nBuzz\nFizz\n97\n98\nFizz\nBuzz\n```\n" }, { "alpha_fraction": 0.4000000059604645, "alphanum_fraction": 0.4457142949104309, "avg_line_length": 28, "blob_id": "1ecd4216a8a98d1f60dec02eecd0febada1e7945", "content_id": "639b36f6a46eced2bf9f3cd79e9f9fb9e02280d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 175, "license_type": "no_license", "max_line_length": 39, "num_lines": 6, "path": "/fizzbuzz.py", "repo_name": "moisesroth/fizzbuzz", "src_encoding": "UTF-8", "text": "def fizzbuzz(n=15):\n for i in range(1, n+1):\n output = ''\n if i % 3 == 0: output += 'Fizz'\n if i % 5 == 0: output += 'Buzz'\n print output or i\n\n" } ]
2
Edinburgh-Genome-Foundry/Geneblocks
https://github.com/Edinburgh-Genome-Foundry/Geneblocks
8553d66f0f02eedcc690bfd073bd4e591973bebd
b021d871614d3872e10b05cdab8d85eeb1a0c2f6
74d302a966937113e74b933ccb8e3d9bf6dbe17d
refs/heads/master
2023-07-31T22:34:13.343665
2022-06-08T19:27:02
2022-06-08T19:27:02
102,761,944
32
3
NOASSERTION
2017-09-07T16:42:00
2020-07-22T04:18:44
2020-09-09T17:38:04
Python
[ { "alpha_fraction": 0.6322135925292969, "alphanum_fraction": 0.7416020631790161, "avg_line_length": 37.733333587646484, "blob_id": "43726226467c419b2e8505642abd888bbddc9d97", "content_id": "bf99476ddd8c654e5be7cb4d985e89ce5bd939d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1161, "license_type": "permissive", "max_line_length": 74, "num_lines": 30, "path": "/examples/complex_sequences.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "from geneblocks import DiffBlocks, CommonBlocks, random_dna_sequence\nimport geneblocks.sequence_modification_utils as smu\nimport matplotlib.pyplot as plt\nimport numpy\n\nnumpy.random.seed(1) # ensures the sequences will be the same at each run\n\n# GENERATE 2 \"SISTER\" SEQUENCES FOR THE EXAMPLE\nseq1 = random_dna_sequence(50000)\nseq1 = smu.copy(seq1, 25000, 30000, 50000)\n\nseq2 = seq1\nseq2 = smu.insert(seq2, 39000, random_dna_sequence(100))\nseq2 = smu.insert(seq2, 38000, random_dna_sequence(100))\nseq2 = smu.reverse(seq2, 30000, 35000)\nseq2 = smu.swap(seq2, (30000, 35000), (45000, 480000))\nseq2 = smu.delete(seq2, 20000, 2000)\nseq2 = smu.insert(seq2, 10000, random_dna_sequence(2000))\nseq2 = smu.insert(seq2, 0, 1000*\"A\")\n\n# FIND COMMON BLOCKS AND DIFFS\ncommon_blocks = CommonBlocks.from_sequences({'seq1': seq1, 'seq2': seq2})\ndiff_blocks = DiffBlocks.from_sequences(seq1, seq2).merged()\n\n# PLOT EVERYTHING\nfig, axes = plt.subplots(3, 1, figsize=(16, 8))\ncommon_blocks.plot_common_blocks(axes=axes[:-1])\ndiff_blocks.plot(ax=axes[-1], separate_axes=False)\naxes[-1].set_xlabel(\"Changes in seq2 vs. seq1\")\nfig.savefig(\"complex_sequences.png\", bbox_inches='tight')" }, { "alpha_fraction": 0.6141732335090637, "alphanum_fraction": 0.6141732335090637, "avg_line_length": 24.399999618530273, "blob_id": "6975e5c114a9e37bbfbfdc5193944e6d0585b5f1", "content_id": "d14fdf7dc964e4dbec80278220d3fc9e8c128632", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 127, "license_type": "permissive", "max_line_length": 54, "num_lines": 5, "path": "/docs/ref/sequence_modification_utils.rst", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "Sequence modifications utils\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. automodule:: geneblocks.sequence_modification_utils\n :members:\n" }, { "alpha_fraction": 0.6515151262283325, "alphanum_fraction": 0.6515151262283325, "avg_line_length": 12.399999618530273, "blob_id": "34ba7d40bc4942db27674d05caba3497f993818d", "content_id": "1e3f5cb5a7aa1c6b6cd104fbd7a244bdee72c5e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 66, "license_type": "permissive", "max_line_length": 35, "num_lines": 5, "path": "/docs/ref/biotools.rst", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "Biotools\n--------\n\n.. automodule:: geneblocks.biotools\n :members:" }, { "alpha_fraction": 0.5523169040679932, "alphanum_fraction": 0.6576980352401733, "avg_line_length": 38.35293960571289, "blob_id": "b77eb5b63cc3e56d170126fc48c97d2229054ae9", "content_id": "0ca3c6eeb89b5e4fb319c2a13e61b443f7e8e6c8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1338, "license_type": "permissive", "max_line_length": 78, "num_lines": 34, "path": "/tests/test_complex_sequences.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "from geneblocks import DiffBlocks, CommonBlocks, random_dna_sequence\nimport geneblocks.sequence_modification_utils as smu\nimport matplotlib.pyplot as plt\n\n\ndef test_complex_sequences():\n seq1 = random_dna_sequence(50000, seed=123)\n seq1 = smu.copy(seq1, 25000, 30000, 50000)\n\n seq2 = seq1\n seq2 = smu.insert(seq2, 39000, random_dna_sequence(100))\n seq2 = smu.insert(seq2, 38000, random_dna_sequence(100))\n seq2 = smu.reverse(seq2, 30000, 35000)\n seq2 = smu.swap(seq2, (30000, 35000), (45000, 480000))\n seq2 = smu.delete(seq2, 20000, 2000)\n seq2 = smu.insert(seq2, 10000, random_dna_sequence(2000))\n seq2 = smu.insert(seq2, 0, 1000 * \"A\")\n diff_blocks = DiffBlocks.from_sequences(seq1, seq2).merged()\n\n b = diff_blocks.blocks\n assert len(b) == 15\n assert b[0].operation == \"insert\"\n start, end, _ = b[0].s2_location.to_tuple()\n assert end - start == 1000\n assert b[1].operation == \"equal\"\n assert b[2].operation == \"insert\"\n start, end, _ = b[2].s2_location.to_tuple()\n assert end - start == 2000\n assert sorted([b[6].operation, b[7].operation]) == [\"change\", \"transpose\"]\n assert sorted([b[-1].operation, b[-2].operation]) == [\"change\", \"reverse\"]\n\n s1, s2 = diff_blocks.reconstruct_sequences_from_blocks(diff_blocks.blocks)\n assert s1 == seq1\n assert s2 == seq2\n" }, { "alpha_fraction": 0.7697368264198303, "alphanum_fraction": 0.7697368264198303, "avg_line_length": 38.52000045776367, "blob_id": "e113fa55b00f79c722042412369b0c42174c2ca0", "content_id": "b4eb8e011e8fa4e7415c296e780dcb730e20e6f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1976, "license_type": "permissive", "max_line_length": 164, "num_lines": 50, "path": "/pypi-readme.rst", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "GeneBlocks\n==========\n\n.. image:: https://github.com/Edinburgh-Genome-Foundry/Geneblocks/actions/workflows/build.yml/badge.svg\n :target: https://github.com/Edinburgh-Genome-Foundry/Geneblocks/actions/workflows/build.yml\n :alt: GitHub CI build status\n\n.. image:: https://coveralls.io/repos/github/Edinburgh-Genome-Foundry/Geneblocks/badge.svg\n :target: https://coveralls.io/github/Edinburgh-Genome-Foundry/Geneblocks\n\nGeneBlocks is a Python library for comparing DNA sequences. It can be used to:\n\n- Find common blocks in a group of DNA sequences, to factorize them (e.g. only analyze or synthetize each common block once).\n- Highlight differences between sequences (insertions, deletions, mutations).\n- Transfer Genbank features from one record to another sharing similar subsequences.\n\nAt the Edinburgh Genome Foundry, we use GeneBlocks to optimize sequence assembly, explore sets of non-annotated sequences, or visualize the differences\nbetween different versions of a sequence, and re-annotate records coming from third parties such as DNA manufacturers.\n\nInfos\n-----\n\n**PIP installation:**\n\n.. code:: bash\n\n pip install geneblocks\n\n**Github Page:**\n\n`<https://github.com/Edinburgh-Genome-Foundry/geneblocks>`_\n\n**Live demos:**\n\n\n`Find common sequence blocks <https://cuba.genomefoundry.org/find-common-blocks>`_\n\n`Plot sequence diffs <https://cuba.genomefoundry.org/compare-two-sequences>`_\n\n`Transfer Genbank features between records <https://cuba.genomefoundry.org/transfer-features>`_\n\n**License:** MIT, Copyright Edinburgh Genome Foundry\n\nMore biology software\n---------------------\n\n.. image:: https://raw.githubusercontent.com/Edinburgh-Genome-Foundry/Edinburgh-Genome-Foundry.github.io/master/static/imgs/logos/egf-codon-horizontal.png\n :target: https://edinburgh-genome-foundry.github.io/\n\nGeneblocks is part of the `EGF Codons <https://edinburgh-genome-foundry.github.io/>`_ synthetic biology software suite for DNA design, manufacturing and validation.\n" }, { "alpha_fraction": 0.42095914483070374, "alphanum_fraction": 0.577856719493866, "avg_line_length": 25.40625, "blob_id": "6a299b3dd9259e1083a9dffdb6bb756d7d934eed", "content_id": "159de964182ee01ff54a655ac8d9ea8ead2a1c93", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1689, "license_type": "permissive", "max_line_length": 60, "num_lines": 64, "path": "/tests/test_base_diff_cases.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "from geneblocks.DiffBlocks import DiffBlock, DiffBlocks\nfrom geneblocks.biotools import random_dna_sequence\n\ndef diff_string(seq1, seq2, contract_under=0):\n return str(DiffBlocks.from_sequences(seq1, seq2))\n\nflanks_dict = {\n 'short': 10 * \"A\",\n 'long': random_dna_sequence(10000)\n}\ndef flanked(seq, flanks='short'):\n flank = flanks_dict[flanks]\n return flank + seq + flank\n\ndef test_1():\n assert diff_string(\n flanked(\"T\", \"short\"),\n flanked(\"C\", \"short\")\n ) == 'replace 10-11|10-11'\n\ndef test_2():\n assert diff_string(\n flanked(\"T\", \"long\"),\n flanked(\"C\", \"long\")\n ) == ', '.join([\n 'equal 0-10000|0-10000',\n 'replace 10000-10001|10000-10001',\n 'equal 10001-20001|10001-20001'\n ])\n\ndef test_3():\n assert diff_string(\n \"AATAATAAT\",\n \"AAAAAAAAA\"\n ) == 'replace 2-3|2-3, replace 5-6|5-6, replace 8-9|8-9'\n\ndef test_4():\n assert diff_string(\n flanked(\"AATAATAAT\", 'long'),\n flanked(\"AAAAAAAAA\", 'long')\n ) == ', '.join([\n 'equal 0-10002|0-10002',\n 'replace 10002-10003|10002-10003',\n 'replace 10005-10006|10005-10006',\n 'replace 10008-10009|10008-10009',\n 'equal 10009-20009|10009-20009'\n ])\n\ndef test_5():\n assert diff_string(\n \"AAAAATTTTGGAAA\",\n \"AAATTTTGGAAAAA\"\n ) == 'delete 3-5|3-3, insert 11-11|9-11'\n\ndef test_6():\n assert diff_string(\n flanked(\"AAAAATTTTGGAAA\", 'long'),\n flanked(\"AAATTTTGGAAAAA\", 'long')\n ) == ', '.join([\n 'equal 0-10003|0-10003',\n 'delete 10003-10005|10003-10003',\n 'insert 10011-10011|10009-10011',\n 'equal 10011-20014|10011-20014'\n ])" }, { "alpha_fraction": 0.5730279684066772, "alphanum_fraction": 0.5750635862350464, "avg_line_length": 30.69354820251465, "blob_id": "e1480a0d23bbb536f7c19bd85a1db18f15a6b682", "content_id": "306d80fa057483c175dce7368cc3700a8cfd66d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1965, "license_type": "permissive", "max_line_length": 78, "num_lines": 62, "path": "/geneblocks/Location.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "from .biotools import reverse_complement\nfrom Bio.SeqFeature import SeqFeature, FeatureLocation\n\n\nclass Location:\n def __init__(\n self, start, end, strand=None, sequence=None, sequence_id=None\n ):\n\n self.start = start\n self.end = end\n self.strand = strand\n self.sequence = sequence\n self.sequence_id = sequence_id\n\n def extract_sequence(self, sequence=None):\n \"\"\"Return the subsequence read at the given location.\n\n If sequence is None, ``self.sequence`` is used.\n \"\"\"\n if sequence is None:\n sequence = self.sequence\n if hasattr(sequence, \"seq\"):\n sequence = str(sequence.seq)\n result = sequence[self.start : self.end]\n if self.strand == -1:\n return reverse_complement(result)\n else:\n return result\n\n def __repr__(self):\n \"\"\"Represent\"\"\"\n result = \"%d-%d\" % (self.start, self.end)\n if self.strand is not None:\n result += {1: \"(+)\", -1: \"(-)\", 0: \"\"}[self.strand]\n if self.sequence_id is not None:\n result = self.sequence_id + \"|\" + result\n return result\n\n def __len__(self):\n \"\"\"Size of the location\"\"\"\n return abs(self.end - self.start)\n\n def to_tuple(self):\n return self.start, self.end, self.strand\n\n def to_biopython_location(self):\n \"\"\"Return a Biopython FeatureLocation equivalent to the location.\"\"\"\n start, end, strand = [\n None if e is None else int(e)\n for e in [self.start, self.end, self.strand]\n ]\n return FeatureLocation(start, end, strand)\n\n def to_biopython_feature(self, feature_type=\"misc_feature\", **qualifiers):\n \"\"\"Return a Biopython SeqFeature with same location and custom\n qualifiers.\"\"\"\n return SeqFeature(\n self.to_biopython_location(),\n type=feature_type,\n qualifiers=qualifiers,\n )\n" }, { "alpha_fraction": 0.503694474697113, "alphanum_fraction": 0.5260531902313232, "avg_line_length": 38.029964447021484, "blob_id": "e3bcc4963d6b29a3f9956634ae5397e3b6768a9d", "content_id": "6ac7f0df5e8da6e859ee06a9564a1bc00d339096", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10421, "license_type": "permissive", "max_line_length": 88, "num_lines": 267, "path": "/geneblocks/DiffBlocks/DiffBlocks.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "from copy import deepcopy\n\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport numpy as np\n\nfrom ..Location import Location\nfrom ..biotools import sequence_to_record\nfrom ..CommonBlocks import CommonBlocks\n\nfrom .DiffBlock import DiffBlock\nfrom .DiffRecordTranslator import DiffRecordTranslator\nfrom .diffblocks_tools import (\n compute_levenshtein_blocks,\n get_optimal_common_blocks,\n merge_blocs_by_location,\n merge_successive_blocks,\n compute_sorted_blocks,\n)\n\n\nclass DiffBlocks:\n \"\"\"Class to generate and represent DiffBlocks.\n\n Usage:\n\n >>> DiffBlocks.from_sequences(s1, s2)\n \"\"\"\n\n def __init__(self, s1, s2, blocks):\n self.s1 = s1\n self.s2 = s2\n self.blocks = blocks\n\n @staticmethod\n def from_sequences(s1, s2, blast_over=500, max_complexity=1e8):\n \"\"\"Create DiffBlocks by comparing two sequences.\n\n Parameters\n ----------\n\n s1, s2\n Two sequences, either \"ATGC...\" strings or Biopython records.\n\n blast_over\n A blast will be triggered to accelerate homology finding if\n len(s1) + len(s2) > blast_over.\n\n max_complexity\n If len(s1) * len(s2) is over max_complexity, no analysis is done and\n s1 is just labeled as a \"change\" of s2 (useful internally during the\n recursions of this method).\n \"\"\"\n # Note: the sequences will always be upperized before they are\n # compared. however we also need to keep the initial sequences to\n # create the final blocks (possibly with upper/lowercase nucleotides)\n\n # If the sequences are records, convert to string\n\n seq_s1 = str(s1.seq) if hasattr(s1, \"seq\") else str(s1)\n seq_s2 = str(s2.seq) if hasattr(s2, \"seq\") else str(s2)\n\n # Simple case to eliminate the trivial case of equality\n\n if seq_s1.upper() == seq_s2.upper():\n return DiffBlocks(s1, s2, [])\n\n # If the sequences are too big for straight-on Levenshtein, first\n # find the large sub-blocks that are identical, and the ones that\n # differ.\n\n if (blast_over is not None) and (len(s1) + len(s2)) > blast_over:\n\n diffblocks = []\n\n # Use CommonBlocks to find all big common blocks\n\n sequences = {\"s1\": s1, \"s2\": s2}\n common_blocks = CommonBlocks.from_sequences(\n sequences,\n min_block_size=100,\n include_self_homologies=False,\n block_selection_method=\"larger_first\",\n ).common_blocks\n blocks_in_seqs, remarks = get_optimal_common_blocks(common_blocks)\n\n # First, each common block is added as an \"equal\" diffblock\n\n for b1, b2 in zip(blocks_in_seqs[\"s1\"], blocks_in_seqs[\"s2\"]):\n diffblocks.append(\n DiffBlock(\n \"equal\",\n s1_location=Location(*b1[:2], sequence=s1),\n s2_location=Location(*b2[:2], sequence=s2),\n )\n )\n\n # for sequence in s1, s2, complete the sequence's list of blocks\n # with a (0, 0, \"START\") on the left, (L, L, \"END\") on the right.\n for seq, blocks in blocks_in_seqs.items():\n blocks_in_seqs[seq] = (\n [(0, 0, \"START\")]\n + blocks_in_seqs[seq]\n + [(len(sequences[seq]), len(sequences[seq]), \"END\")]\n )\n for i in range(len(blocks_in_seqs[\"s2\"]) - 1):\n _, end1, _ = blocks_in_seqs[\"s1\"][i]\n next_start1, _, _ = blocks_in_seqs[\"s1\"][i + 1]\n _, end2, _ = blocks_in_seqs[\"s2\"][i]\n next_start2, _, _ = blocks_in_seqs[\"s2\"][i + 1]\n if next_start2 < end2:\n subdiffblocks = [\n DiffBlock(\n \"delete\",\n s1_location=Location(end1, next_start1, sequence=s1),\n s2_location=Location(next_start2, next_start2, sequence=s2),\n )\n ]\n else:\n subsequence_1 = s1[end1:next_start1]\n subsequence_2 = s2[end2:next_start2]\n subdiffblocks = DiffBlocks.from_sequences(\n subsequence_1,\n subsequence_2,\n blast_over=None,\n max_complexity=max_complexity,\n )\n for block in subdiffblocks.blocks:\n block.s1_location.start += end1\n block.s1_location.end += end1\n block.s1_location.sequence = s1\n block.s2_location.start += end2\n block.s2_location.end += end2\n block.s2_location.sequence = s2\n diffblocks += subdiffblocks.blocks\n diffblocks = [\n b for b in diffblocks if len(b.s1_location) or len(b.s2_location)\n ]\n sorted_blocks = compute_sorted_blocks(diffblocks + remarks)\n return DiffBlocks(s1, s2, sorted_blocks)\n\n s1_std = str(s1.seq if hasattr(s1, \"seq\") else s1).upper()\n s2_std = str(s2.seq if hasattr(s2, \"seq\") else s2).upper()\n levenshtein_blocks = compute_levenshtein_blocks(\n s1_std, s2_std, max_complexity=max_complexity\n )\n blocks = [\n DiffBlock(\n operation,\n Location(s1s, s1e, sequence=s1),\n Location(s2s, s2e, sequence=s2),\n )\n for operation, (s1s, s1e), (s2s, s2e) in levenshtein_blocks\n ]\n return DiffBlocks(s1, s2, blocks)\n\n def merged(\n self, blocks_per_span=(3, 600), change_gap=100, replace_gap=10, reference=\"s2\",\n ):\n blocks = [b for b in self.blocks if b.operation not in [\"reverse\", \"transpose\"]]\n remarks = [b for b in self.blocks if b.operation in [\"reverse\", \"transpose\"]]\n if blocks_per_span is not None:\n max_blocks, span = blocks_per_span\n blocks = merge_blocs_by_location(\n blocks=blocks,\n max_blocks=max_blocks,\n max_span=span,\n reference=reference,\n )\n if change_gap is not None:\n blocks = merge_successive_blocks(\n blocks=blocks,\n change_gap=change_gap,\n replace_gap=replace_gap,\n reference=\"s2\",\n )\n blocks = compute_sorted_blocks(blocks + remarks)\n return DiffBlocks(s1=self.s1, s2=self.s2, blocks=blocks)\n\n def sort_blocks(self):\n self.blocks = compute_sorted_blocks(self.blocks)\n\n def diffs_as_features(self, sequence=\"s2\"):\n return [block.to_feature(sequence=sequence) for block in self.blocks]\n\n def plot(\n self, translator_class=\"default\", separate_axes=True, sequence=\"s2\", **plot_kw\n ):\n\n if translator_class == \"default\":\n translator_class = DiffRecordTranslator\n translator = translator_class()\n record = deepcopy(self.s2 if sequence == \"s2\" else self.s1)\n if not hasattr(record, \"features\"):\n record = sequence_to_record(record)\n\n diff_features = self.diffs_as_features(sequence=sequence)\n\n if separate_axes:\n gr_record = translator.translate_record(record)\n record.features = diff_features\n gr_diffrecord = DiffRecordTranslator().translate_record(record)\n width = plot_kw.get(\"figure_width\", 8)\n if \"axes\" in plot_kw:\n ax1, ax2 = plot_kw[\"axes\"]\n fig = ax1.figure\n else:\n fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(width, 6))\n plot_kw[\"annotate_inline\"] = plot_kw.get(\"annotate_inline\", True)\n _, stats1 = gr_record.plot(ax=ax1, **plot_kw)\n _, stats2 = gr_diffrecord.plot(ax=ax2, with_ruler=False, **plot_kw)\n max_features_1 = gr_record.feature_level_height * max(\n [0] + [v for v in stats1[0].values()]\n )\n max_level_1 = max(\n [max_features_1] + [v[\"annotation_y\"] for v in stats1[1].values()]\n )\n max_level_2 = max([1] + [v[\"annotation_y\"] for v in stats2[1].values()]) + 2\n max_level_1 = int(np.round(max_level_1))\n max_level_2 = int(np.round(max_level_2))\n # print (stats2)\n n_levels = max_level_1 + max_level_2\n if max_level_1 and max_level_2:\n plt.close(fig)\n\n ##\n easing = 3\n gs = gridspec.GridSpec(n_levels + 2 * easing, 1)\n fig = plt.figure(figsize=(width, 1 + 0.5 * n_levels), facecolor=\"w\")\n ax1 = fig.add_subplot(gs[: max_level_1 + easing])\n ax2 = fig.add_subplot(gs[max_level_1 + easing :])\n _, stats1 = gr_record.plot(ax=ax1, **plot_kw)\n _, stats2 = gr_diffrecord.plot(ax=ax2, with_ruler=False, **plot_kw)\n\n # fig.set_size_inches((width, 3 + 0.4 * n_levels))\n ax2.set_ylim(bottom=-2)\n ax2.invert_yaxis()\n for f in gr_diffrecord.features:\n ax1.fill_between(\n [f.start, f.end],\n y1=max_features_1 + 1,\n y2=-1,\n facecolor=f.color,\n alpha=0.07,\n zorder=1000,\n )\n return (ax1, ax2)\n\n else:\n record.features += diff_features\n gr_record = translator.translate_record(record)\n ax, _ = gr_record.plot(**plot_kw)\n return ax\n\n @staticmethod\n def reconstruct_sequences_from_blocks(blocks):\n s1, s2 = \"\", \"\"\n blocks = sorted(blocks, key=lambda b: b.s2_location.to_tuple())\n for block in blocks:\n if block.operation in (\"equal\", \"replace\", \"change\", \"delete\"):\n s1 = s1 + block.s1_location.extract_sequence()\n if block.operation in (\"equal\", \"replace\", \"change\", \"insert\"):\n s2 = s2 + block.s2_location.extract_sequence()\n return s1, s2\n\n def __str__(self):\n return \", \".join([str(b) for b in self.blocks])\n" }, { "alpha_fraction": 0.7424242496490479, "alphanum_fraction": 0.7424242496490479, "avg_line_length": 21.33333396911621, "blob_id": "df51e13a8102d3dbbe8bc8fe3bef691460ef76f5", "content_id": "6f6aaab2948ac8b1e3031c0bc0ee1cae1705385f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 66, "license_type": "permissive", "max_line_length": 38, "num_lines": 3, "path": "/geneblocks/CommonBlocks/__init__.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "from .CommonBlocks import CommonBlocks\n\n__all__ = ['CommonBlocks']" }, { "alpha_fraction": 0.6335418820381165, "alphanum_fraction": 0.6472569704055786, "avg_line_length": 26.16339874267578, "blob_id": "1d865a57b81d00582917d056d6763885ec7f2b86", "content_id": "158701801bdf7b830ad6658dc7e59e482d4e0f58", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4156, "license_type": "permissive", "max_line_length": 86, "num_lines": 153, "path": "/geneblocks/biotools.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "import tempfile\nimport subprocess\n\nimport numpy as np\n\ntry:\n from Bio.Seq import Seq\n from Bio.SeqRecord import SeqRecord\n from Bio.SeqFeature import SeqFeature, FeatureLocation\n from Bio import SeqIO\n\n BIOPYTHON_AVAILABLE = True\nexcept ImportError:\n BIOPYTHON_AVAILABLE = False\n\ntry:\n # Biopython <1.78\n from Bio.Alphabet import DNAAlphabet\n\n has_dna_alphabet = True\nexcept ImportError:\n # Biopython >=1.78\n has_dna_alphabet = False\n\n\ncomplements_dict = {\"A\": \"T\", \"T\": \"A\", \"C\": \"G\", \"G\": \"C\"}\n\n\ndef random_dna_sequence(length, probas=None, seed=None):\n \"\"\"Return a random DNA sequence (\"ATGGCGT...\") with the specified length.\n\n Parameters\n ----------\n\n length\n Length of the DNA sequence.\n\n proba\n Frequencies for the different nucleotides, for instance\n ``probas={\"A\":0.2, \"T\":0.3, \"G\":0.3, \"C\":0.2}``.\n If not specified, all nucleotides are equiprobable (p=0.25).\n\n seed\n The seed to feed to the random number generator. When a seed is provided\n the random results depend deterministically on the seed, thus enabling\n reproducibility\n\n \"\"\"\n if seed is not None:\n np.random.seed(seed)\n if probas is None:\n sequence = np.random.choice(list(\"ATCG\"), length)\n else:\n bases, probas = zip(*probas.items())\n sequence = np.random.choice(bases, length, p=probas)\n return \"\".join(sequence)\n\n\ndef load_record(filename, linear=True, name=\"id\", upperize=True):\n formt = \"genbank\" if filename.endswith((\"gb\", \"gbk\")) else \"fasta\"\n record = SeqIO.read(filename, formt)\n if upperize:\n record.seq = record.seq.upper()\n record.linear = linear\n if name != \"id\":\n record.id = name\n record.name = record.id.replace(\" \", \"_\")[:20]\n\n return record\n\n\ndef complement(sequence):\n return \"\".join(complements_dict[c] for c in sequence)\n\n\ndef reverse_complement(sequence):\n return complement(sequence)[::-1]\n\n\ndef sequence_to_record(sequence, record_id=None, name=\"unnamed\", features=()):\n if not BIOPYTHON_AVAILABLE:\n raise ImportError(\"Creating records requires Biopython installed.\")\n if has_dna_alphabet: # Biopython <1.78\n sequence = Seq(sequence, alphabet=DNAAlphabet())\n else:\n sequence = Seq(sequence)\n\n seqrecord = SeqRecord(sequence, name=name, id=record_id, features=list(features),)\n seqrecord.annotations[\"molecule_type\"] = \"DNA\"\n\n return seqrecord\n\n\ndef annotate_record(\n seqrecord, location=\"full\", feature_type=\"feature\", margin=0, **qualifiers\n):\n \"\"\"Add a feature to a Biopython SeqRecord.\n\n Parameters\n ----------\n\n seqrecord\n The biopython seqrecord to be annotated.\n\n location\n Either (start, end) or (start, end, strand). (strand defaults to +1)\n\n feature_type\n The type associated with the feature\n\n margin\n Number of extra bases added on each side of the given location.\n\n qualifiers\n Dictionnary that will be the Biopython feature's `qualifiers` attribute.\n \"\"\"\n\n if not BIOPYTHON_AVAILABLE:\n raise ImportError(\"Creating records requires Biopython installed.\")\n\n if location == \"full\":\n location = (margin, len(seqrecord) - margin)\n\n strand = location[2] if len(location) == 3 else 1\n seqrecord.features.append(\n SeqFeature(\n FeatureLocation(location[0], location[1], strand),\n qualifiers=qualifiers,\n type=feature_type,\n )\n )\n\n\ndef sequences_differences_array(seq1, seq2):\n \"\"\"Return an array [0, 0, 1, 0, ...] with 1s for sequence differences.\n\n seq1, seq2 should both be ATGC strings.\n \"\"\"\n if len(seq1) != len(seq2):\n raise ValueError(\n \"Only use on same-size sequences (%d, %d)\" % (len(seq1), len(seq2))\n )\n arr1 = np.fromstring(seq1, dtype=\"uint8\")\n arr2 = np.fromstring(seq2, dtype=\"uint8\")\n return arr1 != arr2\n\n\ndef sequences_differences(seq1, seq2):\n \"\"\"Return the number of nucleotides that differ in the two sequences.\n\n seq1, seq2 should be strings of DNA sequences e.g. \"ATGCTGTGC\"\n \"\"\"\n return sequences_differences_array(seq1, seq2).sum()\n" }, { "alpha_fraction": 0.5027118921279907, "alphanum_fraction": 0.5233898162841797, "avg_line_length": 34.54216766357422, "blob_id": "c8ffe5f434ff32816ac1e9d535982d26a7c693f1", "content_id": "d7101dd7d1cc84be8930d66a170c745fd79cc491", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2956, "license_type": "permissive", "max_line_length": 84, "num_lines": 83, "path": "/geneblocks/DiffBlocks/DiffBlock.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "from ..Location import Location\nfrom ..biotools import sequences_differences\n\n\nclass DiffBlock:\n \"\"\"Class to represent a segment that differs between sequences.\n\n Parameters\n ----------\n operation\n One of \"insert\", \"delete\", \"replace\", or \"equal\".\n\n s1_location\n The Location(start, end) of the region in sequence sequence s1.\n\n s2_location\n The Location(start, end) of the region in sequence sequence s2.\n \"\"\"\n\n def __init__(self, operation, s1_location, s2_location):\n self.operation = operation\n self.s1_location = s1_location\n self.s2_location = s2_location\n\n def to_feature(self, sequence=\"s2\"):\n s1_length, s2_length = len(self.s1_location), len(self.s2_location)\n max_length = max([s1_length, s2_length])\n\n if sequence == \"s1\":\n return DiffBlock(\n self.operation, self.s2_location, self.s1_location\n ).to_feature()\n\n if self.operation == \"insert\":\n if max_length <= 7:\n label = \"+%s\" % self.s2_location.extract_sequence()\n else:\n label = \"+ %d nuc.\" % s2_length\n elif self.operation == \"delete\":\n if max_length <= 7:\n label = \"-%s\" % self.s1_location.extract_sequence()\n else:\n label = \"- %d nuc.\" % s1_length\n elif self.operation == \"replace\":\n if max([s1_length, s2_length]) <= 6:\n label = \"%s ➤ %s\" % (\n self.s1_location.extract_sequence(),\n self.s2_location.extract_sequence(),\n )\n else:\n sub_s1 = self.s1_location.extract_sequence()\n sub_s2 = self.s2_location.extract_sequence()\n diffs = sequences_differences(sub_s1, sub_s2)\n label = \"%d mutations\" % diffs\n\n elif self.operation == \"change\":\n if max([s1_length, s2_length]) <= 6:\n label = \"%s ➤ %s\" % (\n self.s1_location.extract_sequence(),\n self.s2_location.extract_sequence(),\n )\n else:\n label = \"%sn ➤ %sn change\" % (s1_length, s2_length)\n elif self.operation == \"reverse\":\n label = \"was reversed at %d-%d\" % (\n self.s1_location.start,\n self.s1_location.end,\n )\n elif self.operation == \"transpose\":\n label = \"was at %d-%d\" % (self.s1_location.start, self.s1_location.end,)\n elif self.operation == \"equal\":\n label = \"Equal\"\n\n return self.s2_location.to_biopython_feature(\n feature_type=\"diff_\" + self.operation, label=label\n )\n\n def __str__(self):\n \"\"\"Represent a diffbloc, for instance: \"insert 10-30|105-105\" \"\"\"\n return \"%s %s|%s\" % (self.operation, self.s1_location, self.s2_location,)\n\n def __repr__(self):\n return str(self)\n" }, { "alpha_fraction": 0.6216216087341309, "alphanum_fraction": 0.6216216087341309, "avg_line_length": 14, "blob_id": "067c4f90c11e136cf5db6503150bb773e01d218a", "content_id": "ed38fd36681272a85a10937699a4e888e80674d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 74, "license_type": "permissive", "max_line_length": 36, "num_lines": 5, "path": "/docs/ref/DiffBlocks.rst", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "DiffBlocks\n------------\n\n.. autoclass:: geneblocks.DiffBlocks\n :members:" }, { "alpha_fraction": 0.6201372742652893, "alphanum_fraction": 0.6378718614578247, "avg_line_length": 33.959999084472656, "blob_id": "34d56a04e775d5d271981ac7c3312c122b99fa48", "content_id": "9838f6722fe34f021d98f90133950c77e2640f30", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1748, "license_type": "permissive", "max_line_length": 78, "num_lines": 50, "path": "/geneblocks/utils.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "from .CommonBlocks import CommonBlocks\nfrom .biotools import sequence_to_record\n\n\ndef _turn_sequence_into_record_if_necessary(sequence, record_id=\"id\"):\n if hasattr(sequence, \"seq\"):\n return sequence\n else:\n return sequence_to_record(sequence, record_id=record_id)\n\n\ndef sequences_are_circularly_equal(sequences):\n \"\"\"Return whether all the sequences represent the same circular sequence.\n\n This means that the sequences are differently rotated versions of a same\n circular sequence, and for any pair s1, s2 in the sequences, there is an\n index i such that s1 = s2[i:] + s2[:i].\n\n The ``sequences`` parameter should be a list of \"ATGC\" strings or\n SeqRecords.\n \"\"\"\n sequences = [\n _turn_sequence_into_record_if_necessary(seq, record_id=\"REC_%d\" % i)\n for i, seq in enumerate(sequences)\n ]\n if len(sequences) < 2:\n raise ValueError(\"Provide at least 2 sequences\")\n elif len(sequences) > 2:\n first_equal = sequences_are_circularly_equal(sequences[:2])\n return first_equal and sequences_are_circularly_equal(sequences[1:])\n s1, s2 = sequences[:2]\n if s1.id == s2.id:\n s1.id += \"_b\"\n if len(s1) != len(s2):\n return False\n blocks = CommonBlocks.from_sequences(sequences=[s1, s2], min_block_size=2)\n if len(blocks.common_blocks) > 2:\n return False\n potential_pivot_indices = [\n index\n for data in blocks.common_blocks.values()\n for (origin, (start, end, _)) in data[\"locations\"]\n for index in [start, end]\n ]\n s1, s2 = str(s1.seq), str(s2.seq)\n for index in potential_pivot_indices:\n new_s1 = s1[index:] + s1[:index]\n if new_s1 == s2:\n return True\n return False\n" }, { "alpha_fraction": 0.4936833679676056, "alphanum_fraction": 0.5199368596076965, "avg_line_length": 36.665428161621094, "blob_id": "8efe17fc942cabc9b81e63784ad821ccb5d9a444", "content_id": "b92899345feca73f8da397433482994c3c445ac5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10132, "license_type": "permissive", "max_line_length": 88, "num_lines": 269, "path": "/geneblocks/DiffBlocks/diffblocks_tools.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "from copy import deepcopy\n\nimport networkx as nx\nimport Levenshtein\n\nfrom ..Location import Location\n\nfrom .DiffBlock import DiffBlock\n\n\ndef compute_levenshtein_blocks(seq1, seq2, max_complexity=1e8):\n \"\"\"Compute the Levenshtein blocks of insertion, deletion, replacement.\n \"\"\"\n # TODO: better method for dealing with long sequences?\n l1, l2 = len(seq1), len(seq2)\n if l1 * l2 > max_complexity:\n return [(\"change\", (0, l1), (0, l2))]\n\n def block_format(op, s1, e1, s2, e2):\n if op == \"delete\":\n return (op, (s1, e1 + 1), (s2, e2))\n if op == \"insert\":\n return (op, (s1, e1), (s2, e2 + 1))\n else:\n return (op, (s1, e1 + 1), (s2, e2 + 1))\n\n edits = Levenshtein.editops(seq1, seq2)\n if len(edits) == 0:\n return []\n bop, s1, s2 = edits[0]\n e1, e2 = s1, s2\n blocks = []\n for (op, _e1, _e2) in edits[1:]:\n continuity = any(\n [\n all([op == \"delete\", _e1 == e1 + 1, e2 == _e2]),\n all([op == \"insert\", _e1 == e1, _e2 == e2 + 1]),\n all([op == \"replace\", _e1 == e1 + 1, _e2 == e2 + 1]),\n ]\n )\n if op == bop and continuity:\n e1, e2 = _e1, _e2\n else:\n blocks.append(block_format(bop, s1, e1, s2, e2))\n bop, s1, s2 = op, _e1, _e2\n e1, e2 = s1, s2\n blocks.append(block_format(bop, s1, e1, s2, e2))\n return blocks\n\n\ndef merge_subblocks(subblocks):\n s1_location = Location(\n min([b.s1_location.start for b in subblocks]),\n max([b.s1_location.end for b in subblocks]),\n sequence=subblocks[0].s1_location.sequence,\n )\n s2_location = Location(\n min([b.s2_location.start for b in subblocks]),\n max([b.s2_location.end for b in subblocks]),\n sequence=subblocks[0].s2_location.sequence,\n )\n if len(s1_location) == len(s2_location):\n return DiffBlock(\"replace\", s1_location, s2_location)\n else:\n return DiffBlock(\"change\", s1_location, s2_location)\n\n\ndef merge_blocs_by_location(blocks, max_blocks, max_span, reference=\"s2\"):\n while 1:\n for i in range(len(blocks) - max_blocks):\n subblocks = blocks[i : i + max_blocks]\n b1, b2 = subblocks[0], subblocks[-1]\n if reference == \"s2\":\n span = b2.s2_location.end - b1.s2_location.start\n else:\n span = b2.s1_location.end - b1.s1_location.start\n if span < max_span:\n new_block = merge_subblocks(subblocks)\n blocks = blocks[:i] + [new_block] + blocks[i + max_blocks :]\n break\n else:\n break\n return blocks\n\n\ndef merge_successive_blocks(blocks, change_gap=10, replace_gap=5, reference=\"s2\"):\n while 1:\n for i in range(len(blocks) - 1):\n b1, b2 = blocks[i], blocks[i + 1]\n operations = (b1.operation, b2.operation)\n if reference == \"s2\":\n gap = b2.s2_location.start - b1.s2_location.end\n else:\n gap = b2.s1_location.start - b1.s1_location.end\n if \"equal\" in operations:\n continue\n if \"change\" in operations and (gap < change_gap):\n new_block = merge_subblocks([b1, b2])\n blocks = blocks[:i] + [new_block] + blocks[i + 2 :]\n break\n if operations == (\"replace\", \"replace\") and gap < replace_gap:\n new_block = merge_subblocks([b1, b2])\n blocks = blocks[:i] + [new_block] + blocks[i + 2 :]\n break\n else:\n break\n return blocks\n\n\ndef compute_sorted_blocks(blocks, reference=\"s2\"):\n def sort_key(block):\n if reference == \"s2\":\n return block.s2_location.to_tuple()\n else:\n return block.s1_location.to_tuple()\n\n return sorted(blocks, key=sort_key)\n\n\ndef get_optimal_common_blocks(common_blocks):\n common_blocks = deepcopy(common_blocks)\n remarks = []\n\n # Make so that there is never an antisense block in s1 and a + block in s2.\n # If it is so, flip the block in s2. It will become antisense and be later\n # removed\n for block_name, data in common_blocks.items():\n locations = data[\"locations\"]\n s1_strands = [strand for (s, (_, _, strand)) in locations if s == \"s1\"]\n if 1 not in s1_strands:\n for i, location in enumerate(locations):\n seq, (start, end, strand) = location\n if seq == \"s2\":\n locations[i] = (seq, (start, end, -strand))\n\n # Remove every antisense blocks now. For the ones in s2, log this\n # with a remark.\n for block_name, data in common_blocks.items():\n locations = data[\"locations\"]\n for i, location in enumerate(locations):\n (seq, (start, end, strand)) = location\n if seq == \"s2\" and (strand == -1):\n locations.remove(location)\n _, (start1, end1, strand1) = locations[0]\n remarks.append(\n DiffBlock(\n \"reverse\",\n s1_location=Location(start1, end1, strand1),\n s2_location=Location(start, end),\n )\n )\n\n # We start the structure that will be returned in the end\n blocks_in_seqs = {\n seq: sorted(\n [\n (start, end, bname)\n for bname, data in common_blocks.items()\n for (s, (start, end, strand)) in data[\"locations\"]\n if s == seq\n ]\n )\n for seq in (\"s1\", \"s2\")\n }\n\n # Identify blocks appearing only in one of the two sequences\n blocks_in_s1 = set(b[-1] for b in blocks_in_seqs[\"s1\"])\n blocks_in_s2 = set(b[-1] for b in blocks_in_seqs[\"s2\"])\n uniblocks = (blocks_in_s1.union(blocks_in_s2)).difference(\n blocks_in_s1.intersection(blocks_in_s2)\n )\n\n # Remove blocks appearing only in one of the two sequences\n # as they are useless for sequences comparison\n # this should be very rare but you never know.\n for block_list in blocks_in_seqs.values():\n for b in block_list:\n if b[-1] in uniblocks:\n block_list.remove(b)\n\n for b1, b2 in zip(block_list, block_list[1:]):\n start1, end1, __name1 = b1\n start2, end2, __name2 = b2\n if end2 <= end1:\n block_list.remove(b2)\n\n # If a block appears several time in a sequence (self-homology)\n # give unique names to each occurence: block_1, block_1*, etc.\n blocks_in_seqs_dicts = dict(s1={}, s2={})\n for seq, blocks_list in list(blocks_in_seqs.items()):\n seen_blocks = set()\n for i, (start, end, block_name) in enumerate(blocks_list):\n while block_name in seen_blocks:\n block_name = block_name + \"*\"\n blocks_list[i] = start, end, block_name\n blocks_in_seqs_dicts[seq][block_name] = dict(rank=i, location=(start, end))\n seen_blocks.add(block_name)\n\n # Find and retain the largest sequence of blocks which is in the right\n # order in both sequences. We will remove every other block.\n # We do that by looking for the longest path in a graph\n\n if len(blocks_in_seqs_dicts[\"s2\"]) < 2:\n retained_blocks = list(blocks_in_seqs_dicts[\"s2\"])\n else:\n s1_dict = blocks_in_seqs_dicts[\"s1\"]\n graph = nx.DiGraph(\n [\n (b1, b2)\n for b1, data1 in blocks_in_seqs_dicts[\"s2\"].items()\n for b2, data2 in blocks_in_seqs_dicts[\"s2\"].items()\n if (b2 in s1_dict)\n and (b1 in s1_dict)\n and (s1_dict[b2][\"rank\"] > s1_dict[b1][\"rank\"])\n and (data2[\"rank\"] > data1[\"rank\"])\n ]\n )\n retained_blocks = nx.dag_longest_path(graph)\n\n # remove any \"misplaced\" block that is not in the retained list.\n # log a remark for the ones in s2.\n for seq in (\"s1\", \"s2\"):\n blocks_list = blocks_in_seqs[seq]\n for block in list(blocks_list): # copy cause we will remove elements\n start, end, block_name = block\n if block_name not in retained_blocks:\n blocks_list.remove(block)\n if seq == \"s2\":\n new_block_name = block_name.strip(\"*\")\n s1_blocks = blocks_in_seqs_dicts[\"s1\"]\n s1_loc = s1_blocks[new_block_name][\"location\"]\n start1, end1 = s1_loc\n if (\n len(remarks)\n and (start == remarks[-1].s2_location.end)\n and (start1 == remarks[-1].s1_location.end)\n ):\n remarks[-1].s1_location.end = end1\n remarks[-1].s2_location.end = end\n else:\n remarks.append(\n DiffBlock(\n \"transpose\",\n s1_location=Location(start1, end1),\n s2_location=Location(start, end),\n )\n )\n\n # Reduce blocks when there is overlap\n blocks_to_reduce = {}\n for seq in (\"s1\", \"s2\"):\n blocks_list = blocks_in_seqs[seq]\n for b1, b2 in zip(blocks_list, blocks_list[1:]):\n start1, end1, block_name1 = b1\n start2, end2, __block_name2 = b2\n diff = end1 - start2\n if diff > 0:\n if block_name1 not in blocks_to_reduce:\n blocks_to_reduce[block_name1] = 0\n blocks_to_reduce[block_name1] = max(blocks_to_reduce[block_name1], diff)\n\n for seq in (\"s1\", \"s2\"):\n blocks_list = blocks_in_seqs[seq]\n for i, (start, end, block_name) in enumerate(blocks_list):\n if block_name in blocks_to_reduce:\n diff = blocks_to_reduce[block_name]\n blocks_list[i] = (start, end - diff, block_name)\n\n return blocks_in_seqs, remarks\n" }, { "alpha_fraction": 0.5413970351219177, "alphanum_fraction": 0.5527217388153076, "avg_line_length": 33.006473541259766, "blob_id": "4308e34fea25e48bfb91d60765cea725406b4ab9", "content_id": "fef17389d2a33a401af2d95987bc60f31ca0435d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10508, "license_type": "permissive", "max_line_length": 88, "num_lines": 309, "path": "/geneblocks/CommonBlocks/commonblocks_tools.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "\"\"\"Algorithmic methods for the selection of common blocks in DiffBlocks\n\n- select_common_blocks\n -\n - segments_difference\n\"\"\"\n\nimport re\nimport tempfile\nimport subprocess\nfrom collections import defaultdict, OrderedDict\n\nimport numpy as np\nfrom ..biotools import reverse_complement, sequence_to_record\n\n\ndef format_sequences_as_dicts(sequences):\n \"\"\"Standardize different formats into a single one.\n\n\n The ``sequences`` can be either:\n - A list [('sequence_id', 'ATGC...'), ('sequence_2', ...)]\n - A list of Biopython records (all with different IDs)\n - A dict {'sequence_id': \"ATGC...\"}\n - A dict {'sequence_id': biopython_record}\n\n The output is a tuple (sequences_dict, records_dict), where\n - sequences_dict is of the form {'sequence_id': 'ATGC...'}\n - sequences_dict is of the form {'sequence_id': 'ATGC...'}\n \"\"\"\n if isinstance(sequences, (list, tuple)):\n if hasattr(sequences[0], \"seq\"):\n # SEQUENCES = LIST OF RECORDS\n records_dict = OrderedDict([(record.id, record) for record in sequences])\n sequences_dict = OrderedDict(\n [(record.id, str(record.seq).upper()) for record in sequences]\n )\n else:\n # SEQUENCES = LIST OF ATGC STRINGS\n sequences_dict = OrderedDict(sequences)\n if isinstance(list(sequences_dict.values())[0], str):\n records_dict = OrderedDict(\n [\n (name, sequence_to_record(seq, name=name))\n for name, seq in sequences_dict.items()\n ]\n )\n else:\n records_dict = sequences\n elif hasattr(list(sequences.values())[0], \"seq\"):\n # SEQUENCES = DICT {SEQ_ID: RECORD}\n records_dict = OrderedDict(sorted(sequences.items()))\n sequences_dict = OrderedDict(\n [\n (record_id, str(record.seq).upper())\n for record_id, record in sequences.items()\n ]\n )\n else:\n # SEQUENCES = DICT {SEQ_ID: ATGC}\n sequences_dict = OrderedDict(sorted(sequences.items()))\n records_dict = OrderedDict(\n [\n (name, sequence_to_record(seq, name=name))\n for name, seq in sequences.items()\n ]\n )\n return sequences_dict, records_dict\n\n\ndef segments_difference(segment, subtracted):\n \"\"\"Return the difference between segment (start, end) and subtracted.\n\n The result is a list containing either zero, one, or two segments of the\n form (start, end).\n\n Examples\n --------\n\n >>> segment=(10, 100), subtracted=(0, 85) => [(85, 100)]\n >>> segment=(10, 100), subtracted=(40, 125) => [(10, 40)]\n >>> segment=(10, 100), subtracted=(30, 55) => [(10, 30), (55, 100)]\n >>> segment=(10, 100), subtracted=(0, 150) => []\n \"\"\"\n seg_start, seg_end = segment\n sub_start, sub_end = subtracted\n result = []\n if sub_start > seg_start:\n result.append((seg_start, min(sub_start, seg_end)))\n if sub_end < seg_end:\n result.append((max(seg_start, sub_end), seg_end))\n return sorted(list(set(result)))\n\n\ndef find_homologies_between_sequences(\n sequences, min_size=0, max_size=None, include_self_homologies=True\n):\n \"\"\"Return a dict listing the locations of all homologies between sequences.\n\n The result is a dict of the form below, where the sequence identifiers\n are used as keys.\n\n >>> {\n >>> 'seq_1': {\n >>> (start1, end1): [('seq2_5', _start, _end), ('seq_3', )...]\n >>> (start2, end2): ...\n >>> }\n >>> }\n\n Parameters\n ----------\n\n sequences\n A dict {'sequence_id': 'ATTGTGCAG...'}.\n\n min_size, max_size\n Minimum and maximum size outside which homologies will be ignored.\n\n include_self_homologies\n If False, self-homologies will be removed from the list.\n \"\"\"\n\n # BLAST THE SEQUENCES USING NCBI-BLAST\n\n temp_fasta_path = tempfile.mktemp(\".fa\")\n\n with open(temp_fasta_path, \"w+\") as f:\n f.write(\n \"\\n\\n\".join(\n [\"> %s\\n%s\" % (name, seq.upper()) for name, seq in sequences.items()]\n )\n )\n proc = subprocess.Popen(\n [\n \"blastn\",\n \"-query\",\n temp_fasta_path,\n \"-subject\",\n temp_fasta_path,\n \"-perc_identity\",\n \"100\",\n \"-dust\",\n \"no\",\n \"-evalue\",\n \"1000000000000000\",\n \"-culling_limit\",\n \"10\",\n \"-ungapped\",\n \"-outfmt\",\n \"6 qseqid qstart qend sseqid sstart send\",\n ],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n result, __blast_err = proc.communicate()\n\n # PARSE THE RESULT FROM BLAST\n\n parsing = [line.split(\"\\t\") for line in result.decode(\"utf-8\").splitlines()]\n homologies = {name: defaultdict(lambda *a: []) for name, seq in sequences.items()}\n\n # FILTER THE RESULTS (MIN_SIZE, MAX_SIZE, SELF-HOMOLOGIES)\n\n for query, qstart, qend, subject, sstart, send in parsing:\n is_self_homology = (query == subject) and (qstart != sstart)\n if is_self_homology and (not include_self_homologies):\n continue\n qstart, qend = int(qstart) - 1, int(qend)\n sstart, send = int(sstart) - 1, int(send)\n if qend - qstart < min_size:\n continue\n if (max_size is not None) and (qend - qstart > max_size):\n continue\n location = (subject, sstart, send)\n homologies[query][(qstart, qend)].append(location)\n return homologies\n\n\ndef count_homologies(matches, min_size):\n \"\"\"Return a dict {(start, end): number_of_homologies_count}.\n \"\"\"\n homologies_counts = {}\n if len(matches) == 1:\n segment = list(matches.keys())[0]\n homologies_counts[segment] = 1\n matches_list = sorted(matches.keys())\n for i, match1 in enumerate(matches_list):\n for match2 in matches_list[i + 1 :]:\n segment = start, end = (match2[0], min(match1[1], match2[1]))\n if end < start:\n # The segment is empty, match1 and match2 as disjunct.\n break\n elif (end - start > min_size) and (segment not in homologies_counts):\n homologies_counts[segment] = len(\n [\n matching\n for (match_start, match_end) in matches_list\n for matching in matches[(match_start, match_end)]\n if match_start <= start <= end <= match_end\n ]\n )\n return homologies_counts\n\n\ndef segment_with_most_homologies(homologies_counts, method=\"most_coverage_first\"):\n \"\"\"Select the \"best\" segment, that should be selected next as a common\n block.\"\"\"\n\n def segment_score(segment):\n if method == \"most_coverage_first\":\n factor = homologies_counts[segment]\n else:\n factor = 1\n start, end = segment\n return factor * (end - start)\n\n return max(\n [(0, (None, None))]\n + [(segment_score(segment), segment) for segment in homologies_counts]\n )\n\n\ndef select_common_blocks(\n homologies, sequences, min_size=0, method=\"most_coverage_first\"\n):\n \"\"\"Select a collection of the largest common blocks, iteratively.\"\"\"\n common_blocks = []\n homologies_counts = {\n seqname: count_homologies(matches=homologies[seqname], min_size=min_size)\n for seqname in sequences\n }\n\n # ITERATIVELY SELECT A COMMON BLOCK AND REMOVE THAT BLOCK FROM THE\n # homologies IN VARIOUS SEQUENCES, UNTIL THERE IS NO HOMOLOGY\n\n while True:\n\n # FIND THE HOMOLOGY WITH THE BEST OVERALL SCORE ACROSS ALL SEQS\n\n (best_score, (start, end)), seqname = max(\n [\n (\n segment_with_most_homologies(\n homologies_counts[seqname], method=method\n ),\n seqname,\n )\n for seqname in sequences\n ]\n )\n\n # IF NO HOMOLOGY WAS FOUND AT ALL, STOP\n\n if best_score == 0:\n break\n\n # FIND WHERE THE SELECTED SUBSEQUENCE APPEARS IN OTHER SEQUENCES.\n # AT EACH LOCATION, \"EXTRUDE\" THE SUBSEQUENCE FROM THE CURRENT\n # LOCATIONS IN homologies_counts\n\n best_subsequence = sequences[seqname][start:end]\n locations = []\n for seqname, sequence in sequences.items():\n seq_n_intersections = homologies_counts[seqname]\n\n # we look for both the subsequence and its reverse complement:\n for strand in [1, -1]:\n if strand == 1:\n matches = re.finditer(best_subsequence, sequence)\n else:\n matches = re.finditer(\n reverse_complement(best_subsequence), sequence\n )\n for match in matches:\n\n # add the location to the list for this subsequence...\n start, end = match.start(), match.end()\n locations.append((seqname, (start, end, strand)))\n\n # ...then subtract the location from the sequence's\n # homologies list\n match_as_segment = tuple(sorted([start, end]))\n for intersection in list(seq_n_intersections.keys()):\n score = seq_n_intersections.pop(intersection)\n for diff in segments_difference(intersection, match_as_segment):\n diff_start, diff_end = diff\n if diff_end - diff_start > min_size:\n seq_n_intersections[diff] = score\n common_blocks.append((best_subsequence, locations))\n\n # REMOVE SELF-HOMOLOGOUS SEQUENCES\n\n common_blocks = [\n (seq, locations) for (seq, locations) in common_blocks if len(locations) >= 2\n ]\n\n # CREATE THE FINAL COMMON_BLOCKS_DICT\n\n common_blocks_dict = OrderedDict()\n if len(common_blocks) > 0:\n number_size = int(np.log10(len(common_blocks))) + 1\n for i, (sequence, locations) in enumerate(common_blocks):\n block_name = \"block_%s\" % (str(i + 1).zfill(number_size))\n common_blocks_dict[block_name] = {\n \"sequence\": sequence,\n \"locations\": locations,\n }\n\n return common_blocks_dict\n" }, { "alpha_fraction": 0.6650164723396301, "alphanum_fraction": 0.6971946954727173, "avg_line_length": 36.84375, "blob_id": "c5c28d7866fefa837c4930957b7e39f40750ad51", "content_id": "92d0600174333ddc1ec1ea6126c83aaf8549d045", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1212, "license_type": "permissive", "max_line_length": 75, "num_lines": 32, "path": "/tests/test_utils.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "from geneblocks.utils import sequences_are_circularly_equal\nfrom Bio import SeqIO\nimport os\n\nthis_directory = os.path.dirname(os.path.realpath(__file__))\n\n\ndef test_sequences_are_circularly_equal():\n\n block_1 = \"ATGTGCACACGCACCGTGTGTGCACACACGTGTGCACACACGTGCACACGGTGT\"\n block_2 = \"ACACACATATACGCGTGCGTGCAAAACACATTTTACACGGCACGTGCA\"\n block_3 = \"ACCCACACTTTGTGTCGCGCACACGTGTG\"\n\n # Three rotated sequences\n seq_1 = block_1 + block_2 + block_3\n seq_2 = block_2 + block_3 + block_1\n seq_3 = block_3 + block_1 + block_2\n\n # Sequences not equivalent to the previous\n seq_4 = block_2 + block_3 + block_1 + \"A\"\n seq_5 = block_1 + block_2 + block_2 + block_3\n\n assert sequences_are_circularly_equal([seq_1, seq_2])\n assert sequences_are_circularly_equal([seq_1, seq_2, seq_3])\n assert not sequences_are_circularly_equal([seq_1, seq_2, seq_3, seq_4])\n assert not sequences_are_circularly_equal([seq_1, seq_5])\n\ndef test_long_equivalents():\n \"\"\"Test with two 12kb sequences with only a 10bp shift\"\"\"\n path = os.path.join(this_directory, \"sequences\", \"long_equivalents.fa\")\n seq_a, seq_b = SeqIO.parse(path, 'fasta')\n assert sequences_are_circularly_equal([seq_a, seq_b])\n\n" }, { "alpha_fraction": 0.6410256624221802, "alphanum_fraction": 0.6410256624221802, "avg_line_length": 14.800000190734863, "blob_id": "20aff64635387f0c4fd04a5f41491a66c40035ff", "content_id": "a33d63b1143cba3d6fee34e1e1dc0428330d6112", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 78, "license_type": "permissive", "max_line_length": 38, "num_lines": 5, "path": "/docs/ref/CommonBlocks.rst", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "CommonBlocks\n------------\n\n.. autoclass:: geneblocks.CommonBlocks\n :members:" }, { "alpha_fraction": 0.803680956363678, "alphanum_fraction": 0.803680956363678, "avg_line_length": 40, "blob_id": "83ef24671a9b4e06ff95f8009e1f7f7d637ee970", "content_id": "a66fe52c8e7fb866a303fd8d8eff87cd588894fa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 163, "license_type": "permissive", "max_line_length": 61, "num_lines": 4, "path": "/geneblocks/DiffBlocks/__init__.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "from .DiffBlocks import DiffBlocks, DiffBlock\nfrom .DiffRecordTranslator import DiffRecordTranslator\n\n__all__ = ['DiffBlocks', 'DiffBlock', 'DiffRecordTranslator']" }, { "alpha_fraction": 0.6031128168106079, "alphanum_fraction": 0.6586992740631104, "avg_line_length": 37.27659606933594, "blob_id": "951a62a2f1586c08d229b793aa3ae7bacd4251a2", "content_id": "b1cc6d723589329d39b6aea4c23c185f847de416", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3598, "license_type": "permissive", "max_line_length": 86, "num_lines": 94, "path": "/tests/test_scenarios.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "import os\nimport matplotlib\nimport networkx as nx\nfrom geneblocks import CommonBlocks, DiffBlocks, load_record\nfrom geneblocks.biotools import reverse_complement, random_dna_sequence\nfrom geneblocks.DiffBlocks import DiffBlock\nfrom geneblocks.Location import Location\n\nmatplotlib.use(\"Agg\")\n\n\ndef test_CommonBlocks_basics(tmpdir):\n C1, A, B, C2, C3, D, E, F = [random_dna_sequence(100 * L) for L in range(1, 9)]\n\n sequences = {\n \"a\": C1 + A + C2,\n \"b\": B + D + C2 + C3,\n \"c\": E + C1 + C2,\n \"d\": C2 + C1 + F + C3,\n \"e\": C3 + reverse_complement(C2 + C1),\n }\n\n common_blocks = CommonBlocks.from_sequences(sequences)\n assert len(common_blocks.common_blocks) == 3\n\n axes = common_blocks.plot_common_blocks()\n fig_path = os.path.join(str(tmpdir), \"basic_example.png\")\n axes[0].figure.savefig(fig_path, bbox_inches=\"tight\")\n\n # GET ALL COMMON BLOCKS AS BIOPYTHON RECORDS\n _ = common_blocks.common_blocks_records()\n _ = common_blocks.unique_blocks_records()\n\n # WRITE ALL COMMON BLOCKS INTO A CSV SPREADSHEET\n csv_path = os.path.join(str(tmpdir), \"basic_example.csv\")\n common_blocks.common_blocks_to_csv(target_file=csv_path)\n\n\ndef test_DiffBlocks_basics(tmpdir):\n seq_1 = load_record(os.path.join(\"tests\", \"sequences\", \"sequence1.gb\"))\n seq_2 = load_record(os.path.join(\"tests\", \"sequences\", \"sequence2.gb\"))\n\n diff_blocks = DiffBlocks.from_sequences(seq_1, seq_2).merged()\n # next line is just to cover separate_axes=false\n diff_blocks.plot(figure_width=8, separate_axes=False)\n ax1, __ax2 = diff_blocks.plot(figure_width=8)\n fig_path = os.path.join(str(tmpdir), \"diff_blocks.png\")\n ax1.figure.savefig(fig_path, bbox_inches=\"tight\")\n assert list(map(str, diff_blocks.blocks)) == [\n \"insert 0-0|0-120\",\n \"equal 0-1000|120-1120\",\n \"replace 1000-1004|1120-1124\",\n \"equal 1004-1503|1124-1623\",\n \"insert 1503-1503|1623-1723\",\n \"equal 1503-2304|1723-2524\",\n \"delete 2304-2404|2524-2524\",\n \"equal 2404-3404|2524-3524\",\n ]\n\n\ndef test_features_transfer():\n seq_folder = os.path.join(\"tests\", \"sequences\", \"features_transfer\")\n insert = load_record(os.path.join(seq_folder, \"insert.gb\"), name=\"insert\")\n plasmid = load_record(\n os.path.join(seq_folder, \"plasmid_to_annotate.gb\"), name=\"plasmid\"\n )\n blocks = CommonBlocks.from_sequences([insert, plasmid])\n records = blocks.copy_features_between_common_blocks(inplace=False)\n assert len(records[\"plasmid\"].features) == 6\n assert len(plasmid.features) == 2\n blocks.copy_features_between_common_blocks(inplace=True)\n assert len(plasmid.features) == 6\n\n\ndef test_networkx_dag_longest_path():\n # Github issue #7\n # networkx >=2.6 has a different correct output. This test catches future changes.\n test_graph = nx.DiGraph([(\"block_1\", \"block_3\"), (\"block_1\", \"block_2\")])\n assert nx.dag_longest_path(test_graph) == [\"block_1\", \"block_3\"]\n\n\ndef test_good_management_of_homologies():\n \"\"\"This checks for a former obscure bug where a sequence with 2 homologies\n in seq2 corresponding to a single sequence in s1 used to cause an index\n error due to the \"*\" added by the algorithm to the end of homologies.\"\"\"\n # See also Github issue #7\n b1 = random_dna_sequence(4000, seed=123)\n b2 = random_dna_sequence(4000, seed=234)\n b3 = random_dna_sequence(4000, seed=345)\n seq1 = b1 + \"A\" + \"T\" + b2 + b3\n seq2 = \"T\" + b1 + \"T\" + b3 + b2 + b1 + b1\n\n blocks = DiffBlocks.from_sequences(seq1, seq2).merged()\n assert len(blocks.blocks) == 9\n" }, { "alpha_fraction": 0.6578212380409241, "alphanum_fraction": 0.6578212380409241, "avg_line_length": 26.538461685180664, "blob_id": "cc30face7753bc84dc1a77ba77bc5ed830ce0d66", "content_id": "defcdd6ec0281d3311a99e461140ee3e09f752d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 716, "license_type": "permissive", "max_line_length": 79, "num_lines": 26, "path": "/setup.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "import ez_setup\n\nez_setup.use_setuptools()\n\nfrom setuptools import setup, find_packages\n\nexec(open(\"geneblocks/version.py\").read()) # loads __version__\n\nsetup(\n name=\"geneblocks\",\n version=__version__,\n author=\"Zulko\",\n description=\"Library to compare DNA sequences (diff, common blocks, etc.)\",\n long_description=open(\"pypi-readme.rst\").read(),\n license=\"MIT\",\n url=\"https://github.com/Edinburgh-Genome-Foundry/geneblocks\",\n keywords=\"DNA sequence blocks diff synthetic-biology bioinformatics\",\n packages=find_packages(exclude=\"docs\"),\n install_requires=[\n \"numpy\",\n \"Biopython\",\n \"dna_features_viewer\",\n \"networkx\",\n \"python-Levenshtein\",\n ],\n)\n" }, { "alpha_fraction": 0.7854597568511963, "alphanum_fraction": 0.7854597568511963, "avg_line_length": 86.6875, "blob_id": "a293b7faafb26e423534540371a9eb6f13968705", "content_id": "72205c95cca8c2868caaff1a74c8306da2686ba9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1403, "license_type": "permissive", "max_line_length": 186, "num_lines": 16, "path": "/geneblocks/README.md", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "# Code organisation\n\nThis document walks you trough the Geneblocks code. Please request changes if anything is unclear.\n\n- **CommonBlocks/** implements the CommonBlocks class. The code is separated in two files:\n - **commonblocks_tools.py** implements the (rather long) algorithms to extract common blocks from a set of sequences.\n - **CommonBlocks.py** implements the CommonBlocks class, which stores a set of common blocks and provides methods to display them or export them as Genbank.\n\n- **DiffBlocks/** implements the DiffBlocks class. The code is separated in several files:\n - **DiffBlock.py** implements a class to store a unit diff block (sequence location and edit operation), as well as methods to pretty-print the block or export it as a Genbank feature.\n - **diffblocks_tools.py** implements the (rather long) algorithms to identify different diffblocks using the Levenshtein algorithm, and merge various diffblocks together.\n - **DiffBlocks.py** implements the CommonBlocks class, which stores a set of common blocks and provides methods to display them or export them as Genbank.\n\n- **biotools.py** implements methods related to sequence and Genbank record analysis and manipulation (reverse_complement, BLAST).\n\n- **sequence_modification_utils.py** implements a collection of sequence manipulation routines (to insert, delete, replace fragments), only to create examples and tests.\n" }, { "alpha_fraction": 0.6862027049064636, "alphanum_fraction": 0.7106227278709412, "avg_line_length": 33.66666793823242, "blob_id": "87df16bb62b7e2af46a12b715456825b6225c3c9", "content_id": "aafee9df63a7821a86b87071b6c3eb3b70a79f3b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 6552, "license_type": "permissive", "max_line_length": 175, "num_lines": 189, "path": "/README.rst", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": ".. raw:: html\n\n <p align=\"center\">\n <img alt=\"Geneblocks Logo\" title=\"Geneblocks\" src=\"https://raw.githubusercontent.com/Edinburgh-Genome-Foundry/Geneblocks/master/docs/_static/images/title.png\" width=\"450\">\n <br /><br />\n </p>\n\nGeneBlocks\n==========\n\n.. image:: https://github.com/Edinburgh-Genome-Foundry/Geneblocks/actions/workflows/build.yml/badge.svg\n :target: https://github.com/Edinburgh-Genome-Foundry/Geneblocks/actions/workflows/build.yml\n :alt: GitHub CI build status\n\n.. image:: https://coveralls.io/repos/github/Edinburgh-Genome-Foundry/Geneblocks/badge.svg\n :target: https://coveralls.io/github/Edinburgh-Genome-Foundry/Geneblocks\n\nGeneBlocks is a Python library for comparing DNA sequences. It can be used to:\n\n- Find common blocks in a group of DNA sequences, to factorize them (e.g. only analyze or synthetize each common block once).\n- Highlight differences between sequences (insertions, deletions, mutations).\n- Transfer Genbank features from one record to another sharing similar subsequences.\n\nAt the Edinburgh Genome Foundry, we use GeneBlocks to optimize sequence assembly, explore sets of non-annotated sequences, or visualize the differences\nbetween different versions of a sequence, and re-annotate records coming from third parties such as DNA manufacturers.\n\nLive demos\n----------\n\n`Find common sequence blocks <https://cuba.genomefoundry.org/find-common-blocks>`_\n\n`Plot sequence diffs <https://cuba.genomefoundry.org/compare-two-sequences>`_\n\n`Transfer Genbank features between records <https://cuba.genomefoundry.org/transfer-features>`_\n\nInstallation\n------------\n\nThe CommonBlocks feature requires NCBI BLAST+. On Ubuntu, install it with\n\n.. code:: shell\n\n apt-get install ncbi-blast+\n\n\nYou can install GeneBlocks through PIP:\n\n.. code:: shell\n\n pip install geneblocks\n\nAlternatively, you can unzip the sources in a folder and type:\n\n.. code:: shell\n\n python setup.py install\n\n\nUsage\n-----\n\n\nFinding common blocks in a set of sequences:\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. code:: python\n\n from geneblocks import CommonBlocks\n\n # Input sequences are in a dictionary as follows:\n sequences = {'seq1': 'ATTTGCGT', 'seq2': 'ATGCCCGCACG',} # etc\n\n common_blocks = CommonBlocks.from_sequences(sequences)\n\n # PLOT THE BLOCKS\n axes = common_blocks.plot_common_blocks()\n axes[0].figure.savefig(\"basic_example.png\", bbox_inches=\"tight\")\n\n # GET ALL COMMON BLOCKS AS BIOPYTHON RECORDS\n blocks_records = common_blocks.common_blocks_records()\n\n # WRITE ALL COMMON BLOCKS INTO A CSV SPREADSHEET\n common_blocks.common_blocks_to_csv(target_file=\"blocks.csv\")\n\nResult:\n\n.. raw:: html\n \n <img src='https://raw.githubusercontent.com/Edinburgh-Genome-Foundry/GeneBlocks/master/examples/common_blocks.png'\n width='600px'/>\n\nTransferring features between genbank records:\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn this snippet we assume that we have two genbank records:\n\n- A record of an annotated part, containing an expression module.\n- A record of a plasmid which contains the part but the part was not properly annotated.\n\nWe will use Geneblocks to automatically detect where the part is located in\nthe plasmid and automatically copy the features from the part record to the\nplasmid record.\n\n.. code:: python\n\n from geneblocks import CommonBlocks, load_record\n part = load_record('part.gb', name='insert')\n plasmid = load_record('part.gb', name='plasmid')\n blocks = CommonBlocks.from_sequences([part, plasmid])\n new_records = blocks.copy_features_between_common_blocks(inplace=False)\n annotated_plasmid = new_records['plasmid'] # Biopython record\n\n\nThe resulting annotated plasmids has annotations from both the original plasmid and the annotated part:\n\n.. raw:: html\n \n <img src='https://raw.githubusercontent.com/Edinburgh-Genome-Foundry/GeneBlocks/master/examples/features_transfer.png'\n width='600px'/>\n\nHighlighting the differences between two sequences:\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. code:: python\n\n seq_1 = load_record(\"sequence1.gb\")\n seq_2 = load_record(\"sequence2.gb\")\n\n diff_blocks = DiffBlocks.from_sequences(seq_1, seq_2)\n ax1, ax2 = diff_blocks.merged().plot(figure_width=8)\n ax1.figure.savefig(\"diff_blocks.png\")\n\nResult:\n\n.. raw:: html\n \n <img src='https://raw.githubusercontent.com/Edinburgh-Genome-Foundry/GeneBlocks/master/examples/diff_blocks.png'\n width='700px'/>\n\nExample on more complex sequences\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn the example below we build two ~50kb \"sister\" sequences with many insertions,\ndeletions, transpositions between them, and even a self-homology. Then we ask\nGeneblocks to compare the two sequences, in term of common blocks, and in terms\nof modifications brought to the second sequence:\n\n.. code:: python\n\n from geneblocks import DiffBlocks, CommonBlocks, random_dna_sequence\n import geneblocks.sequence_modification_utils as smu\n import matplotlib.pyplot as plt\n\n # GENERATE 2 \"SISTER\" SEQUENCES FOR THE EXAMPLE\n seq1 = random_dna_sequence(50000)\n seq1 = smu.copy(seq1, 25000, 30000, 50000)\n\n seq2 = seq1\n seq2 = smu.insert(seq2, 39000, random_dna_sequence(100))\n seq2 = smu.insert(seq2, 38000, random_dna_sequence(100))\n seq2 = smu.reverse(seq2, 30000, 35000)\n seq2 = smu.swap(seq2, (30000, 35000), (45000, 480000))\n seq2 = smu.delete(seq2, 20000, 2000)\n seq2 = smu.insert(seq2, 10000, random_dna_sequence(2000))\n seq2 = smu.insert(seq2, 0, 1000*\"A\")\n\n # FIND COMMON BLOCKS AND DIFFS\n common_blocks = CommonBlocks.from_sequences({'seq1': seq1, 'seq2': seq2})\n diff_blocks = DiffBlocks.from_sequences(seq1, seq2).merged()\n\n # PLOT EVERYTHING\n fig, axes = plt.subplots(3, 1, figsize=(15, 8))\n common_blocks.plot_common_blocks(axes=axes[:-1])\n diff_blocks.plot(ax=axes[-1], separate_axes=False)\n axes[-1].set_xlabel(\"Changes in seq2 vs. seq1\")\n fig.savefig(\"complex_sequences.png\", bbox_inches='tight')\n\n.. raw:: html\n \n <img src='https://raw.githubusercontent.com/Edinburgh-Genome-Foundry/GeneBlocks/master/examples/complex_sequences.png'\n width='700px'/>\n\nLicense = MIT\n-------------\n\nGeneblocks is an open-source software originally written at the `Edinburgh Genome Foundry\n<http://www.genomefoundry.org>`_ by `Zulko <https://github.com/Zulko>`_\nand `released on Github <https://github.com/Edinburgh-Genome-Foundry/Geneblocks>`_ under the MIT license (Copyright 2017 Edinburgh Genome Foundry).\nEveryone is welcome to contribute!\n" }, { "alpha_fraction": 0.5266969203948975, "alphanum_fraction": 0.533073902130127, "avg_line_length": 33.78195571899414, "blob_id": "658ec67986fea4a7f0a474151aa49d1c9ac08466", "content_id": "e665ebcdcd2b4a6ef1ce567aa0f35f86ce83393f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9252, "license_type": "permissive", "max_line_length": 84, "num_lines": 266, "path": "/geneblocks/CommonBlocks/CommonBlocks.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "\"\"\"Defines central class BlockFinder.\"\"\"\nimport itertools\nfrom collections import OrderedDict\nfrom copy import deepcopy\n\n\nfrom .CommonBlocksRecordTranslator import CommonBlocksRecordTranslator\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\nfrom ..biotools import annotate_record\n\nfrom .commonblocks_tools import (\n format_sequences_as_dicts,\n select_common_blocks,\n find_homologies_between_sequences,\n)\n\n# TODO: Simplify the code by using the new Location class in Location.py\n\n\nclass CommonBlocks:\n \"\"\"Class to represent a set of common blocks from different sequences.\n\n Create with ``CommonBlocks.from_sequences``:\n\n >>> common_blocks = CommonBlocks.from_sequences({'s1': 'ATGC...'})\n\n Parameters\n ----------\n\n common_blocks\n A dictionary of the sequences to compare, of the form\n {sequence_name: ATGC_sequence_string} or a list of records, all with\n different IDs.\n\n records\n A dictionary of the Biopython records of the sequences\n {record_id: record}.\n \"\"\"\n\n def __init__(self, common_blocks, records):\n \"\"\"Initialize, compute best blocks.\"\"\"\n self.common_blocks = common_blocks\n self.records = records\n\n @staticmethod\n def from_sequences(\n sequences,\n block_selection_method=\"most_coverage_first\",\n include_self_homologies=True,\n min_block_size=80,\n max_block_size=None,\n ):\n sequences_dict, records_dict = format_sequences_as_dicts(sequences)\n homologies_dict = find_homologies_between_sequences(\n sequences_dict,\n min_size=min_block_size,\n max_size=max_block_size,\n include_self_homologies=include_self_homologies,\n )\n common_blocks = select_common_blocks(\n homologies_dict,\n sequences_dict,\n min_size=min_block_size,\n method=block_selection_method,\n )\n return CommonBlocks(common_blocks=common_blocks, records=records_dict)\n\n def compute_unique_blocks(self):\n \"\"\"Return a dictionary listing unique blocks by sequence.\n\n The unique blocks are the blocks between the selected common blocks.\n\n The result is of the form {seq: [(start, end), (start2, end2), ...]}\n \"\"\"\n\n unique_blocks = OrderedDict()\n for seqname, rec in self.sequences_with_annotated_blocks().items():\n blocks_locations = (\n [(0, 0)]\n + sorted(\n [\n (f.location.start, f.location.end)\n for f in rec.features\n if f.qualifiers.get(\"is_block\", False)\n ]\n )\n + [(len(rec), len(rec))]\n )\n unique_blocks[seqname] = [\n (end1, start2)\n for (_, end1), (start2, _) in zip(\n blocks_locations, blocks_locations[1:]\n )\n if (start2 - end1) > 1\n ]\n return unique_blocks\n\n def common_blocks_to_csv(self, target_file=None):\n \"\"\"Write the common blocks into a CSV file.\n\n If a target CSV file is provided the result is written to that file.\n Otherwise the result is returned as a string.\n\n The columns of the CSV file are \"block\", \"size\", \"locations\", and\n sequence.\n \"\"\"\n csv_content = \"\\n\".join(\n [\"block;size;locations;sequence\"]\n + [\n \";\".join(\n [\n block_name,\n str(len(data[\"sequence\"])),\n \" \".join(\n [\n \"%s(%d, %d, %d)\" % (cst, start, end, strand)\n for (cst, (start, end, strand)) in data[\"locations\"]\n ]\n ),\n data[\"sequence\"],\n ]\n )\n for block_name, data in self.common_blocks.items()\n ]\n )\n if target_file:\n with open(target_file, \"w+\") as f:\n f.write(csv_content)\n else:\n return csv_content\n\n def common_blocks_records(self):\n \"\"\"Return all common blocks as a list of Biopython records.\n \"\"\"\n if self.records is None:\n raise ValueError(\"\")\n records = []\n for block_name, data in self.common_blocks.items():\n cst, (start, end, strand) = data[\"locations\"][0]\n record = self.records[cst][start:end]\n if strand == -1:\n record = record.reverse_complement()\n record.id = record.name = block_name\n records.append(record)\n return records\n\n def unique_blocks_records(self, target_file=None):\n \"\"\"Return all unique blocks as a list of Biopython records.\"\"\"\n if self.records is None:\n raise ValueError(\"\")\n records = []\n for seqname, locations in self.compute_unique_blocks().items():\n for i, (start, end) in enumerate(locations):\n record = self.records[seqname][start:end]\n record.id = \"%s_%03d\" % (seqname, i)\n records.append(record)\n return records\n\n def sequences_with_annotated_blocks(self, colors=\"auto\"):\n \"\"\"Return a list of Biopython records representing the sequences\n with annotations indicating the common blocks.\n\n Parameter ``colors`` is either a list of colors or \"auto\" for the\n default.\n \"\"\"\n records = deepcopy(self.records)\n if colors == \"auto\":\n colors = itertools.cycle([cm.Paired(0.21 * i % 1.0) for i in range(30)])\n blocks_and_colors = zip(self.common_blocks.items(), colors)\n for (name, data), color in blocks_and_colors:\n for (seqname, location) in data[\"locations\"]:\n annotate_record(\n records[seqname],\n location,\n feature_type=\"misc_feature\",\n is_block=True,\n label=name,\n color=color,\n )\n return records\n\n def plot_common_blocks(\n self, colors=\"auto\", axes=None, figure_width=10, ax_height=2\n ):\n \"\"\"Plot the common blocks found on vertically stacked axes.\n\n The axes on which the plots are drawn are returned at the end.\n\n Parameters\n ----------\n\n colors\n Either a list of colors to use for blocks or \"auto\" for the default.\n\n axes\n A list of matplotlib axes on which to plot, or None for new axes.\n\n figure_width\n Width of the final figure in inches.\n\n ax_eight\n Height of each plot.\n \"\"\"\n\n translator = CommonBlocksRecordTranslator()\n records = self.sequences_with_annotated_blocks(colors=colors)\n if axes is None:\n fig, axes = plt.subplots(\n len(self.records),\n 1,\n facecolor=\"white\",\n sharex=True,\n figsize=(figure_width, ax_height * len(self.records)),\n )\n else:\n fig = axes[0].figure\n for (ax, (seqname, record)) in zip(axes, records.items()):\n gr_record = translator.translate_record(record)\n gr_record.plot(\n ax,\n x_lim=(0, max([len(rec) for rec in self.records.values()])),\n with_ruler=(ax == axes[-1]),\n )\n ax.set_ylim(top=ax.get_ylim()[1])\n ax.set_title(seqname, loc=\"left\", fontdict=dict(weight=\"bold\"))\n # fig.tight_layout()\n return axes\n\n def copy_features_between_common_blocks(self, inplace=False):\n def extract_subrecord(record, location):\n start, end, strand = location\n record = record[start:end]\n if strand == -1:\n record = record.reverse_complement()\n return record\n\n def extract_features(record, offset, reverse=False):\n if reverse:\n record = record.reverse_complement()\n new_features = [deepcopy(f) for f in record.features]\n for f in new_features:\n f.qualifiers[\"original_record\"] = record.id\n for f in new_features:\n f.location += offset\n return new_features\n\n if inplace:\n records = self.records\n else:\n records = deepcopy(self.records)\n for data in self.common_blocks.values():\n locations = data[\"locations\"]\n subrecords = {\n rec_id: extract_subrecord(records[rec_id], location)\n for rec_id, location in data[\"locations\"]\n }\n for l1, l2 in itertools.combinations(locations, 2):\n for ((id1, loc1), (id2, __loc2)) in ((l1, l2), (l2, l1)):\n start1, __end1, strand1 = loc1\n # start2, end2, strand2 = loc2\n records[id1].features += extract_features(\n subrecords[id2], offset=start1, reverse=(strand1 == -1)\n )\n return records\n" }, { "alpha_fraction": 0.7212681770324707, "alphanum_fraction": 0.7357991933822632, "avg_line_length": 31.913043975830078, "blob_id": "763c30dca7f774364d3e37f86deed920506b25b9", "content_id": "8470fa337beb619bfbbe9f95b1523bddcd41b5ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1514, "license_type": "permissive", "max_line_length": 78, "num_lines": 46, "path": "/examples/features_transfer.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "import os\nfrom geneblocks import CommonBlocks, load_record\nfrom dna_features_viewer import BiopythonTranslator\nimport matplotlib.pyplot as plt\n\n# LOAD THE TWO RECORDS\n\npart_path = os.path.join(\"sequences\", \"features_transfer\", \"part.gb\")\npart = load_record(part_path, name=\"part\")\nplasmid_path = os.path.join(\n \"sequences\", \"features_transfer\", \"plasmid_to_annotate.gb\"\n)\nplasmid = load_record(plasmid_path, name=\"plasmid\")\n\n\n# TRANSFER THE FEATURES\n\nblocks = CommonBlocks.from_sequences([part, plasmid])\nnew_records = blocks.copy_features_between_common_blocks(inplace=False)\nannotated_plasmid = new_records[\"plasmid\"] # record with all features\n\n\n# PLOT ALL RECORDS\n\n\nfig, (ax0, ax1, ax2) = plt.subplots(3, 1, sharex=True, figsize=(7, 5))\nax0.set_title(\"Record 1: Annotated part\", loc=\"left\")\nax1.set_title(\"Record 2: Partially annotated plasmid\", loc=\"left\")\nax2.set_title(\"Record 2 (after) with all annotations\", loc=\"left\")\n\n\nclass SpecialBiopythonTranslator(BiopythonTranslator):\n def compute_feature_color(self, f):\n original_record = \"\".join(f.qualifiers.get(\"original_record\", \"\"))\n return \"#ffafaf\" if (original_record == \"part\") else \"#afafff\"\n\n\ntr = SpecialBiopythonTranslator()\ntr.translate_record(part).plot(ax0, with_ruler=False, x_lim=(0, len(plasmid)))\ntr.translate_record(plasmid).plot(ax1, with_ruler=False)\ntr.translate_record(annotated_plasmid).plot(ax2, with_ruler=False)\n\nfig.tight_layout()\nfig.subplots_adjust(hspace=0.6)\n\nfig.savefig(\"features_transfer.png\", dpi=125)\n" }, { "alpha_fraction": 0.69140625, "alphanum_fraction": 0.69140625, "avg_line_length": 23.380952835083008, "blob_id": "0de66f4cb9e56e968ca9f36893e35588c712c977", "content_id": "da83bf9b682a28be84baca41479a2d4a4efbe230", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 512, "license_type": "permissive", "max_line_length": 74, "num_lines": 21, "path": "/geneblocks/__init__.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "\"\"\" geneblocks/__init__.py \"\"\"\n\n# __all__ = []\n\nfrom .CommonBlocks import CommonBlocks\nfrom .DiffBlocks import DiffBlocks, DiffRecordTranslator\nfrom .biotools import load_record, random_dna_sequence, reverse_complement\nfrom .utils import sequences_are_circularly_equal\n\nfrom .version import __version__\n\n__all__ = [\n \"CommonBlocks\",\n \"DiffBlocks\",\n \"DiffRecordTranslator\",\n \"load_record\",\n \"random_dna_sequence\",\n \"reverse_complement\",\n \"sequences_are_circularly_equal\"\n \"__version__\",\n]\n" }, { "alpha_fraction": 0.7105262875556946, "alphanum_fraction": 0.7397660613059998, "avg_line_length": 37, "blob_id": "aeae6daf8b4233a4ffc5557909e4392fda155e1f", "content_id": "084b5756b29c3cb7d79d9275094b6b199b6f5b18", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 342, "license_type": "permissive", "max_line_length": 62, "num_lines": 9, "path": "/examples/diff_blocks.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "import os\nfrom geneblocks import DiffBlocks, load_record\n\nseq_1 = load_record(os.path.join(\"sequences\", \"sequence1.gb\"))\nseq_2 = load_record(os.path.join(\"sequences\", \"sequence2.gb\"))\n\ndiff_blocks = DiffBlocks.from_sequences(seq_1, seq_2)\nax1, ax2 = diff_blocks.plot(figure_width=8)\nax1.figure.savefig(\"diff_blocks.png\", bbox_inches='tight')\n" }, { "alpha_fraction": 0.6491228342056274, "alphanum_fraction": 0.6491228342056274, "avg_line_length": 10.600000381469727, "blob_id": "6ada8e13291754db489e3ac6adc7d8e57bf8724b", "content_id": "5c199e6e57576374ccd9e1e14b573c758146519f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 57, "license_type": "permissive", "max_line_length": 32, "num_lines": 5, "path": "/docs/ref/utils.rst", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "Utils\n-----\n\n.. automodule:: geneblocks.utils\n :members:" }, { "alpha_fraction": 0.5984252095222473, "alphanum_fraction": 0.6397637724876404, "avg_line_length": 30.75, "blob_id": "c9ac85ec84985f02b8acd16fe35647fde6f2c972", "content_id": "657bc763a3b932f0b2224e2d9ba2df6fdfef41c8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 508, "license_type": "permissive", "max_line_length": 79, "num_lines": 16, "path": "/examples/common_blocks.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "from geneblocks import CommonBlocks\nfrom geneblocks.biotools import reverse_complement, random_dna_sequence\n\nC1, A, B, C2, C3, D, E, F = [random_dna_sequence(100 * L) for L in range(1, 9)]\n\nsequences = {\n \"a\": C1 + A + C2,\n \"b\": B + D + C2 + C3,\n \"c\": E + C1 + C2,\n \"d\": C2 + C1 + F + C3,\n \"e\": C3 + reverse_complement(C2 + C1)\n}\n\ncommon_blocks = CommonBlocks.from_sequences(sequences)\naxes = common_blocks.plot_common_blocks()\naxes[0].figure.savefig(\"common_blocks.png\", bbox_inches=\"tight\")\n" }, { "alpha_fraction": 0.5857142806053162, "alphanum_fraction": 0.6103895902633667, "avg_line_length": 28.615385055541992, "blob_id": "78f3979355f3aa8fdfc935caeee5d77ba984d804", "content_id": "688961e3f6b2db995e98e47c591767af7dfe4fdf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 770, "license_type": "permissive", "max_line_length": 68, "num_lines": 26, "path": "/geneblocks/DiffBlocks/DiffRecordTranslator.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "from dna_features_viewer import BiopythonTranslator\n\n\nclass DiffRecordTranslator(BiopythonTranslator):\n\n ignored_features_types = (\"diff_equal\",)\n default_box_color = None\n\n @staticmethod\n def compute_feature_color(f):\n return dict(\n diff_delete=\"#E76F51\", # RED\n diff_insert=\"#2A9D8F\", # GREEN\n diff_replace=\"#E9C46A\", # YELLOW\n diff_change=\"#F4A261\", # ORANGE\n diff_reverse=\"white\",\n diff_transpose=\"white\",\n ).get(f.type, \"white\")\n\n @staticmethod\n def compute_feature_box_linewidth(f):\n return 1 if f.type.startswith(\"diff_\") else 0\n\n @staticmethod\n def compute_feature_fontdict(f):\n return {\"fontsize\": 12 if f.type.startswith(\"diff_\") else 9}\n" }, { "alpha_fraction": 0.605847954750061, "alphanum_fraction": 0.6204678416252136, "avg_line_length": 29.535715103149414, "blob_id": "0295a36caba3e318459488917f4f43c86640d877", "content_id": "99fdef9d610161216ec190008bfedf0ba7b299c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1710, "license_type": "permissive", "max_line_length": 79, "num_lines": 56, "path": "/geneblocks/sequence_modification_utils.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "\"\"\"These methods are only useful to build examples and tests for Geneblocks.\"\"\"\n\nfrom .biotools import reverse_complement\n\n\ndef change(seq, start, end, change):\n \"\"\"Return the sequence with ``seq[start:end]`` replaced by ``change``\"\"\"\n return seq[:start] + change + seq[end:]\n\n\ndef insert(seq, pos, inserted):\n \"\"\"Return the sequence with ``inserted`` inserted, starting at index 'pos'\n \"\"\"\n return seq[:pos] + inserted + seq[pos:]\n\n\ndef delete(seq, pos, deletions):\n \"\"\"Return the sequence with a number of deletions from position pos.\"\"\"\n return seq[:pos] + seq[pos + deletions :]\n\n\ndef reverse(seq, start, end):\n \"\"\"Return the sequence with segment seq[start:end] reverse-complemented.\"\"\"\n return seq[:start] + reverse_complement(seq[start:end]) + seq[end:]\n\n\ndef move(seq, start, end, diff):\n \"\"\"Move a subsequence by \"diff\" nucleotides the left or the right.\"\"\"\n sub = seq[start:end]\n if diff > 0:\n return seq[:start] + seq[end : end + diff] + sub + seq[end + diff :]\n else:\n return (\n seq[: start + diff] + sub + seq[start + diff : start] + seq[end:]\n )\n\n\ndef swap(seq, pos1, pos2):\n \"\"\"Return a new sequence with segments at position pos1 and pos2 swapped.\n\n pos1, pos2 are both of the form (start1, end1), (start2, end2)\n \"\"\"\n (start1, end1), (start2, end2) = sorted([pos1, pos2])\n return (\n seq[:start1]\n + seq[start2:end2]\n + seq[end1:start2]\n + seq[start1:end1]\n + seq[end2:]\n )\n\n\ndef copy(seq, start, end, new_start):\n \"\"\"Return the sequence with segment [start, end] also copied elsewhere,\n starting in new_start.\"\"\"\n return insert(seq, new_start, seq[start:end])\n" }, { "alpha_fraction": 0.6661490797996521, "alphanum_fraction": 0.6739130616188049, "avg_line_length": 29.66666603088379, "blob_id": "ad1333a4b55caae392e37cb751366358cca5d7c9", "content_id": "4db18237ec60869c8846e47367e875c4004616e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 644, "license_type": "permissive", "max_line_length": 77, "num_lines": 21, "path": "/geneblocks/CommonBlocks/CommonBlocksRecordTranslator.py", "repo_name": "Edinburgh-Genome-Foundry/Geneblocks", "src_encoding": "UTF-8", "text": "from dna_features_viewer import BiopythonTranslator\n\n\nclass CommonBlocksRecordTranslator(BiopythonTranslator):\n\n ignored_features_types = (\"diff_equal\",)\n default_box_color = None\n\n def compute_feature_color(self, f):\n if f.qualifiers.get(\"is_block\", False):\n return BiopythonTranslator.compute_feature_color(self, f)\n else:\n return \"white\"\n\n @staticmethod\n def compute_feature_box_linewidth(f):\n return 1 if f.qualifiers.get(\"is_block\", False) else 0\n\n @staticmethod\n def compute_feature_fontdict(f):\n return {\"fontsize\": 12 if f.qualifiers.get(\"is_block\", False) else 9}\n" } ]
31
R-Niagra/Networking-Projects
https://github.com/R-Niagra/Networking-Projects
fa39cc539f60f8eec6ee55becc19c62b810e80c3
520f0ece98e1235a5098595ce4b423854c305b68
4abe660bd639697cc6d00addd110719607c4fd5a
refs/heads/master
2022-01-30T16:02:52.227291
2022-01-21T23:00:49
2022-01-21T23:00:49
127,670,242
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5003281235694885, "alphanum_fraction": 0.5229032635688782, "avg_line_length": 17.90570640563965, "blob_id": "3ed3d69ed105c90a780d8ced90ef4a7a922c08e7", "content_id": "f387d4ee09cc5780b7db6848b5576a1d52902942", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7619, "license_type": "no_license", "max_line_length": 77, "num_lines": 403, "path": "/fileSharing/myServer.cc", "repo_name": "R-Niagra/Networking-Projects", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <sys/types.h> \n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <iostream>\n#include <dirent.h>\n#include <stdio.h>\n#include <string>\n#include <fstream>\n#include <sstream>\nusing namespace std;\nint file_size(char* filename)\n{\nifstream file( filename, ios::binary | ios::ate);\nreturn file.tellg();\n\n}\n\n//////////////////////////////\nvoid sendFileData(char* filename,int sockfd)\n{\nint index=0,w;\nstring line=\"\",fileData=\"\",fsize=\"\";\n//ifstream infile(filename.c_str());\nint fileSize=file_size(filename);\nstringstream ss;\nss<<fileSize<<endl;\nfsize=ss.str();\n\n\n if(w=write(sockfd,fsize.c_str(),fsize.length())<0)\n {\n cout<<\"Failed to send\"<<endl;\n exit(1);\n }\nsleep(0.7);\ncout<<\"File size is: \"<<fileSize<<endl;\n FILE *fs = fopen(filename, \"r\");\n\n\n\nchar data[512];\nint block,byteSent=0;\nint bread=0;\nint ind=0;\n while(1)\n {\n int bread=fread(data,sizeof(char),512,fs);\n\n if(bread<=0)\n break;\n\nint bytes_written=0;\nchar *p=data;\nwhile (bread > 0) {\n bytes_written = write(sockfd, p, bread);\n bread -= bytes_written;\n p += bytes_written;\n }\n\n }\nsleep(0.5);\n\n}\n\n////////////////////////////////////////////////////////////\nvoid sendDirectory(int newsockfd)\n {\n int send;\n DIR *d;\n struct dirent *dir;\n d = opendir(\".\");\n if (d)\n {\n while ((dir = readdir(d)) != NULL)\n {\n printf(\"Sending %s\\n\", dir->d_name);\n sleep(0.7);\n\n\t send=write(newsockfd,dir->d_name,50);\n \tif (send < 0)\n {\n printf(\"ERROR writing to socket\");\n }\n\n }\n\tcout<<\"Files done\"<<endl;\n\tsleep(1);\n\tsend=write(newsockfd,\"THE END\",7);\n closedir(d);\n }\n }\n\n\nbool stringCheck(char* buffer,string toCheck)\n{\nint count=0;\nfor(int i=0;i<toCheck.length();i++)\n\t{\nif(buffer[i]==toCheck[i])\ncount++;\n\t}\n\nreturn count==toCheck.length();\t\n}\n\nbool isFilePresent(char* fileName)\n{\nifstream infile(fileName);\nreturn infile.good();\n}\n\nvoid shakeHand(int newsockfd,char* buffer)\n{\nint n,m;\n\tn = read(newsockfd,buffer,1024);\n\n if (n < 0)\n {\n printf(\"ERROR reading from socket\");\n }\n\n printf(\"RECEIVED: %s\\n\",buffer);\n\n m = write(newsockfd,\"I got your message,Welcome\",30);\n \n if (m < 0) \n {\n printf(\"ERROR writing to socket\");\n }\n\n\n\n\n\n\n}\n\n\n\n//////////////////////////////////////\nint main(int argc, char *argv[])\n{\n int sockfd, newsockfd, portno;\n socklen_t clilen;\n char buffer[1024];\n struct sockaddr_in serv_addr, cli_addr;\n int n,m;\n\n\n bzero(buffer,1024);\n\n if (argc < 2) {\n fprintf(stderr,\"ERROR, no port provided\\n\");\n exit(1);\n }\n sockfd = socket(AF_INET, SOCK_STREAM, 0);\n if (sockfd < 0) \n printf(\"ERROR opening socket\");\n bzero((char *) &serv_addr, sizeof(serv_addr));\n\n portno = atoi(argv[1]);\n\n if((portno > 65535) || (portno < 2000))\n {\n cout<< \"Please enter a port number between 2000 - 65535\" << endl;\n return 0;\n }\n\n\n serv_addr.sin_family = AF_INET;\n serv_addr.sin_addr.s_addr = INADDR_ANY;\n serv_addr.sin_port = htons(portno);\n if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) \n printf(\"ERROR on binding\");\n\n\n listen(sockfd,5);\n clilen = sizeof(cli_addr);\n\n while(1) \n {\n\t\n\tcout<<\"Started listening!\"<<endl;\n newsockfd = accept(sockfd, \n (struct sockaddr *) &cli_addr, \n &clilen);\n \n\tn=1;\n\t if (newsockfd < 0) \n\t{\n printf(\"ERROR on accept\");\n\treturn 0;\n\t}\nshakeHand(newsockfd,buffer);\n\n//cout<<\"New sock in main \"<<newsockfd<<endl;\n\n while(n>0)\n\t{\n\t//cout<<\"rup\"<<endl;\n \n bzero(buffer,2048); \n\tcout<<\"waiting to receive...\"<<endl;\n n = read(newsockfd,buffer,1024);\n \n// cout<<\"Starting n val: \"<<n<<endl;\n\n if (n < 0) \n\t{\n\tprintf(\"ERROR reading from socket\");\n\t}\n\n printf(\"RECEIVED: %s\\n\",buffer);\n \n/* m = write(newsockfd,\"I got your message\",18);\n \n if (m < 0) \n\t{\n\tprintf(\"ERROR writing to socket\");\n\t}\n*/\n//cout<<\"Buffer is: \"<<buffer<<\"done\"<<endl;\n\n if(stringCheck(buffer,\"list server\"))\n\t{\n\tsendDirectory(newsockfd);\n\t}\n\n\n\n if(stringCheck(buffer,\"create server \"))\n\t{\n\t char filename[50];\n\tmemcpy(filename,&buffer[14],20);\n cout<<\"File name is: \"<<filename<<endl;\n\n if(isFilePresent(filename))\n {\n cout<<\"ERROR!!! File already exists\"<<endl;\n\t m = write(newsockfd,\"ERROR!!! File already exists\",40);\n\n\t if (m < 0)\n \t\t {\n\t printf(\"--ERROR writing to socket\");\n \t\t }\n\n\n }\n\n else\n {\n ofstream outfile;\n outfile.open(filename);\n cout<<filename<<\" Has been created!!\"<<endl;\n m = write(newsockfd,\"--File has been successfully created!!\",40);\n\n if (m < 0)\n {\n printf(\"ERROR writing to socket\");\n }\n \n\t\t }\n\t}\n/////////////////////////////////////////////////////\n\n\tif(stringCheck(buffer,\"send \"))\n\t{\n\tchar filename1[30];\n\n memcpy(filename1,&buffer[5],15);\n cout<<\"File name is: \"<<filename1<<endl;\n\t\n\n if(isFilePresent(filename1))\n {\n cout<<\"ERROR!!! File already exists\"<<endl;\n m = write(newsockfd,\"ERROR!!! File already exists\",40);\n\n if (m < 0)\n {\n printf(\"--ERROR writing to socket\");\n }\n }\n else\n\t\t{\n\n\tFILE *file;\n\tfile = fopen(filename1, \"w\");\n\tm = write(newsockfd,\"File doesnot exists! Plz send data\",50);\n if (m < 0)\n {\n printf(\"Asked for the valid file data!\");\n }\n\t n = read(newsockfd,buffer,1024);\n\n if (n < 0)\n {\n printf(\"ERROR reading from socket\");\n }\n\tint fileSize=atoi(buffer);\n\tcout<<\"File size: \"<<fileSize<<endl;\t\n\t \n\tsleep(0.5);\n\tssize_t len; \n\twhile(fileSize>0)\n\t {\n\t len = recv(newsockfd,buffer,512,0);\t\n \t if (len <= 0)\n {\n printf(\"No data!!!\");\n\tbreak;\n }\n\tfwrite(&buffer,sizeof(char),len,file);\n\tfileSize-=len;\n\t\n\tbzero(buffer,2048);\n\t }\n\n\tfclose (file);\n\tcout<<\"EXITING while\"<<endl;\n\t\t}\n\t}\n\n if(stringCheck(buffer,\"receive \"))\n {\n\tcout<<\"came in receive func\"<<endl;\n\n char filename1[30];\n memcpy(filename1,&buffer[8],15);\n cout<<\"File name is: \"<<filename1<<endl;\n\n\n if(!isFilePresent(filename1))\n {\n cout<<\"Wait!!! File doesnot exists\"<<endl;\n m = write(newsockfd,\"ERROR!!! File doesnot exists\",40);\n\n if (m < 0)\n {\n printf(\"--ERROR writing to socket\");\n }\n\n }\n\t else\n\t\t{\n m = write(newsockfd,\"ERROR!!! File does exists.Sending...\",40);\n\t\tsleep(0.8);\n\t\tsendFileData(filename1,newsockfd);\n\t\n\n\t\t}\n\n }\n\nif(stringCheck(buffer,\"delete server \"))\n {\n \n\n char filename1[30];\n memcpy(filename1,&buffer[14],15);\n cout<<\"File name is: \"<<filename1<<endl;\n\tint m=1;\n\tif(remove (filename1)!=0)\n\t{\n cout<<\"Error deleting the file!!!!\"<<endl;\n\t m = write(newsockfd,\"Error deleting the file!!!!\",40);\n\t\n\t}\n else\n\t{\n cout<<\"file successfully deleted!!!\"<<endl;\n\t m = write(newsockfd,\"File successfully deleted\",40);\n\t}\n\n if (m < 0)\n {\n printf(\"--ERROR writing to socket\");\n }\n\n }\n\n\n bzero(buffer,2048);\n }\n }\n\n\n\n\n\n\n\ncout<<\"Closing socket\"<<endl;\n close(newsockfd);\n close(sockfd);\n\nreturn 0;\n\n}\n" }, { "alpha_fraction": 0.529350221157074, "alphanum_fraction": 0.5484133362770081, "avg_line_length": 18.20089340209961, "blob_id": "5f649e4750e73255242feced4ded5cc4224d6dea", "content_id": "ad40dcc5bc296c00fa92ef6c630b3a5a7d75769b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8605, "license_type": "no_license", "max_line_length": 84, "num_lines": 448, "path": "/fileSharing/myClient.cc", "repo_name": "R-Niagra/Networking-Projects", "src_encoding": "UTF-8", "text": "#include <unistd.h>\n#include <stdio.h> // basic I/O\n#include <stdlib.h>\n#include <sstream>\n#include <cstdlib>\n#include <sys/types.h> // standard system types\n#include <netinet/in.h> // Internet address structures\n#include <sys/socket.h> // socket API\n#include <arpa/inet.h>\n#include <netdb.h> // host to IP resolution\n#include <string.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <stdio.h>\n#include <fstream>\n#include <string>\n#include <iostream>\n\nusing namespace std;\n\n#define HOSTNAMELEN 40 // maximal host name length; can make it variable if you want\n#define BUFLEN 1024 // maximum response size; can make it variable if you want\n//#define PORT argv[2] // port of daytime server\n\nvoid recvData(char* filename1,int sockfd)\n {\nchar buffer[1024];\nint m=1,n=1;\n FILE *file;\n file = fopen(filename1, \"w\");\n/* m = write(sockfd,\"waiting to get File...\",50);\n if (m < 0)\n {\n printf(\"Asked for the valid file data!\");\n } */\n\n n = read(sockfd,buffer,1024);\n\n if (n < 0)\n {\n printf(\"ERROR reading from socket\");\n }\n int fileSize=atoi(buffer);\n cout<<\"File size: \"<<fileSize<<endl;\n\n sleep(0.5);\n ssize_t len;\n while(fileSize>0)\n {\n len = recv(sockfd,buffer,512,0);\n if (len <= 0)\n {\n printf(\"No data!!!\");\n break;\n }\n fwrite(&buffer,sizeof(char),len,file);\n fileSize-=len;\n bzero(buffer,1024);\n }\n\n fclose (file);\n cout<<\"EXITING while\"<<endl;\n }\n \n\nvoid printDirectory()\n\t{\n\n DIR *d;\n struct dirent *dir;\n d = opendir(\".\");\n if (d)\n {\n while ((dir = readdir(d)) != NULL)\n {\n printf(\"%s\\n\", dir->d_name);\n }\n\n closedir(d);\n }\n\t}\n\nvoid shakeHand(char* buf,int numbytes,int sockfd)\n {\n\nint io;\n\nif((io=write(sockfd,\"Hello!!\",20))<0)\n{\ncout<<\"Failed to send\"<<endl;\nexit(1);\n}\n\nif((numbytes = recv(sockfd, buf, BUFLEN-1, 0)) == -1)\n{\n cout<<\"Failed to receive data\"<<endl;\n exit(1);\n}\n\n\nbuf[numbytes] = '\\0';\nprintf(\"Received: %s \\n\", buf);\n\n\n }\n\nbool stringCheck(char* buffer,string toCheck)\n{\n//cout<<\"buff: \"<<buffer<<endl;\nint count=0;\nfor(int i=0;i<toCheck.length();i++)\n {\nif(buffer[i]==toCheck[i])\ncount++;\n }\n\nreturn count==toCheck.length();\n}\n///////////////////////////////////////////\nbool isFilePresent(string fileName)\n{\nifstream infile(fileName.c_str());\nreturn infile.good();\n}\n//////////////////////////////////////////\nint file_size(string filename)\n{\nifstream file( filename.c_str(), ios::binary | ios::ate);\nreturn file.tellg();\n\n}\n\n/////////////////////////////////////////////\nvoid sendFileData(string filename,int sockfd)\n{\nint index=0,w;\nstring line=\"\",fileData=\"\",fsize=\"\";\n//ifstream infile(filename.c_str());\nint fileSize=file_size(filename);\nstringstream ss;\nss<<fileSize<<endl;\nfsize=ss.str();\n\n\n if(w=write(sockfd,fsize.c_str(),fsize.length())<0)\n {\n cout<<\"Failed to send\"<<endl;\n exit(1);\n }\nsleep(0.7);\ncout<<\"File size is: \"<<fileSize<<endl;\n FILE *fs = fopen(filename.c_str(), \"r\");\n\n\n\nchar data[512];\nint block,byteSent=0;\nint bread=0;\nint ind=0;\n\twhile(1)\n \t{\n int bread=fread(data,sizeof(char),512,fs);\n\t\n\tif(bread<=0)\n\tbreak;\n\nint bytes_written=0;\nchar *p=data;\n while (bread > 0) {\n bytes_written = write(sockfd, p, bread); \n\t bread -= bytes_written;\n p += bytes_written;\n }\n\n }\nsleep(0.5);\n\n}\n\n//////////////////////////////////////////////\nint main(int argc, char *argv[])\n{\n // define your variables here\nint sockfd, numbytes,PORT,io;\nchar buf[BUFLEN];\nstruct hostent *serv;\n// connector’s address information\nstruct sockaddr_in their_addr;\nPORT=atoi(argv[2]);\n//printf(\"Port is: \",PORT);\n\n\n // check that there are enough parameters\n if (argc != 3)\n {\n fprintf(stderr, \"Usage: mydaytime <hostname>\\n\");\n exit(-1);\n }\n\n // Write your code here\n\nif((serv=gethostbyname(argv[1])) == NULL)\n{\n cout<<\"Error in hostName\"<<endl;\n exit(1);\n}\n\nif((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)\n{\ncout<<\"Error in creating socket\"<<endl;\nreturn 0;\n}\n\ntheir_addr.sin_family = AF_INET;\ntheir_addr.sin_port = htons(PORT);\ntheir_addr.sin_addr = *((struct in_addr *)serv->h_addr);\nmemset(&(their_addr.sin_zero), '\\0', 8);\n/////////////////////////////////////////\n\nif(connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) <0)\n{\n cout<<\"Connection failed to establish\"<<endl;\n exit(1);\n}\nelse\n cout<<\"Connection established!!!!\"<<endl;\n\nstring mystr=\"\";\nnumbytes=1;\n\nshakeHand(buf,numbytes,sockfd);\n\n//////////////////////////////////////////////////////////////////\nwhile(numbytes!=0)\n{\nstring filename;\n\ncout<<\"Please enter your command: \";\ngetline(cin,mystr);\n\ncout<<\"Mystr is: \"<<mystr<<endl;\n\nif (mystr==\"list client\")\n\t{\n printDirectory();\n\t}\n/////////////////////////////\nelse if(mystr==\"list server\")\n\t{\n\nif((io=write(sockfd,\"list server\",11))<0)\n{\ncout<<\"Failed to send\"<<endl;\nexit(1);\n}\n int rcv=1;\n\twhile(!stringCheck(buf,\"THE END\"))\n\t\t{\n\tif((rcv = recv(sockfd, buf, BUFLEN-1, 0)) == -1)\n\t{cout<<\"Failed to receive data\"<<endl;\n \texit(1);}\n\t\n\t\tbuf[rcv] = '\\0';\n\t\tprintf(\"Received: %s \\n\", buf);\n\t\t\t\n\t\t}\n\t}\n///////////////////////////////////\n\n//string filename;\n\nelse if(mystr.substr(0,14)==\"create client \")\n\t{\n\tfilename=mystr.substr(14,mystr.length()-14);\n\tcout<<\"File name is: \"<<filename<<endl;\n\n\tif(isFilePresent(filename))\n\t\t{\n\tcout<<\"ERROR!!! File already exists\"<<endl;\t\n\t\t}\n\n\telse\n\t\t{\n\tofstream outfile;\n\toutfile.open(filename.c_str());\n\tcout<<filename<<\" Has been created!!\"<<endl;\n\t\t}\n\t}\n\nelse if(mystr.substr(0,14)==\"create server \")\n\t{\nint w;\n\t\n\tif((io=write(sockfd,mystr.c_str(),mystr.length()))<0)\n\t{\n\tcout<<\"Failed to send\"<<endl;\n\texit(1);\n\t}\n\n\tif((numbytes = recv(sockfd, buf, BUFLEN-1, 0)) == -1)\n\t{\n\t cout<<\"Failed to receive data\"<<endl;\n\t exit(1);\n\t}\n\n\n\tbuf[numbytes] = '\\0';\n\tprintf(\"Received: %s \\n\", buf);\n\n\n\t}\n//////////////////////////////////////\nelse if(mystr.substr(0,5)==\"send \")\n{\n\tint w;\n string fileData;\n\tcout<<\"mystr\"<<mystr<<endl;\n\tfilename=mystr.substr(5,mystr.length()-5);\n\t cout<<\"File name is: \"<<filename<<endl;\n\n\t if((io=write(sockfd,mystr.c_str(),mystr.length()))<0)\n {\n cout<<\"Failed to send\"<<endl;\n exit(1);\n }\n\tsleep(0.2);\n\n if((numbytes = recv(sockfd, buf, BUFLEN-1, 0)) == -1)\n {\n cout<<\"Failed to receive data\"<<endl;\n exit(1);\n }\n buf[numbytes] = '\\0';\n printf(\"Received: %s \\n\", buf);\n\n\tif(!stringCheck(buf,\"ERROR!!! File already exists\"))\t\n\tsendFileData(filename,sockfd);\n\t\n\t\n}\n\nelse if(mystr.substr(0,8)==\"receive \")\n {\n\n int w;\n string fileData;\n cout<<\"mystr\"<<mystr<<endl;\n filename=mystr.substr(8,mystr.length()-8);\n cout<<\"File name is: \"<<filename<<endl;\n\n\tif(isFilePresent(filename))\n\t{\n\tcout<<\"Wait!! File already exists!!\"<<endl;\n\tcout<<\"Press 1 for override: \"<<endl;\n\tcout<<\"Press 0 to to stop this: \";\n\tstring x=\"\";\n\tgetline(cin,x);\n\tif(x==\"0\")\n\tcontinue;\n\t}\n\n\n\n\n\n if((io=write(sockfd,mystr.c_str(),mystr.length()))<0)\n {\n cout<<\"Failed to send\"<<endl;\n exit(1);\n }\n sleep(0.2);\n\n if((numbytes = recv(sockfd, buf, BUFLEN-1, 0)) == -1)\n {\n cout<<\"Failed to receive data\"<<endl;\n exit(1);\n }\n buf[numbytes] = '\\0';\n printf(\"Received: %s \\n\", buf);\n\t\n\tchar filename1[30];\n\tfor(int i=0;i<filename.length();i++)\n\tfilename1[i]=filename[i];\n\n\n if(!stringCheck(buf,\"ERROR!!! File doesnot exists\"))\n\t{\n\t recvData(filename1,sockfd);\n\n\t}\n\n }\n\n\nelse if(mystr.substr(0,14)==\"delete client \")\n{\n cout<<\"mystr\"<<mystr<<endl;\n filename=mystr.substr(14,mystr.length()-14);\n cout<<\"File name is: \"<<filename<<endl;\n\t\n\tif(remove (filename.c_str())!=0)\n\tcout<<\"Error deleting the file!!!!\"<<endl;\n\t\n\telse\n\tcout<<\"file successfully deleted!!!\"<<endl; \n\n\n}\n\nelse if(mystr.substr(0,14)==\"delete server \")\n{\n\n if((io=write(sockfd,mystr.c_str(),mystr.length()))<0)\n {\n cout<<\"Failed to send\"<<endl;\n exit(1);\n }\n sleep(0.2);\n\n if((numbytes = recv(sockfd, buf, BUFLEN-1, 0)) == -1)\n {\n cout<<\"Failed to receive data\"<<endl;\n exit(1);\n }\n buf[numbytes] = '\\0';\n printf(\"Received: %s \\n\", buf);\n\n\n}\n\n\nelse if(mystr==\"EXIT\" || mystr==\"exit\")\n\t{\nclose(sockfd);\nnumbytes=0;\nbreak;\n\t}\n\n else\n cout<<\"Just Try Again!!!\"<<endl;\n\n\n}\n\n\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.8148148059844971, "alphanum_fraction": 0.8148148059844971, "avg_line_length": 53, "blob_id": "e3c8f676b98d48a866f2d7682ec730f4a4355d32", "content_id": "e25a7b26b62dfe29774bd9b14270074dd5c9a892", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 108, "license_type": "no_license", "max_line_length": 95, "num_lines": 2, "path": "/bittorent/README.md", "repo_name": "R-Niagra/Networking-Projects", "src_encoding": "UTF-8", "text": "A a peer to\npeer file sharing model based on BitTorrent peer to peer file sharing model based on BitTorrent\n" }, { "alpha_fraction": 0.5885093212127686, "alphanum_fraction": 0.6040372848510742, "avg_line_length": 22.796297073364258, "blob_id": "32272d6165b35dcd23b0588d442ab4e1dc95dad2", "content_id": "f5a57cd8cc774f5e40746103f438d7ec9536265c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1288, "license_type": "no_license", "max_line_length": 92, "num_lines": 54, "path": "/searchQuery/client.py", "repo_name": "R-Niagra/Networking-Projects", "src_encoding": "UTF-8", "text": "import socket\nimport sys\nfrom termcolor import colored\n\n\ndef main(argv):\n\tcl=socket.socket()\n\tcl.connect((argv[1],int(argv[2])))\n\twelcome=cl.recv(2000)\n\tprint welcome\n\tquery=raw_input()\n\tcl.send(query)\n\tdata=\"\"\n\twhile(1):\n\t\tdata=cl.recv(3000)\n\t\t#print data\n\t\tmylines = data.splitlines() #This part is rendered for colour change\n\t\tfor j in mylines:\n\t\t\tmywords = j.split()\n\t\t\tfor i in mywords:\n\t\t\t\tif i==query:\n\t\t\t\t\tprint colored(i, 'red'),\n\t\t\t\telse:\n\t\t\t\t\tprint (i),\n\t\t\tprint ''\t\t\n\t\tfolder=\"\" #Till here!!!\n\t\tif data[-10:]==\"$$-Done-$$\":\n\t\t\twhile(1):\n\t\t\t\tprint(\"Please enter the folder name to download or press exit: \")\n\t\t\t\tfolder=raw_input()\n\t\t\t\tfnd=folder.find(\"/\") # This looks for the only file name given(Without directory)\n\t\t\t\t\n\t\t\t\twhile (folder.count(\"/\")!=1 and folder!=\"exit\"):\n\t\t\t\t\tprint \"Please enter acceptiple format again: \"\n\t\t\t\t\tfolder=raw_input()\n\n\t\t\t\tcl.send(folder)\n\t\t\t\tif(folder==\"exit\"):\n\t\t\t\t\tbreak\n\t\t\t\tfileData=cl.recv(2024)\n\t\t\t\t#print fileData\n\t\t\t\t# print colored(fileData, 'red')\n\t\t\t\tif(fileData!=\"File doesnot exists!!\" and fileData!=\"empty file\"):\t\n\t\t\t\t\tfile=open(folder[fnd+1:],'w')\n\t\t\t\t\tfile.write(fileData)\n\t\t\t\telse:\n\t\t\t\t\tprint fileData\t\t\t\n\n\t\tif(folder==\"exit\"):\n\t\t\tcl.close()\n\t\t\tbreak\t\t\t\n\nif __name__==\"__main__\":\n\tmain(sys.argv)\n\n\n\n" }, { "alpha_fraction": 0.6003416180610657, "alphanum_fraction": 0.6131511330604553, "avg_line_length": 19.707963943481445, "blob_id": "fa8369f7120c1cc6204bba7517c888093c1c48d2", "content_id": "0a2c6e8c4236e209e3594a3f4e5d379a467f2b46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2344, "license_type": "no_license", "max_line_length": 84, "num_lines": 113, "path": "/fileSharing/simpleclient.cc", "repo_name": "R-Niagra/Networking-Projects", "src_encoding": "UTF-8", "text": "#include <stdio.h> // basic I/O\n#include <stdlib.h>\n#include <sys/types.h> // standard system types\n#include <netinet/in.h> // Internet address structures\n#include <sys/socket.h> // socket API\n#include <arpa/inet.h>\n#include <netdb.h> // host to IP resolution\n#include <string.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <stdio.h>\n#include <fstream>\n#include <string>\n#include <iostream>\n\nusing namespace std;\n\n#define HOSTNAMELEN 40 // maximal host name length; can make it variable if you want\n#define BUFLEN 1024 // maximum response size; can make it variable if you want\n//#define PORT argv[2] // port of daytime server\n\n\n//////////////////////////////////////////////\nint main(int argc, char *argv[])\n{\n // define your variables here\nint sockfd, numbytes,PORT,io;\nchar buf[BUFLEN];\nstruct hostent *serv;\n// connector’s address information\nstruct sockaddr_in their_addr;\nPORT=atoi(argv[2]);\n//printf(\"Port is: \",PORT);\n\n\n // check that there are enough parameters\n if (argc != 3)\n {\n fprintf(stderr, \"Usage: mydaytime <hostname>\\n\");\n exit(-1);\n }\n\n // Write your code here\n\nif((serv=gethostbyname(argv[1])) == NULL)\n{\n cout<<\"Error in hostName\"<<endl;\n exit(1);\n}\n\nif((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)\n{\ncout<<\"Error in creating socket\"<<endl;\nreturn 0;\n}\n\ntheir_addr.sin_family = AF_INET;\ntheir_addr.sin_port = htons(PORT);\ntheir_addr.sin_addr = *((struct in_addr *)serv->h_addr);\nmemset(&(their_addr.sin_zero), '\\0', 8);\n/////////////////////////////////////////\n\nif(connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) <0)\n{\n cout<<\"Connection failed to establish\"<<endl;\n exit(1);\n}\nelse\n cout<<\"Connection established!!!!\"<<endl;\n\nstring mystr=\"\";\nnumbytes=1;\n\n\n//////////////////////////////////////////////////////////////////\nwhile(numbytes!=0)\n{\nstring filename;\n\nif((numbytes = recv(sockfd, buf, BUFLEN-1, 0)) == -1)\n{\n cout<<\"Failed to receive data\"<<endl;\n exit(1);\n}\nbuf[numbytes] = '\\0';\nprintf(\"Received: %s \\n\", buf);\n\n\ncout<<\"Please enter your command: \";\ngetline(cin,mystr);\n\ncout<<\"Mystr is: \"<<mystr<<endl;\nmystr=mystr+\"\\r\\n\";\n\nif((io=write(sockfd,mystr.c_str(),mystr.length()))<0)\n{\ncout<<\"Failed to send\"<<endl;\nexit(1);\n}\n\n\n if(mystr==\"EXIT\\r\\n\" || mystr==\"exit\\r\\n\")\n\t{\nclose(sockfd);\nnumbytes=0;\nbreak;\n\t}\n}\n\n\n\n return 0;\n}\n\n\n" }, { "alpha_fraction": 0.8636363744735718, "alphanum_fraction": 0.8636363744735718, "avg_line_length": 65, "blob_id": "d4c43bed554234cfe28fd6442342fc441daa66eb", "content_id": "58970a56561069267ee6412c9d5691bf71b3c652", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 66, "license_type": "no_license", "max_line_length": 65, "num_lines": 1, "path": "/mapReduce/README.md", "repo_name": "R-Niagra/Networking-Projects", "src_encoding": "UTF-8", "text": "A distributed search engine using concurrency and multi-threading\n" }, { "alpha_fraction": 0.6110833883285522, "alphanum_fraction": 0.63429856300354, "avg_line_length": 19.413265228271484, "blob_id": "dae9419a4505a66781dd0ebe1edfb7cc1f300427", "content_id": "5d5116b9c0420375a28110c949da4772ff38afd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4006, "license_type": "no_license", "max_line_length": 108, "num_lines": 196, "path": "/mapReduce/workerClient.py", "repo_name": "R-Niagra/Networking-Projects", "src_encoding": "UTF-8", "text": "import socket\nimport sys\nimport os.path\nfrom thread import *\nimport threading\nimport time\nimport Queue\n\ndataRead=[]\ncheckedTill=0\nqueryCount1=0\nendRange=0;\n\n\ndef finder(parts,q,addr,sock):\n\tt = threading.currentThread() #Creating an object\n\tt.run=True\n\tglobal dataRead\n\tglobal checkedTill\n\tglobal endRange\n\n\tquery=parts[5]\n\tprint \"Query is: \",query\n\tqueryCount=0\n\tglobal queryCount1\n\tfileNum=0;\n\trangeStart=parts[3]\n\tendRange=parts[4]\n\n\tprint \"will check from: \",parts[3],\" to \",parts[4]\n\tprint \"started searching-------\"\n\n\tfolder_size=0;\n\tfor(path, dirs, files) in os.walk(\"source\"):\n\n\t\tfor file in files:\n\t\t\tfilename = os.path.join(path, file)\n\t\t\tfolder_size += os.path.getsize(filename)\n\n\t\t\tif(t.run==False):\n\t\t\t\tprint \"Quiting!\";\n\t\t\t\treturn;\n\n\t\t\tif(folder_size>=int(parts[3]) and folder_size<=int(endRange)):\n\t\t\t\t# print \"End range is: \",endRange\n\t\t\t\tcheckFile=open(filename,\"r\")\n\t\t\t\tfileData=checkFile.readlines()\n\t\t\t\tcheckFile.close()\n\t\t\t\tputIn=0;\n\t\t\t\t# print \"checking\"\n\t\t\t\tfor line in fileData:\n\t\t\t\t\tif(query in line):\n\t\t\t\t\t\t# print line\n\t\t\t\t\t\tqueryCount+=1;\n\t\t\t\t\t\tputIn=1;\n\t\t\t\t\t\tqueryCount1+=1;\n\t\t\t\t\t\t# q.put(filename)\n\t\t\t\t\t\t# dataRead.append(folder_size)\n\t\t\t\t\t\t# break;\n\n\t\t\t\t# putIn=fileData.count(query)\n\t\t\t\tif(putIn>=1):\n\t\t\t\t\tq.put(filename)\n\t\t\t\t\tqueryCount+=putIn\n\t\t\t\t\tputIn=0;\n\n\t\t\t\tfileNum+=1;\n\t\t\t\tdataRead.append(folder_size)\n\n\n\t\t\t\t# print fileData\n\t\t\t# time.sleep(0.2)\n\tprint \"Files checked: \",fileNum, \" Query count: \",queryCount\n\tif(len(dataRead)>0):\n\t\tcheckedTill=dataRead[-1]\n\n\tsock.sendto(\"15440,-,5,%s,%d,%s,%d\" %(rangeStart,checkedTill,query,queryCount),addr)\n\n\n\ndef main(argv):\n\n\tsock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) \n\tsip=argv[1]\n\tsport=int(argv[2])\n\taddr=(sip,sport)\n\tsock.setblocking(0)\n\tsock.sendto(\"15440,-,1,-,-,-,-\",addr)\n\n\tping=time.time()+60*3\n\n\tresult=[]\n\tq = Queue.Queue()\n\t# dataRead=Queue.LifoQueue() #Corrosponding to the chunks that has been read!\n\tglobal checkedTill\n\tglobal dataRead\n\tglobal queryCount1\n\tglobal endRange\n\tstart=0\n\tend=0\n\tsearchStart=0;\n\tquery=\"\"\n\n\twhile(True):\n\n\t\ttry:\n\n\t\t\tdata,addr=sock.recvfrom(1024)\n\n\t\texcept socket.error as error:\n\n\t\t\tif \"[Errno 35]\" in str(error):\n\t\t\t\t# if(time.time()>=ping):\n\t\t\t\t# \tsock.sendto(\"15440,-,3,-,-,-,-\",addr) \n\n\t\t\t\tcontinue\n\n\t\t\telse:\n\t\t\t\traise error\n\n\n\t\tprint \"data: \",data\n\t\tparts=data.split(\",\")\n\n\t\tif(parts[2]==\"2\"):\n\t\t\tprint \"job received! Sending confirmation: \"\n\t\t\tstart=int(parts[3])\n\t\t\tend=int(parts[4])\n\t\t\tsock.sendto(\"15440,-,3,-,-,-,-\",addr) # job confirmation\n\n# ping=time.time()+3;\n\n\t# if(threading.active_count()==1):\n\t\t\tsearchStart=int(parts[3])\n\t\t\tquery=parts[5]\n\n\t\t\tprint \"threading count: \",threading.active_count()\n\n\t\t\tif(threading.active_count()==1):\n\t\t\t\tt = threading.Thread(target=finder, args=(parts,q,addr,sock))\n\t\t\t\tt.start()\n\n\t\t\telse:\n\t\t\t\tprint \"coming in else condition\"\n\t\t\t\tendRange=int(parts[4])\n\n\n\t\t\t# print \"threading count later: \",threading.active_count()\n\n\n# if()\n# \tt.do_run = False\n# \t\t\tt.join()\n\t# Start from new range\n\n\n\t\tif(parts[2]==\"0\"):\n\t\t\tprint \"Received ping! Sending reply updates::\"\n\t\t\tcurrent=\"\"\n\n\n\t\t\tif(len(dataRead)>0):\n\t\t\t\t# print \"dataRead: \",dataRead\n\t\t\t\tcheckedTill=dataRead.pop();\n\t\t\t\tprint \"Checked till: \",checkedTill\n\t\t\t\tdataRead=[]\n\n\t\t\tif(q.qsize()>0):\n\t\t\t\tlimit=q.qsize();\n\t\t\t\tfor val in range(limit):\n\t\t\t\t\tx=q.get();\n\t\t\t\t\tprint \"result in: \",x\n\t\t\t\t\tcurrent+=(x+\"|<->|\")\n\t\t\t\t\tresult.append(x) #Maintaining its current result state\n\n\t\t\tprint \"query count is: \",queryCount1\n\t\t\tcurrent=current+str(queryCount1)\n\t\t\tqueryCount1=0\n\t\t\t# if(dataRead.qsize()>0):\n\t\t\t# \tcheckedTill=dataRead.get();\n\t\t\t# \tdataRead=[]\n\t\t\tprint \"Sending: \",current\t\t\n\t\t\tsock.sendto(\"15440,-,6,%d,%d,%s,%s\" %(searchStart,checkedTill,query,current),addr)\t\t\n\n\n\t\tif(parts[2]==\"8\"): #Cancel job command!!\n\t\t\tprint \"job has been cancelled!!\"\n\n\t\t\tt.run=False\t\t # Thread will stop running if cancel commad fiven or essentially new command comes\t\t\t\n\t\t\tt.join()\n\t\t\treturn\n# print \"hello\",q.get()\t\t\n\n\nif __name__==\"__main__\":\n\tmain(sys.argv)\n\n\n\n\n\n" }, { "alpha_fraction": 0.8285714387893677, "alphanum_fraction": 0.8285714387893677, "avg_line_length": 51.5, "blob_id": "2eef1e25691cf7fbc4234138c46f81af753d0831", "content_id": "7938ad3807318e9c1bec8b2657772f315215b6b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 105, "license_type": "no_license", "max_line_length": 82, "num_lines": 2, "path": "/README.md", "repo_name": "R-Niagra/Networking-Projects", "src_encoding": "UTF-8", "text": "# Networking-Projects\nThis repository contains the set of computer networking projects I have worked on.\n" }, { "alpha_fraction": 0.8260869383811951, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 22, "blob_id": "41ffb1c4ed575a095ffbbb9eea5943e957f126d2", "content_id": "b027f718c31860fef964dd85536cd24710eb4590", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 23, "license_type": "no_license", "max_line_length": 22, "num_lines": 1, "path": "/searchQuery/README.md", "repo_name": "R-Niagra/Networking-Projects", "src_encoding": "UTF-8", "text": "A simple serach engine\n" }, { "alpha_fraction": 0.5913645029067993, "alphanum_fraction": 0.6092557311058044, "avg_line_length": 20.782608032226562, "blob_id": "d71fee376be89be4d08151e70083e70176234ec6", "content_id": "6a3666efa67e5deaa148d1ee35411d7aab8eaad6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4192, "license_type": "no_license", "max_line_length": 105, "num_lines": 184, "path": "/bittorent/tracker_server.py", "repo_name": "R-Niagra/Networking-Projects", "src_encoding": "UTF-8", "text": "import socket\r\nimport sys\r\nimport os\r\nfrom thread import *\r\nimport shutil\r\nimport zipfile\r\nimport glob\r\nimport time\r\n\r\n\r\ndef makeSearchFile(addr):\r\n\tduplicates=0\r\n\r\n\tprint \"Came in with address: \",addr\r\n\tsearchFile = open(\"search_content.txt\", \"w\")\r\n\trecordFile=open(\"record.txt\",\"a+\")\r\n\trecordFile.seek(0) #Brings cursor at start to readline!\r\n\trecordLines=recordFile.readlines()\r\n\r\n\tprint\" recordLines are\",recordLines\r\n\r\n\tallTorrents = glob.glob(\"*.torrent\")\r\n\tfor torrent in allTorrents:\r\n\t\twith open(torrent) as f:\r\n\t \t\tlines = f.readlines()\r\n\r\n\t\toneLine = lines[0].split(\".\")\r\n\t\t\r\n\t\tname=oneLine[0].split(\":\")\r\n\r\n\t\t# if not recordLines:\r\n\t\t# \tprint \"Got in\"\r\n\t\t# \trecordFile.write(str(addr[0])+\" \"+str(addr[1])+\" \"+name[1]+\".\"+oneLine[1].rstrip()+\" \"+torrent+\"\\n\")\r\n\r\n\r\n\t\tfor line in recordLines:\r\n\t\t\tif torrent in line:\r\n\t\t\t\tduplicates+=1;\t\t\r\n\r\n\t\tif(duplicates==0):\r\n\t\t\trecordFile.write(str(addr[0])+\" \"+str(addr[1])+\" \"+name[1]+\".\"+oneLine[1].rstrip()+\" \"+torrent+\"\\n\")\r\n\t\t\t\r\n\t\tduplicates=0;\r\n\r\n\r\n\t \tlineToPrint = oneLine[0] + \" type:\" + oneLine[1].rstrip() + \" tor:\" + torrent + \"\\n\"\r\n\t \tsearchFile.write(lineToPrint)\r\n\r\n\trecordFile.close()\r\n\tsearchFile.close()\r\n\r\n\t# print \"record is: \",record\r\n\t# return record\r\n\t \t# print lineToPrint\r\n\r\ndef searchFile(reqFile,client): #This will search and send appropriate torrent file\r\n\tsearchFile=open(\"search_content.txt\",'r')\r\n\tfileData=searchFile.readlines()\r\n\t\r\n\tdivide=reqFile.split(\".\")\r\n\tname=divide[0]\r\n\textension=divide[1]\r\n\ttoFind=\"Name:\"+name+ \" type:\"+extension\r\n\t\r\n\tfor line in fileData:\r\n\r\n\t\tif toFind in line:\r\n\t\t\tprint \"rq line is: \",line\r\n\t\t\treqTorrent=line.split(\"tor:\",1)[1]\r\n\t\t\treqTorrent=reqTorrent.strip()\r\n\t\t\tprint\"reqTorrent\",reqTorrent\r\n\t\t\twith open(reqTorrent,'r') as inFile:\r\n\t\t\t\ttorFile=inFile.readlines()\r\n\t\t\tclient.send(''.join(torFile))\r\n\t\t\tclient.recv(1024)\r\n\r\n\t\r\n\ttime.sleep(.2)\r\n\tclient.send(\"..Done Sending Torrents..\")\r\n\r\n\trecordFile=open(\"record.txt\",'r')\r\n\trecord=recordFile.readlines()\r\n\r\n\tfor line in record:\r\n\t\tif(reqFile in line):\r\n\t\t\tprint line\r\n\t\t\tclient.send(line)\r\n\t\t\tclient.recv(1024)\r\n\r\n\tclient.send(\"--ALL PEERS SENT--\")\r\n\tprint \"Till this\"\r\n\trecordFile.close()\r\n\r\n\t# \tprint \"Came in: \"\r\n\t# \tprint record[2]\r\n\t# \tif(record[2]==reqFile):\r\n\t# \t\tprint \"record:\",record[0],record[1],record[2]\r\n\r\n\r\n\r\n\r\ndef clientThread(client,addr,count):\r\n\r\n\twhile 1:\r\n\r\n\t\tprint \"Before\"\r\n\t\tdata = client.recv(1024)\r\n\t\tprint \"after\"\r\n\t\ttime.sleep(.3)\r\n\t\tprint data\r\n\r\n\t\tif \"~Download mode~\" in data:\r\n\r\n\t\t\treqFile=client.recv(2048)\r\n\t\t\tprint reqFile\r\n\t\t\tsearchFile(reqFile,client)\r\n\t\t\t# client.close()\r\n\r\n\r\n\t\telif \"~Sending Torrent File::~\" in data:\r\n\t\t\tdata=\"\"\r\n\t\t\twith open('received_file%s.zip' %count, 'wb') as f:\r\n\t\t\t\twhile True:\r\n\t\t\t\t\tdata = client.recv(1024)\r\n\t\t\t\t\tf.write(data)\r\n\t\t\t\t\t# data = client.recv(1024)\r\n\t\t\t\t\tif \"~^~Done Sending~^~\" in data:\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\t# data = client.recv(1024)\r\n\t\t\t\t\t\r\n\r\n\t\t\tclient.send(\"Data received!\")\r\n\t\t\tf.close()\r\n\r\n\t\t\tzip = zipfile.ZipFile('received_file%s.zip' %count)\r\n\t\t\tzip.extractall()\r\n\t\t\tmakeSearchFile(addr)\r\n\r\n\r\n\t\telif \"^^Quiet^^\" in data or not data:\r\n\t\t\tclient.close()\r\n\t\t\trecordFile=open(\"record.txt\",\"r\")\r\n\t\t\trecordData=recordFile.readlines();\r\n\t\t\trecordFile.close();\r\n\r\n\t\t\trecordF=open(\"record.txt\",\"w\")\r\n\t\t\tfor line in recordData:\r\n\t\t\t\tif addr[0]+\" \"+str(addr[1]) not in line:\r\n\t\t\t\t\trecordF.write(line)\r\n\r\n\t\t\trecordF.close()\t\r\n\t\t\treturn\r\n\r\n\r\n\t\t# if not data:\r\n\t\t# \treturn\r\n\r\n\t\tdata=\"\"\r\n\r\n\r\ndef main(argv):\r\n\r\n\t# port = 1234 # Reserve a port for your service.\r\n\ts = socket.socket() # Create a socket object\r\n\ts.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n\thost = '127.0.0.1' \t\t\t\t# Get local machine name\r\n\ts.bind((host,int(argv[1]))) # Bind to the port\r\n\ts.listen(5) # Now wait for client connection.\r\n\t# record=[[],[],[]]\t\t\t\t#Record against Ip address,port, and file names\r\n\tcount=1;\r\n\r\n\r\n\twhile 1:\r\n\t\tclient, addr = s.accept() # Establish connection with client.\r\n\t\tstart_new_thread(clientThread,(client,addr,count))\r\n\t\tprint\"In big while\"\r\n\t\tcount+=1\r\n\t\t# print \"record in while is: \",record\r\n\r\n\r\n\r\n\r\nif __name__==\"__main__\":\r\n\tmain(sys.argv)\r\n" }, { "alpha_fraction": 0.5889375805854797, "alphanum_fraction": 0.6163464188575745, "avg_line_length": 27.653846740722656, "blob_id": "712a38d833bb61ca8a30e7d2e8a0af9e91b21525", "content_id": "6cbdb5242902dd38e3c1e50b64b94e401d80a3e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14156, "license_type": "no_license", "max_line_length": 130, "num_lines": 494, "path": "/mapReduce/server.py", "repo_name": "R-Niagra/Networking-Projects", "src_encoding": "UTF-8", "text": "import sys\nimport socket\nimport os\nimport time\nfrom thread import *\nimport threading\nimport path\nimport random\nimport threading\nimport Queue\nfrom os import path\nfrom collections import Counter\nimport ast\n\n# if os.path.isdir(\"arch\")==1:\n# \t\tprint\"yes dir\" \t\t\t\t\t\t\n# \tif os.path.isfile(\"COPYING\"):\n# \t\tprint\"yes file\"\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ndef findSize(source): #Checks for the size of the source file\n \tnumOfFiles=0;\n\tfolder_size=0;\n\tfor(path, dirs, files) in os.walk(source):\n\n\t\tfor file in files:\n\t\t\tfilename = os.path.join(path, file)\n\t\t\t# print \"fname: \",filename\n\t\t\tfolder_size += os.path.getsize(filename)\n\t\t\tnumOfFiles+=1;\n\n\t# print \"Total number of files: \",numOfFiles\n\treturn folder_size\t\t\n\n\ndef reAssignJob(wcData,sock): #[time,addr,[chunk range], timesAssigned,query,accepted,searched,jobDone,pingsDiscarded]\n\t\n\n\tstring=\"15440,-,2,%d,%d,%s,-\" %(wcData[2][0], wcData[2][1], wcData[4])\n\tprint \"wcData in reassign: \",wcData\n\n\tsock.sendto(string,wcData[1])\n\twcData[3]+=1;\n\twcData[0]=time.time()+8\n\treturn wcData\n\ndef send2Client(sock,qResults,clients,query):\n\tt = threading.currentThread() \n\t# print \"in thread: \",qResults,\"query\",query\n\t# print \"clients are: \",clients\n\n\n\tresIndex=0\n\tclientIndex=0\n\tfor x in range(len(qResults)):\n\t\tif(qResults[x][0]==query):\n\t\t\tresIndex=x;\n\n\tfor y in range(len(clients)):\n\t\tif (query==clients[y][2]):\n\t\t\tclientIndex=y\n\n\tclientAddr=clients[clientIndex][1]\n\t\t\t\t#start sending the results\n\tsock.sendto(\"%s queries found in the data\" %str(qResults[resIndex][1]),clientAddr)\n\tfor z in range(2,len(qResults[resIndex])):\n\t\tcheckFile=open(qResults[resIndex][z],\"r\")\n\t\tfileData=checkFile.readlines()\n\t\tcheckFile.close()\n\n\t\tfor line in fileData:\n\t\t\tif(query in line):\n\t\t\t\tsock.sendto(\"%s: %s\"%(qResults[resIndex][z],line),clientAddr)\n\n\tdel qResults[resIndex]\n\treturn qResults\n\n\ndef main(argv):\n\n\n\tip='127.0.0.1'\n\tport=int(argv[1])\n\n\tsock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n\tsock.bind((ip,port))\n\tsock.setblocking(0)\n\t# sock.settimeout(5)\n\t# rcPing=time.time()+60*5 #Rquest client ping\n\tserverState=time.time()+20\n\twcData=[]\t\t\t\t\t#Worker client ping\n\t\n\tcurDir=os.getcwd()\n\tjob=[] # [Query,start,endSearch]\n\tqResults=[]\n\tclients=[]\t\t\t\t\t#[client,addr,query]\n\twcTimeSpan=0\n\tactiveQworker=[] #[Query,activeWorkerWorking]\n\t\n\tdeleteCommand=0\n\tpopular=\"\"\n\tpopularResult=[]\n\tchunkLength=0;\n\tfileSize=0;\n\tqHistory=[]\n\tquery=\"\"\n\tjobless=[] #Against jobless workers\n\tonJob=[]\t\t#Against in job workers\n\n\tif(\"myState.txt\" in os.listdir(os.getcwd())):\n\t\tstartFile=open(\"myState.txt\",\"r\")\n\t\tstartData=startFile.readlines()\n\t\tstartFile.close()\n\t\tprint startData\n\t\tprint startData[0]\n\t\twcData = ast.literal_eval(startData[0])\n\t\tjob=ast.literal_eval(startData[1])\n\t\tqResults=ast.literal_eval(startData[2])\n\t\tjobless=ast.literal_eval(startData[3])\n\t\tonJob=ast.literal_eval(startData[4])\n\t\tactiveQworker=ast.literal_eval(startData[5])\n\t\t# wcData=startData[0]\n\n\twhile(True):\n\t\ttry:\n\n\t\t\tdata,addr=sock.recvfrom(3072)\t\n\t\texcept socket.error as error:\n\n\t\t\tif \"[Errno 35]\" in str(error):\n\n\t\t\t\t# print \"time is: \",time.time()\n\n\t\t\t\tfor x in range(len(clients)):\t\t\n\t\t\t\t\tif(time.time()>clients[x][0]):\n\t\t\t\t\t\tprint \"Request client connection has gone skeptical...Breaking Connection!! \"\n\t\t\t\t\t\tdeleteCommand=1\n\t\t\t\t\t\tsock.sendto(\"15440,-,8,-,-,-,-\",clients[x][1])\n\t\t\t\t\t\trmv=0\n\t\t\t\t\t\tfor x in range(len(wcData)):\n\t\t\t\t\t\t\tif(wcData[x][4]==clients[x][1]):\n\t\t\t\t\t\t\t\tsock.sendto(\"15440,-,8,-,-,-,-\",wcData[x][1])\n\t\t\t\t\t\t\t\trmv+=1\n\t\t\t\t\t\tfor y in range(len(activeQworker)):\n\t\t\t\t\t\t\tif(activeQworker[y][0]==clients[x][1]):\n\t\t\t\t\t\t\t\tactiveQworker[y][1]-=rmv\n\n\n\t\t\t\t\tif(x==len(clients)-1 and deleteCommand==1):\n\t\t\t\t\t\tdel clients[x]\n\t\t\t\t\t\tdeleteCommand=0;\t\n\t\t\t\t\t\t# return;\n\n\t\t\t\tif(len(qHistory)>=1):\n\t\t\t\t\tpopular=(Counter(qHistory).most_common(1))[0][0]\n\t\t\t\t\t# print \"popular is: \",popular\n\n\t\t\t\tif(time.time()>serverState):\n\t\t\t\t\tmyFile=open(\"myState.txt\",\"w\")\n\t\t\t\t\tprint \"Updating state\"\n\t\t\t\t\tmyFile.write(str(wcData)+\"\\n\");\n\t\t\t\t\tmyFile.write(str(job)+\"\\n\");\n\t\t\t\t\tmyFile.write(str(qResults)+\"\\n\");\n\t\t\t\t\tmyFile.write(str(jobless)+\"\\n\");\n\t\t\t\t\tmyFile.write(str(onJob)+\"\\n\");\n\t\t\t\t\tmyFile.write(str(activeQworker)+\"\\n\");\n\n\t\t\t\t\tmyFile.close()\n\t\t\t\t\tserverState=time.time()+30\n\n\n\t\t\t\tif(len(qResults)>0):\n\t\t\t\t\tfor z in range(len(qResults)):\n\t\t\t\t\t\tif(popular==qResults[z][0]):\n\t\t\t\t\t\t\tpopularResult.append(qResults[z])\n\n\t\t\t\t\tvalid=1\n\t\t\t\t\t# print \"check1\"\n\t\t\t\t\tfor x in range(len(activeQworker)):\n\t\t\t\t\t\t# print \"check2\"\n\t\t\t\t\t\tif(activeQworker[x][1]<=0):\n\t\t\t\t\t\t\tfor y in range(len(job)):\n\t\t\t\t\t\t\t\t# print \"job detected\"\n\t\t\t\t\t\t\t\tif(activeQworker[x][0]==job[y][0]):\n\t\t\t\t\t\t\t\t\tvalid=0\n\t\t\t\t\t\t\tif(valid==1 and threading.active_count()==1 and len(qResults)>0):\n\t\t\t\t\t\t\t\tprint \"check4\"\n\n\t\t\t\t\t\t\t\t#Search has been already completed send result to client\n\t\t\t\t\t\t\t\t# start_new_thread(send2Client,(sock,qResults,clients,activeQworker[x][0]))\n\t\t\t\t\t\t\t\tt = threading.Thread(target=send2Client, args=(sock,qResults,clients,activeQworker[x][0]))\n\t\t\t\t\t\t\t\tt.start()\n\n\n\t\t\t\tif(len(wcData)> 0):\n\t\t\t\t\tfor x in range(0,len(wcData)):\n\n\n\t\t\t\t\t\t# print \"Main data: \",wcData[x]\n\n\t\t\t\t\t\tif (time.time()> wcData[x][0] and wcData[x][3]<3 and wcData[x][5]==0):\n\t\t\t\t\t\t\tprint \"resending job until 3 time\"\n\t\t\t\t\t\t\twcData[x]=reAssignJob(wcData[x],sock)\n\t\t\t\t\t\t\t# print \"wcData later: \",wcData\n\t\t\t\t\t\telif(wcData[x][3]>=3):\n\t\t\t\t\t\t\tprint \"Gonna delete this dead node: \",wcData[x][1]\n\t\t\t\t\t\t\tdeleteCommand=1;\n\t\t\t\t\t\t\tsock.sendto(\"15440,-,8,-,-,-,-\",wcData[x][1])\n\n\t\t\t\t\t\t\t# del wcData[x] Will delete down\n\n\t\t\t\t\t\tif(time.time()>=wcData[x][0] and wcData[x][8]<3):\n\t\t\t\t\t\t\tprint \"Ping not answered. Resending!!!\"\n\n\t\t\t\t\t\t\tsock.sendto(\"15440,-,0,-,-,-,-\",wcData[x][1])\n\t\t\t\t\t\t\twcData[x][0]+=14;\n\t\t\t\t\t\t\twcData[x][8]+=1;\n\t\t\t\t\t\t\n\t\t\t\t\t\telif(time.time()>=wcData[x][0] and wcData[x][8]>=3):\n\t\t\t\t\t\t\tprint \"Connection of: \",wcData[x][1],\" has gone skeptical. Disconnecting with the worker!!\"\t\n\t\t\t\t\t\t\t#putting the job left by the worker into the job Queue\n\t\t\t\t\t\t\tsock.sendto(\"15440,-,8,-,-,-,-\",wcData[x][1])\n\n\t\t\t\t\t\t\tjob.append([wcData[x][4],int(wcData[x][6]),int(wcData[x][2][1])])\n\n\t\t\t\t\t\t\tfor z in range(len(activeQworker)):\n\t\t\t\t\t\t\t\tif(activeQworker[z][0]==wcData[x][4]): #Active worker decreases\n\t\t\t\t\t\t\t\t\tactiveQworker[z][1]-=1; \n\n\t\t\t\t\t\t\t# print \"deleting data of this worker: \"\n\t\t\t\t\t\t\tdeleteCommand=1;\n\t\t\t\t\t\t\t# del wcData[x] Will delete down\n\n\n\n\t\t\t\t\t\tif(time.time()>=(wcData[x][0]-5) and wcData[x][5]==1 and time.time()>=wcTimeSpan): #Worker client has confirmed job req Now\n\t\t\t\t\t\t\t#Ping worker client\n\t\t\t\t\t\t\tsock.sendto(\"15440,-,0,-,-,-,-\",wcData[x][1])\n\t\t\t\t\t\t\t# wcData[x][0]+=0.1;\n\t\t\t\t\t\t\twcTimeSpan=time.time()+3\n\n\n\t\t\t\t\t#If there is a job divide equally among jobless\n\t\t\t\tif(len(job)>0 and len(jobless)>0 ):\n\t\t\t\t\t\t#assign task to free workers\n\t\t\t\t\tfor y in range(len(job)):\n\n\t\t\t\t\t\tcurrentJob=job.pop();\n\n\t\t\t\t\t\tallowedWorkers=0;\n\t\t\t\t\t\tquery=currentJob[0]\n\n\t\t\t\t\t\tprint \"active worker: \",activeQworker\n\t\t\t\t\t\tprint \"current job: \",currentJob\n\n\n\t\t\t\t\t\tfor z in range(len(activeQworker)):\n\t\t\t\t\t\t\tif(activeQworker[z][0]==currentJob[0]): #If queries are equall\n\t\t\t\t\t\t\t\tallowedWorkers=5-activeQworker[z][1]\n\n\n\t\t\t\t\t\tif(len(jobless)>0 and len(jobless)<allowedWorkers):\n\t\t\t\t\t\t\tchunkLength=(currentJob[2]-currentJob[1])/(len(jobless))\n\t\t\t\t\t\tif(len(jobless)>allowedWorkers):\n\t\t\t\t\t\t\tchunkLength=(currentJob[2]-currentJob[1])/allowedWorkers\n\n\t\t\t\t\t\t# for z in range(len(wcData)):\n\t\t\t\t\t\t\t# if()\n\n\t\t\t\t\t\tcurChunk=currentJob[1];\n\t\t\t\t\t\tfor x in range(0,allowedWorkers):\t\t\t\t\n\n\t\t\t\t\t\t\tif(x>=len(jobless)):\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tonJob.append(jobless[x])\n\t\t\t\t\t\t\t# onJob[x][1]=random.randint(0,1000)\n\t\t\t\t\t\t\tprint \"Connecting to: \",jobless[x][0]\n\t\t\t\t\t\t\tstring=\"15440,-,2,%d,%d,%s,-\" %(curChunk, (curChunk+chunkLength), query)\n\t\t\t\t\t\t\tsock.sendto(string,jobless[x][0])\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\twcData.append([(time.time()+7),jobless[x][0],[curChunk,curChunk+chunkLength],1,query,0,curChunk,0,0])\n\t\t\t\t\t\t\t#[time,addr,[chunk range], timesAssigned,query,accepted,searched,jobDone,unansweredPings]\n\t\t\t\t\t\t\t#[time,addr,[chunk range], timesAssigned,query,accepted,searched,jobDone,pingsDiscarded]\n\t\t\t\t\t\t\tfor z in range(len(activeQworker)):\n\t\t\t\t\t\t\t\tif(activeQworker[z][0]==query):\n\t\t\t\t\t\t\t\t\tactiveQworker[z][1]+=1\n\n\t\t\t\t\t\t\tcurChunk=curChunk+chunkLength\n\n\t\t\t\t\t\tfor y in range(0,len(onJob)):\n\t\t\t\t\t\t\tif onJob[y] in jobless:\n\t\t\t\t\t\t\t\tjobless.remove(onJob[y])\n\n\t\t\t\tif(len(activeQworker)>0 and len(jobless)>0): #There are more than 1 search query\t\t\n\t\t\t\t\tfor x in range(len(activeQworker)):\n\t\t\t\t\t\tif(activeQworker[x][1]>=5):\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tcurrentProgress=[]\n\t\t\t\t\t\t\t#assign him some part of work to new worker!!!\n\t\t\t\t\t\t\tfor y in range(len(wcData)):\n\t\t\t\t\t\t\t\tcurrentProgress.append(wcData[y][2][1]-wcData[y][6])\n\t\t\t\t\t\t\tmaxVal=max(currentProgress) #Max data left to be searched\n\t\t\t\t\t\t\tmaxIndex=currentProgress.index(maxVal)\n\n\t\t\t\t\t\t\tif(maxVal<50000000): #If the chunk is too short just skip\n\t\t\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t\t\t#Assign to new worker and update prev worker\n\t\t\t\t\t\t\t# string=\"15440,-,2,%d,%d,%s,-\" %(curChunk, (curChunk+chunkLength), query)\n\t\t\t\t\t\t\tprimaryLimit=maxVal/2+wcData[y][6]\n\t\t\t\t\t\t\tstring=\"15440,-,2,%d,%d,%s,-\" %(0,primaryLimit, wcData[maxIndex][4])\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tsock.sendto(string,wcData[maxIndex][1])\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tsecondaryLimit=primaryLimit+maxVal/2;\n\t\t\t\t\t\t\tstring1=\"15440,-,2,%d,%d,%s,-\" %(primaryLimit, (secondaryLimit),wcData[maxIndex][4])\n\t\t\t\t\t\t\tsock.sendto(string1,jobless[0][0])\n\t\t\t\t\t\t\tonJob.append(jobless[0])\n\n\t\t\t\t\t\t\tfor z in range(len(activeQworker)):\n\t\t\t\t\t\t\t\tif(activeQworker[z][0]==wcData[maxIndex][4]):\n\t\t\t\t\t\t\t\t\tactiveQworker[z][1]+=1\n\n\t\t\t\t\t\t\tfor y in range(0,len(onJob)):\n\t\t\t\t\t\t\t\tif onJob[y] in jobless:\n\t\t\t\t\t\t\t\t\tjobless.remove(onJob[y])\n\n\n\n\t\t\t\tif(deleteCommand==1):\n\t\t\t\t\tdel wcData[x];\n\t\t\t\t\tdeleteCommand=0;\n\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\traise error\n\n\t\t# print \"came out\"\n\t\t# print \"Data: \",data\n\t\tparts=data.split(\",\");\n\t\t# print \"qResults: \",qResults\n\t\t# print \"activeQworker\",activeQworker\n\t\t# print \"wcData\",wcData\n\t\t# print \"clients\",clients\n\n\t\tif(parts[2]==\"-1\"): #Client connected\n\t\t\t\n\t\t\tquery=parts[5]\n\t\t\tqHistory.append(query)\n\t\t\tclients.append([time.time()+15,addr,query]) #<---\n\t\t\t\n\t\t\tif(query==popular):\n\t\t\t\tt = threading.Thread(target=send2Client, args=(sock,popularResult,clients,query))\n\t\t\t\t# t.start()\n\t\t\t\tcontinue\n\n\n\n\t\t\tqResults.append([query,0])\n\t\t\tactiveQworker.append([query,0])\n\n\t\t\tif(fileSize==0):\n\t\t\t\tfileSize=findSize(\"source\")\n\t\t\t\tfileSize=150000000\n\n\t\t\tif(len(jobless)==0):\n\t\t\t\tprint \"No worker client connected(available) right now!! Wait a sec\"\n\t\t\t\tjob.insert(0,[query,0,fileSize]) #Job will be queued\n\t\t\t\tprint \"job len: \",len(job)\n\n\t\t\tif(len(jobless)>0 and len(jobless)<5):\n\t\t\t\tchunkLength=fileSize/(len(jobless))\n\t\t\tif(len(jobless)>5):\n\t\t\t\tchunkLength=fileSize/5\n\n\t\t\tcurChunk=0;\n\t\t\tfor x in range(0,5):\t\t\t\t\n\t\t\t\tif(x>=len(jobless)):\n\t\t\t\t\tbreak\n\n\t\t\t\tonJob.append(jobless[x])\n\t\t\t\t# onJob[x][1]=random.randint(0,1000)\n\t\t\t\tprint \"Connecting to: \",jobless[x][0]\n\t\t\t\tstring=\"15440,-,2,%d,%d,%s,-\" %(curChunk, (curChunk+chunkLength), query)\n\t\t\t\tsock.sendto(string,jobless[x][0])\n\t\t\t\tactiveQworker[-1][1]+=1; #Will add to last worker\n\t\t\t\tprint \"increased\"\n\t\t\t\twcData.append([(time.time()+8),jobless[x][0],[curChunk,curChunk+chunkLength],1,query,0,curChunk,0,0])\n\t\t\t\t#[time,addr,[chunk range], timesAssigned,query,accepted,searched,jobDone,unansweredPings]\n\t\t\t\tcurChunk=curChunk+chunkLength\n\t\t\t\tprint \"active workers: \",activeQworker\n\n\t\t\tfor y in range(0,len(onJob)):\n\t\t\t\tif onJob[y] in jobless:\n\t\t\t\t\tjobless.remove(onJob[y])\n\t\t\t\t\tonJob[y][1]=random.randint(0,1000)\n\n\t\t\tprint \"file size is: \", fileSize\n\n\t\t\t# rcPing=0\n\t\t\t# rcPing=time.time()+15 #Request client ping time ends at\n\n\n\t\tif(parts[2]==\"0\"):\t\t#Against the ping\n\t\t\tfor z in range(len(clients)):\n\t\t\t\tif(addr==clients[z][1]):\n\t\t\t\t\tprint \"reseting clients ping\"\n\t\t\t\t\tclients[z][0]=time.time()+15\n\n\n\t\tif(parts[2]==\"1\"): #When worker clients joins\n\t\t\tjobless.append([addr,0])\n\t\t\tprint \"jobless are: \",jobless\n\t\t\tprint \"length of jobless: \",len(jobless)\n\n\t\tif (parts[2]==\"3\"): #confirmation of the job\n\t\t\tfor x in range(0,len(wcData)):\n\t\t\t\tif(addr==wcData[x][1]):\n\t\t\t\t\t# print \"resetting wc time of\",addr,\" wcdata\",wcData[x] \n\t\t\t\t\t# wcData[x][0]=wcData[x][0]+3\n\n\t\t\t\t\twcData[x][5]=1;\n\t\t\t\t\t# print \"later: \",wcData[x]\n\n\t\tif(parts[2]==\"6\"):\n\t\t\t# print \"Search \",parts[6]\n\t\t\t# print \"Search done till: \",parts[3],\"---\",parts[4]\n\t\t\t\n\t\t\tfor y in range(len(wcData)):\n\t\t\t\tif(wcData[x][1]==addr):\n\t\t\t\t\twcData[x][0]=time.time()+10\n\n\n\t\t\tfor x in range(len(wcData)):\n\t\t\t\tif(wcData[x][1]==addr): #Updating the chunks read\t\t\t\n\t\t\t\t\tprint \"updating chunks: \",parts[4]\n\n\t\t\t\t\twcData[x][6]=int(parts[4])\n\t\t\t\t\t# print \"Updated: \",wcData[x]\n\n\t\t\tfor x in range(len(qResults)):\n\t\t\t\tif(qResults[x][0]==parts[5]):\n\t\t\t\t\tresults=parts[6].split(\"|<->|\")\n\t\t\t\t\t# qResults[x].append(results);\n\t\t\t\t\tfor y in range(len(results)-1):\n\t\t\t\t\t\t# print \"results are: \",results[y]\n\t\t\t\t\t\tqResults[x].append(results[y]) #Results against query\n\n\t\t\t\t\t# print \"result length: \", results[len(results)-1]\n\t\t\t\t\t# print \"qResults are: \",qResults\n\t\t\t\t\t# qResults[x][1]=qResults[x][1]+int(results[len(results)-1]) <<<<<<<<-------\n\n\t\tif(parts[2]==\"5\"):\n\n\t\t\tfor z in range(len(qResults)):\n\t\t\t\tif(qResults[z][0]==parts[5]):\n\t\t\t\t\tqResults[z][1]+=int(parts[6])\n\n\n\t\t\t# Worker client Successfulyy completed search\n\t\t\tprint \"job done by: \",addr\n\t\t\t# for x in range(len(wcData)):\n\t\t\t# \tif(wcData[x][1]==addr):\n\t\t\t# \t\twcData[x][7]=1;\n\t\t\tprint \"final qResults: \",qResults\n\t\t\t# print \"on job: \",onJob\n\t\t\tfor y in range(len(onJob)):\n\t\t\t\tif(onJob[y][0]==addr):\n\t\t\t\t\tjobless.append(onJob[y])\n\t\t\t\t\t# onJob.remove(onJob[y]) #<<<<---------\n\n\t\t\tfor y in range(0,len(jobless)):\n\t\t\t\tif jobless[y] in onJob:\n\t\t\t\t\tonJob.remove(jobless[y])\n\n\t\t\t# print \"on job: \",onJob\n\t\t\t# print \"on job: \",jobless\n\t\t\tfor z in range(len(activeQworker)):\n\t\t\t\tif(activeQworker[z][0]==parts[5]):\n\t\t\t\t\tprint \"decreased\"\n\t\t\t\t\tactiveQworker[z][1]-=1\n\n\t\t\tfor x in range(len(wcData)):\n\t\t\t\tif(wcData[x][1]==parts[1]):\n\t\t\t\t\tdel wcData[x] #Current progress deleted by when job is done\n\n\t\t\tprint \"activeQworker after completing job: \",activeQworker\n\n\t\t\t#Also delete from wcData\n\t\t\t#Also uodate activeQworker\n\n\nif __name__==\"__main__\":\n\tmain(sys.argv)\n\n" }, { "alpha_fraction": 0.615760087966919, "alphanum_fraction": 0.6276150345802307, "avg_line_length": 24.79279327392578, "blob_id": "c33a52410c34c6256ba7ea1524979e6dff70304b", "content_id": "1721b976852c5407c01bbbe82825e667d3974f69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2868, "license_type": "no_license", "max_line_length": 90, "num_lines": 111, "path": "/searchQuery/server.py", "repo_name": "R-Niagra/Networking-Projects", "src_encoding": "UTF-8", "text": "import socket\nimport sys\nimport os\nfrom thread import *\n\ndef clientthread(client,default):\n\tclient.send(\"Server: Welcome to CS 382 search engine! Please enter your search Query:\")\n\tquery=client.recv(2000) # this value is the buffer capacity\n\tprint query\n\n\twhile(1):\n\n\t\tos.chdir(default)\n\t\tserverPath=os.getcwd()\n\t\tbbcPath=serverPath+\"/bbcsport\"\n\n\t\tfiles=os.listdir(bbcPath)\n\t\t#print files\n\t\tfor i in range(1,len(files)):\n\n\t\t\tif('.' not in files[i]):\n\t\t\t\tnewPath=bbcPath+'/'+files[i]\n\t\t\t\tos.chdir(newPath)\t\t\t\t\t\n\t\t\t\tnewFiles=os.listdir(newPath)\n\t\t\t\tfor f in range(0,len(newFiles)):\n\t\t\t\t\tif(query in newFiles[f]):\n\t\t\t\t\t\tcurrentPath=os.getcwd()+\"/\"+newFiles[f]\n\t\t\t\t\t\tposit=currentPath.find(\"bbcsport\")\n\t\t\t\t\t\tslicedPath=currentPath[posit:]\n\t\t\t\t\t\tclient.send(slicedPath)\n\t\t\t\t\t\t\n\t\t\t\t\tif(newFiles[f][-3:]=='txt' or newFiles[f][-3:]=='TXT'):\t #It ensures that file is txt\n\t\t\t\t\t\twith open(newFiles[f],'r') as infile:\n\t\t\t\t\t\t\tfileData=infile.readlines()\n\t\t\t\t\t\tfor line in fileData:\n\t\t\t\t\t\t\tif query in line:\n\t\t\t\t\t\t\t\tcurrentPath=os.getcwd()+\"/\"+newFiles[f]\n\t\t\t\t\t\t\t\tposit=currentPath.find(\"bbcsport\")\n\t\t\t\t\t\t\t\tslicedPath=currentPath[posit:]\n\t\t\t\t\t\t\t\tclient.send(slicedPath) #This is the shortened path sent to the client\n\t\t\t\t\t\t\t\tclient.send(''.join(fileData))\n\t\t\t\t\t\t\t\tbreak\n\n\t\t\telif('.'in files[i]):\n\t\t\t\tos.chdir(bbcPath)\n\t\t\t\tif(query in files[i]):\n\t\t\t\t\tcurrentPath=os.getcwd()+\"/\"+files[i]\n\t\t\t\t\tposit=currentPath.find(\"bbcsport\")\n\t\t\t\t\tslicedPath=currentPath[posit:]\n\t\t\t\t\tclient.send(slicedPath)\n\t\t\t\n\t\t\t\tif(newFiles[f][-3:]=='txt' or newFiles[f][-3:]=='TXT'):\t\n\t\t\t\t\twith open(files[i],'r') as infile:\n\t\t\t\t\t\tfileData=infile.readlines()\n\t\t\t\t\tfor line in fileData:\n\t\t\t\t\t\tif query in line:\n\t\t\t\t\t\t\tcurrentPath=os.getcwd()+\"/\"+files[i]\n\t\t\t\t\t\t\tposit=currentPath.find(\"bbcsport\")\n\t\t\t\t\t\t\tslicedPath=currentPath[posit:]\n\t\t\t\t\t\t\tclient.send(slicedPath)\n\t\t\t\t\t\t\tclient.send(''.join(fileData))\n\t\t\t\t\t\t\tbreak\n\n\t\tclient.send(\"$$-Done-$$\") #This is a signal that search is finished\n\n\t\twhile(1):\n\t\t\tfolder=client.recv(2024)\n\t\t\tprint folder\n\t\t\tif(folder==\"exit\"):\n\t\t\t\tclient.close()\n\t\t\t\treturn \n\t\t\tfnd=folder.rfind(\"/\") #Finds / in reverse manner to extract file name and path\n\t\t\tdownloadD=bbcPath+\"/\"+folder[0:fnd]\n\t\t\tos.chdir(downloadD)\n\t\t\tprint os.getcwd()\n\t\t\tallFiles=os.listdir(downloadD)\n\t\t\tprint folder[fnd+1:]\n\t\t\tif(folder[fnd+1:] in allFiles):\n\n\t\t\t\twith open(folder[fnd+1:],'r') as infile:\n\t\t\t\t\tfileData=infile.readlines()\n\t\t\t\tclient.send(''.join(fileData))\t\n\t\t\t\tif(os.stat(folder[fnd+1:]).st_size == 0):\n\t\t\t\t\tclient.send(\"empty file\")\n\n\t\t\telse:\n\t\t\t\tclient.send(\"File doesnot exists!!\")\n\n\t\t\t\n\t\t\n\t\t\n\ndef main(argv):\n\n\tip='127.0.0.1'\n\ts=socket.socket()\n\ts.bind((ip,int(argv[1])))\n\tdefault=os.getcwd()\n\n\twhile 1:\n\t\ts.listen(5)\n\t\tclient,add=s.accept()\n\t\tstart_new_thread(clientthread,(client,default))\t\n\t\n\n\tclient.close()\n\ts.close()\t\n\n\nif __name__==\"__main__\":\n\tmain(sys.argv)\n\n\n\n\n\n" }, { "alpha_fraction": 0.8205128312110901, "alphanum_fraction": 0.8205128312110901, "avg_line_length": 38, "blob_id": "05a1f325a1dc79d0d6b40c8103e0ce25bf32ae7a", "content_id": "3e387c530c092996741078af0500c07bdee568cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 39, "license_type": "no_license", "max_line_length": 38, "num_lines": 1, "path": "/fileSharing/README.md", "repo_name": "R-Niagra/Networking-Projects", "src_encoding": "UTF-8", "text": "A client server model for sharing data\n" }, { "alpha_fraction": 0.574698805809021, "alphanum_fraction": 0.6156626343727112, "avg_line_length": 15.959183692932129, "blob_id": "b6481462d6a644040e2ea570314bc07e406e7d7c", "content_id": "b94d96b3fd12b9679cb831ba605277768f634a59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 830, "license_type": "no_license", "max_line_length": 59, "num_lines": 49, "path": "/mapReduce/client.py", "repo_name": "R-Niagra/Networking-Projects", "src_encoding": "UTF-8", "text": "import socket\nimport sys\nimport os.path\nimport time\nfrom thread import *\n\n\ndef main(argv):\n\tsock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) \n\tsip=argv[1]\n\tsport=int(argv[2])\n\taddr=(sip,sport)\n\tsock.setblocking(0)\n\n\tquery=raw_input(\"Plese enter your Query:- \")\n\tsock.sendto(\"15440,-,-1,-,-,%s,-\" %query ,addr)\n\tpingTime=time.time()+5\t\n\n\twhile True:\n\t\t\n\t\t# data,addr=sock.recvfrom(1024)\t\n\n\t\ttry:\n\n\t\t\tdata,addr=sock.recvfrom(1024)\n\n\t\texcept socket.error as error:\n\n\t\t\tif \"[Errno 35]\" in str(error):\n\t\t\t\t# if(time.time()>=ping):\n\t\t\t\t# \tsock.sendto(\"15440,-,3,-,-,-,-\",addr) \n\t\t\t\tif(time.time()>pingTime): #Pings every 5 seconds\n\t\t\t\t\tprint \"Pinging\"\n\t\t\t\t\tsock.sendto(\"15440,-,0,-,-,-,-\",addr)\n\t\t\t\t\tpingTime=time.time()+5\n\n\t\t\t\tcontinue\n\n\t\t\telse:\n\t\t\t\traise error\n\n\n\t\tprint data\n\t\t\t\n\n\n\nif __name__==\"__main__\":\n\tmain(sys.argv)" }, { "alpha_fraction": 0.5799792408943176, "alphanum_fraction": 0.6028139591217041, "avg_line_length": 20.390180587768555, "blob_id": "57da1495c0e0a6afd3962728f5b6c515a34a1954", "content_id": "7aed1404a1c766662ee317ffe4061df3b3498434", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8671, "license_type": "no_license", "max_line_length": 141, "num_lines": 387, "path": "/bittorent/peer.py", "repo_name": "R-Niagra/Networking-Projects", "src_encoding": "UTF-8", "text": "from __future__ import division\r\nfrom collections import Counter\r\nimport math\r\nimport socket\r\nimport sys\r\nimport os.path\r\nfrom thread import *\r\nimport shutil\r\nimport uuid\r\nimport random\r\nimport time\r\n\r\n\r\ndef createTorrents(uploadsPath, torrentsPath):\r\n\r\n\tcount = random.randint(0,100)\r\n\tcount=count^2+31\r\n\tprint \"count: \",count \r\n\tif not os.path.exists(torrentsPath):\r\n\t\tos.makedirs(torrentsPath)\r\n\t\r\n\tfiles = os.listdir(uploadsPath)\r\n\tprint files\r\n\tfor file in files:\r\n\t\tcount = count + 1\r\n\t\ttorrent = open((\"torrents/\" + str(count) + \".torrent\"), \"w\")\r\n\t\ttorrent.write(\"Name:%s\\n\" %file)\r\n\t\ttorrent.write(\"Key : \" + str(uuid.uuid4()) + \"\\n\")\r\n\t\ttorrent.write(\"size : %d bytes\\n\" %os.path.getsize(uploadsPath+\"/\"+file))\r\n\t\ttorrent.write(\"n_parts : 30\\n\")\r\n\r\n# def breakConnection(s)\r\n# \ts.close()\r\n\r\ndef sendToPeer(client,addr):\r\n\tclient.send(\"U are connected with the peer!!!!!!!!!!\")\r\n\tfile2Send=client.recv(1024)\r\n\r\n\tdownloadRecord=open(\"downloadRecord.txt\",\"a+\")\r\n\tdownloadRecord.seek(0)\r\n\tdownloadData=downloadRecord.readlines()\r\n\r\n\r\n\tcounter=0;\r\n\tmaximum=0;\r\n\r\n\tfor line in downloadData:\r\n\t\tif str(addr[1]) in downloadData:\r\n\t\t\tcounter+=1;\r\n\r\n\tprint \"download data: \",downloadData\r\n\tif(len(downloadData)!=0):\r\n\t\tmaximum=(Counter(downloadData).most_common(1))[0][1]\r\n\r\n\tprint \"counter\", counter, \"max: \",maximum\r\n\tprint \"Time sleep is: \",maximum-counter\r\n\t# time.sleep(maximum-counter)\r\n\r\n\r\n\tprint file2Send\r\n\tcurrentDir=os.getcwd()\r\n\tfilePath = os.getcwd() + \"/uploads\"\r\n\t# print filePath\r\n\t# os.chdir(filePath)\r\n\t\r\n\t# if os.path.exists(file2Send):\r\n\t\r\n\tchunkFile=open(\"chunkRecord.txt\",\"a+\")\r\n\tchunkFile.seek(0)\r\n\tchunkRecord=chunkFile.readlines();\r\n\r\n\tprint chunkRecord\r\n\t# print chunkRecord[0],chunkRecord[1]\r\n\r\n\r\n\tos.chdir(filePath)\r\n\tfileReq=open(file2Send,\"r\")\r\n\tfileData=fileReq.readlines()\r\n\t# print fileData\r\n\r\n\r\n\tprint addr\r\n\tchunkStart=0;\r\n\r\n\tif(len(chunkRecord)!=0):\r\n\t\tprint \"came in chunk\"\r\n\t\tfor line in chunkRecord:\r\n\t\t\tprint line\r\n\t\t\tif addr[0]+\" \"+str(addr[1])+\" \"+file2Send in line:\r\n\t\t\t\tchunkStart=int(line.split(\" \",3)[3])\r\n\t\t\t\tprint \"Resume from\", chunkStart\r\n\r\n\t\t\t\r\n\r\n\r\n\tlength=len(fileData)\r\n\tchunkSize=int(length/30)\r\n\r\n\tprint \"Chunks size is: \",chunkSize \r\n\r\n\tx=chunkStart;\r\n\r\n\ttry:\r\n\r\n\t\tfor x in range(chunkStart,31):\r\n\t\t\r\n\t\t\ttime.sleep((maximum-counter)*0.5)\r\n\r\n\t\t\tconfirm=client.recv(1024)\r\n\t\t\t# if x is not 30:\r\n\t\t\tclient.send(''.join(fileData[x*chunkSize : (x+1)*chunkSize]))\r\n\t\t\t# if x is 30:\r\n\t\t\t# \tprint \"came in last\"\r\n\t\t\t# \tclient.send(''.join(fileData[x*chunkSize:]))\r\n\t\t\t\r\n\t\t\tif not confirm:\r\n\t\t\t\tbreak\r\n\r\n\t\t\t# client.recv(1024)\r\n\t\t\tprint \"Data sent: \",int ((x/30)*100),\"%\\n\"\r\n\t\t\ttime.sleep(0.1)\r\n\t\t\t# time.sleep((maximum-counter)*0.5)\r\n\r\n\r\n\texcept IOError as e:\r\n\t\t \tprint \"client is disconnected\"\r\n\t\t \tprint \"sent till: \",x\r\n\t\t \tchunkFile.write(addr[0]+\" \"+str(addr[1])+\" \"+file2Send+\" \"+str(x-1)+\"\\n\")\r\n\t\t \tclient.close()\r\n\t\t \tfileReq.close();\r\n\t\t \tchunkFile.close()\r\n\t\t\tos.chdir(currentDir)\r\n\t\t \treturn\r\n\r\n\t# if(len(chunkRecord)!=0): //Required to remove those fully downloaded!\r\n\t# \tfor line in chunkRecord:\r\n\t# \t\tprint line\r\n\t# \t\tif addr[0]+\" \"+str(addr[1])+\" \"+file2Send in line:\r\n\r\n\r\n\tfileReq.close();\r\n\tchunkFile.close()\r\n\tdownloadRecord.close()\r\n\tos.chdir(currentDir)\r\n\tclient.close()\r\n\r\n\tchunkF=open(\"chunkRecord.txt\",\"w\")\r\n\tfor line in chunkRecord:\r\n\t\tif addr[0]+\" \"+str(addr[1])+\" \"+file2Send not in line:\r\n\t\t\tchunkF.write(line)\r\n\r\n\tchunkF.close()\r\n\r\n\t# if(len(chunkRecord)!=0): //Required to remove those fully downloaded!\r\n\t# \tfor line in chunkRecord:\r\n\t# \t\tprint line\r\n\t# \t\tif addr[0]+\" \"+str(\r\n\r\n\r\n\r\n\r\n\r\ndef listenToTracker(s):\r\n\r\n\r\n\tchoice=0;\r\n\tchoice2=-15\r\n\t\t\r\n\r\n\t# s = socket.socket() # Create a socket object\r\n\t# s.connect((argv[1],int(argv[2])))\r\n\t# address=s.getsockname()\r\n\t\r\n\twhile(1):\t\t\r\n\t\t\r\n\t\tchoice=input(\"Press 1 to send stuff to tracker\\nPress 2 to download a file\\nPress 3 to break connection with tracker \\nPress -1 to quit\\n\")\r\n\t\t\r\n\t\tif(choice==-1):\r\n\t\t\ts.send(\"^^Quiet^^\")\r\n\t\t\ts.close()\r\n\t\t\texit()\r\n\r\n\r\n\t\tif(choice==1):\r\n\t\t\ts.send(\"~Sending Torrent File::~\")\r\n\t\t\ttime.sleep(.3)\r\n\t\t\ttorrentsPath = os.getcwd() + \"/torrents\"\r\n\t\t\tuploadsPath = os.getcwd() + \"/uploads\"\r\n\t\t\tcreateTorrents(uploadsPath, torrentsPath)\r\n\t\t\tshutil.make_archive(\"zipped\", 'zip', torrentsPath)\r\n\r\n\t\t\t# s = socket.socket() # Create a socket object\r\n\t\t\t# s.connect((argv[1],int(argv[2])))\r\n\r\n\t\t\tfilename='zipped.zip'\r\n\t\t\tf = open(filename,'rb')\r\n\t\t\tl = f.read(1024)\r\n\r\n\t\t\twhile (l):\r\n\t\t\t\ts.send(l)\r\n\t\t\t\t# print('Sent ',repr(l))\r\n\t\t\t\tl = f.read(1024)\r\n\t\t\tf.close()\r\n\t\t\ts.send(\"~^~Done Sending~^~\")\r\n\t\t\tprint('Done sending')\r\n\t\t\ts.recv(1024)\r\n\t\t\t# s.send('Thank you for connecting')\r\n\t\t\tchoice2=input(\"Press 0 to break connection with tracker \\nPress 1 to review menu\\n\")\r\n\t\t\tif(choice2==0):\r\n\t\t\t\ts.send(\"^^Quiet^^\")\r\n\t\t\t\t# s.close()\r\n\t\t\t\t# listen(address)\r\n\r\n\r\n\t\tif(choice==2):\r\n\t\t\ts.send(\"~Download mode~\");\r\n\t\t\treqFile=raw_input(\"Please enter the required file name: \")\r\n\t\t\ts.send(reqFile)\r\n\t\t\ttorFile=\"\"\r\n\r\n\t\t\tcount=1\r\n\t\t\twhile(1):\r\n\t\t\t\ttorFile=s.recv(2000)\r\n\t\t\t\tif(\"..Done Sending Torrents..\" in torFile):\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\t\treqTorrent=open(\"reqTorrent\"+str(count)+\".torrent\",'w')\r\n\t\t\t\treqTorrent.write(torFile)\r\n\r\n\t\t\t\ts.send(\"Received packet!\")\r\n\t\t\t\tcount+=1;\r\n\t\t\t\treqTorrent.close()\r\n\r\n\t\t\tpeersList=[]\r\n\t\t\tportList=[]\r\n\r\n\t\t\twhile(1): \t\t\t\t\t# Receiving peer ports!\r\n\r\n\t\t\t\tpeerData=s.recv(1024)\r\n\t\t\t\t\r\n\t\t\t\t# print \"Sent peer data: \",peerData\r\n\t\t\t\tif(\"--ALL PEERS SENT--\") in peerData: #18\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tpeersList.append(peerData)\r\n\t\t\t\ts.send(\"Received!!\")\r\n\r\n\r\n\r\n\t\t\t# print \"peer List\",peersList\r\n\r\n\r\n\t\t\tfor line in peersList:\r\n\t\t\t\tportList.append(line.split(\" \",2)[1])\r\n\r\n\t\t\t# peerPort=peerData.split(\" \",2)[1]\r\n\t\t\t# peerIp=peerData.split(\" \",2)[0]\r\n\r\n\r\n\t\t\t# print peerData\r\n\t\t\tprint \"Port list: \",portList\r\n\t\t\tpeerNumber=input(\"Enter the peer number u wanna connect to: \")\r\n\t\t\t\r\n\t\t\tif(len(portList)==0):\r\n\t\t\t\tprint \"File doesnot exists!!\"\r\n\t\t\t\treturn\r\n\r\n\t\t\tif(peerNumber > len(portList ) or peerNumber < 0 ):\r\n\t\t\t\tprint \"Invalid input\"\r\n\t\t\t\treturn;\r\n\r\n\t\t\tpeerPort=portList[peerNumber-1]\r\n\r\n\t\t\tfileSize=0\r\n\t\t\treqTorrent=open(\"reqTorrent1.torrent\",\"r\")\r\n\t\t\ttorrData=reqTorrent.readlines()\r\n\r\n\t\t\tfor line in torrData:\t\t\t#This checks for the file\r\n\t\t\t\tif \"size\" in line:\r\n\t\t\t\t\tfileSize=int(line.split(\" \",3)[2])\r\n\t\t\t\t\tbreak;\r\n\r\n\t\t\tprint \"file size is: \",fileSize\r\n\r\n\t\t\t# s.send(\"Received!!\")\r\n\r\n\r\n\t\t\t# choice2=input(\"Press 0 to break connection with tracker\\n\")\r\n\t\t\t# if(choice2==0):\r\n\t\t\t# \ts.send(\"^^Quiet^^\")\r\n\r\n\r\n\t\t\t# print \"till gere\"\r\n\t\t\tm = socket.socket() # Create a socket object\r\n\t\t\tm.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n\r\n\t\t\tportChoice=input(\"Enter the valid port number u wanna bind to: \")\r\n\t\t\tm.bind((\"127.0.0.1\",portChoice))\r\n\r\n\t\t\tm.connect((\"127.0.0.1\",int(peerPort)-2))\r\n\t\t\tprint \"till gere\"\r\n\t\t\tgot=m.recv(1024)\r\n\t\t\tprint got\r\n\t\t\tm.send(reqFile)\r\n\t\t\t\r\n\t\t\t# content=m.recv(1024)\r\n\t\t\t# m.send(\"chunk received!\")\r\n\t\t\t\r\n\t\t\tfileAsked=open(reqFile,\"a+\")\r\n\t\t\tcurPath=os.getcwd()\r\n\t\t\t\r\n\t\t\ttry:\r\n\r\n\t\t\t\twhile 1:\r\n\r\n\t\t\t\t\tm.send(\"receiving\")\r\n\r\n\t\t\t\t\tcontent=m.recv(2048)\r\n\t\t\t\t\tprint \"Data received: \",int ((os.path.getsize(curPath+\"/\"+reqFile)/fileSize)*100),\"%\\n\"\r\n\t\t\t\t\tif not content:\r\n\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t# m.send(\"chunk received!\")\r\n\t\t\t\t\t\r\n\t\t\t\t\tfileAsked.write(content)\r\n\t\t\t\t\t# print \"Data received: \",int ((os.path.getsize(curPath+\"/\"+reqFile)/fileSize)*100),\"%\\n\"\r\n\r\n\t\t\t\r\n\t\t\t\tdownloadRecord=open(\"downloadRecord.txt\",\"a+\")\r\n\t\t\t\tdownloadRecord.write(str(int(peerPort)-2)+\"\\n\")\r\n\r\n\t\t\t\tdownloadRecord.close()\r\n\r\n\r\n\t\t\texcept KeyboardInterrupt:\r\n\t\t\t\tprint \"Came in keyBoard interrupt\"\r\n\t\t\t\ts.close()\r\n\t\t\t\t# fileAsked.write(content)\r\n\t\t\t\tm.close()\r\n\r\n\t\t\t\r\n\r\n\t\t\tm.close()\r\n\t\t\tfileAsked.close()\r\n\r\n\t\t\t\t# s.close()\r\n\t\t\t\t# breakConnection(s)\r\n\t\t\t\t# connectWithPeer(peerIp,peerPort,s)\r\n\t\t\t\r\n\t\tif(choice==3):\r\n\t\t\ts.send(\"^^Quiet^^\")\r\n\t\t\t# s.close()\r\n\t\t\t# listen(address)\r\n\t\t\t# exit()\r\n\t\t\t\t\r\n\r\n\t\tchoice=-10\r\n\t\tchoice2=-10\r\n\r\n\t# s.close()\r\n\r\ndef main(argv):\r\n\r\n\ts = socket.socket() # Create a socket object\r\n\ts.connect((argv[1],int(argv[2])))\r\n\ts.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n\taddress=s.getsockname()\r\n\t\r\n\tn = socket.socket() # Create a socket object\r\n\tn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n\thost = '127.0.0.1' \r\n\tn.bind((host,int(address[1])-2)) # Bind to the port\r\n\tn.listen(5) # Now wait for client connection.\r\n\r\n\t\r\n\tstart_new_thread(listenToTracker,(s,))\r\n\r\n\twhile 1:\r\n\t\tclient, addr = n.accept() # Establish connection with client.\r\n\t\tstart_new_thread(sendToPeer,(client,addr))\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__==\"__main__\":\r\n\tmain(sys.argv)\r\n\r\n\r\n\r\n" } ]
15
shadowstep666/login
https://github.com/shadowstep666/login
0a1e56277555ee230601bbcb7696d22f06440054
1251ad88dce1c973175f043c3f7d06770f88ec1c
1d851c6a6ea2a1b2dc85e33c3d3611ee8539e33a
refs/heads/master
2020-05-16T04:23:47.122176
2019-04-22T12:11:36
2019-04-22T12:11:36
182,778,144
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.748031497001648, "alphanum_fraction": 0.748031497001648, "avg_line_length": 23.799999237060547, "blob_id": "af5fe0569acce78c3981ef9ab9a1d72ac765ad08", "content_id": "a242f9d30a0c37312fe6787ffbe32005210e1b60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 127, "license_type": "no_license", "max_line_length": 46, "num_lines": 5, "path": "/login/user.py", "repo_name": "shadowstep666/login", "src_encoding": "UTF-8", "text": "from mongoengine import Document , StringField\r\n\r\nclass User(Document):\r\n username=StringField()\r\n password=StringField()" }, { "alpha_fraction": 0.5471478700637817, "alphanum_fraction": 0.5518044233322144, "avg_line_length": 26.700000762939453, "blob_id": "cc5dc0d408b87e524d50d4c8725ff11d41a70237", "content_id": "558dc659beb90428c3bd977f203ab9d2e8062912", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 859, "license_type": "no_license", "max_line_length": 61, "num_lines": 30, "path": "/login/app.py", "repo_name": "shadowstep666/login", "src_encoding": "UTF-8", "text": "from flask import Flask,render_template,request,session,flash\r\nimport mlab\r\nfrom user import User\r\n\r\napp = Flask(__name__)\r\napp.config[\"SECRET_KEY\"] = \"abcd1234\"\r\nmlab.connect()\r\n\r\[email protected](\"/login\",methods=[\"GET\",\"POST\"])\r\ndef login():\r\n if request.method ==\"GET\":\r\n return render_template(\"login.html\")\r\n elif request.method==\"POST\":\r\n form = request.form\r\n u=form[\"username\"]\r\n p=form[\"password\"]\r\n users=User.objects(username=u).first()\r\n if users != None:\r\n\r\n if users.password == p :\r\n return \"hello\"\r\n else :\r\n flash(\"invalid password\")\r\n return render_template(\"login.html\")\r\n else :\r\n flash(\"username not found\")\r\n return render_template(\"login.html\")\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)" } ]
2
paradoxdjell/twitter
https://github.com/paradoxdjell/twitter
522686710251fe14974c7ca5fe778b39dca9dd47
a39c40fbfcda665001a3e2ae24b713d6e159fbbc
a861e6a1219e0378235df4f09517af336179d236
refs/heads/master
2018-10-21T23:00:22.439463
2015-08-22T12:03:28
2015-08-22T12:03:28
41,205,143
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 30.5, "blob_id": "12c7b96cd202797e4ff7f7b114ef4418a6dc47c6", "content_id": "aecf2341b63076adc05a499bcbecc32b822fb269", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 63, "license_type": "no_license", "max_line_length": 52, "num_lines": 2, "path": "/README.md", "repo_name": "paradoxdjell/twitter", "src_encoding": "UTF-8", "text": "# Twitter\nA Twitter client written in Python for a UNIX shell.\n" }, { "alpha_fraction": 0.5204491019248962, "alphanum_fraction": 0.5228548645973206, "avg_line_length": 30.9743595123291, "blob_id": "276b335fc19f732d1b3615959362bec4cfc1b187", "content_id": "0668554d573fbb4cf1d6a28eef9928fcaea27688", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1247, "license_type": "no_license", "max_line_length": 84, "num_lines": 39, "path": "/twitter.py", "repo_name": "paradoxdjell/twitter", "src_encoding": "UTF-8", "text": "import tweepy\nimport sys\n\ndef get_api(cfg):\n auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])\n auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])\n return tweepy.API(auth)\n\ndef main():\n cfg = {\n \"consumer_key\" : \"\",\n \"consumer_secret\" : \"\",\n \"access_token\" : \"\",\n \"access_token_secret\" : \"\"\n }\n\n api = get_api(cfg)\n\n while(1):\n command = input(\"[T]weet\\tSearch by [H]ashtag\\tCheck [F]ollowers\\tE[x]it\\n\")\n if((command==\"T\") or (command==\"t\")):\n tweet = input(\"Enter tweet: \")\n status = api.update_status(status=tweet)\n elif((command==\"H\") or (command==\"h\")):\n q = input(\"Enter hashtag: \")\n tweets = tweepy.Cursor(api.search, q).items(20)\n for tweet in tweets:\n print(tweet.created_at, tweet.text,\"\\n\")\n elif((command==\"F\") or (command==\"f\")):\n id = input(\"Enter ID: \")\n for user in tweepy.Cursor(api.followers, id).items():\n print(user.screen_name)\n elif((command==\"X\") or (command==\"x\")):\n sys.exit()\n else:\n print(\"Invalid option, try again.\")\n\nif __name__ == \"__main__\":\n main()\n" } ]
2
xujiaqi980622/scrapy_demo
https://github.com/xujiaqi980622/scrapy_demo
f66d2a0d2eabdd8fe1925b3828fc2953a8c31575
2934c02821e4e09e3837b61299d728e447ce4b2b
d00a21c8615bc771dce4517afe6b6af46e08dd8a
refs/heads/master
2021-04-13T07:04:37.114396
2020-03-22T09:39:49
2020-03-22T09:39:49
249,145,250
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5209256410598755, "alphanum_fraction": 0.5563761591911316, "avg_line_length": 38.82352828979492, "blob_id": "d757227f3147c54ad226dc7a26d18820151cf97d", "content_id": "a47aa45f9915e2de5bd316239a653f67916d23fa", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2201, "license_type": "permissive", "max_line_length": 115, "num_lines": 51, "path": "/news/news/spiders/finance.py", "repo_name": "xujiaqi980622/scrapy_demo", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport scrapy\nfrom ..items import NewsItem\n\n\nclass FinanceSpider(scrapy.Spider):\n # 爬虫名,启动爬虫时需要的参数\n name = 'finance'\n # 爬取域范围,允许爬虫在这个域名下进行爬取(可选)\n allowed_domains = []\n # url列表,爬虫执行后第一批请求,将从这个列表获取\n page = 2\n # 并发爬取\n # start_urls = ['http://news.21so.com/chanye/'+ str(page)+ '.html' for page in range(2, 6)]\n start_urls = ['http://news.21so.com/chanye/index.html', 'http://news.21so.com/chanye/' + str(page) + '.html', ]\n\n def parse(self, response):\n # print(response.body.decode())\n node_list = response.xpath('//div[@class=\"textBox\"]')\n for node in node_list:\n item = NewsItem()\n # 提取每条新闻的信息\n # 标题\n item['newsTitle'] = node.xpath('./h5/a/text()').extract()[0]\n # 关键字\n if len(node.xpath('./div[@class=\"tags\"]/a/text()')):\n item['newsKeyword'] = node.xpath('./div[@class=\"tags\"]/a/text()').extract()\n else:\n item['newsKeyword'] = \"\"\n # 链接\n item['newsLink'] = node.xpath('./h5/a/@href').extract()[0]\n\n detail_url = node.xpath('./h5/a/@href').extract()[0]\n # print(type(detail_url), detail_url, \"00000000000000000000000000000000000000000000000000\")\n yield scrapy.Request(url=detail_url, callback=self.detail_parse, meta={\"item\": item})\n\n # yield item\n # 构建下一页请求\n if int(self.page) < 6:\n self.page += 1\n url = 'http://news.21so.com/chanye/' + str(self.page) + '.html'\n yield scrapy.Request(url, callback=self.parse)\n\n def detail_parse(self, response):\n item = response.meta[\"item\"]\n node_list = response.xpath('//div[@class=\"articleInfo\"]')\n for node in node_list:\n item['newsSource'] = node.xpath('normalize-space(./span[@class=\"articleSource\"]/text())').extract()[0]\n item['newsTime'] = node.xpath('normalize-space(./span[@class=\"articleDate\"]/text())').extract()[0]\n\n yield item\n" } ]
1
prantik-ghosh/bowling_performance_predictor_in_test_cricket
https://github.com/prantik-ghosh/bowling_performance_predictor_in_test_cricket
e82ff4f34db46ff7d60fd02752bfdc1368e077c7
37b6f29981cf9d57b74604114c2629de196247c4
7d44851dc6a8771d4a0b2820a4fcb720f30d9fd6
refs/heads/master
2021-05-14T08:24:29.136221
2018-01-24T04:27:52
2018-01-24T04:27:52
116,294,923
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.577825665473938, "alphanum_fraction": 0.585488498210907, "avg_line_length": 38.58293914794922, "blob_id": "1e4ce0204a508dfd5a0459e6b69cc8593d1afe9b", "content_id": "404716776f4e5002a517f24b5dcb98462f22aa92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8352, "license_type": "no_license", "max_line_length": 122, "num_lines": 211, "path": "/src/python_scripts/run_lr_and_rf_for_various_feature_sets.py", "repo_name": "prantik-ghosh/bowling_performance_predictor_in_test_cricket", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import explained_variance_score\nfrom sklearn.metrics import mean_squared_error\nimport statsmodels.api as sm\n\n\n\n\ndef fit_lr_model(df, X_train, y_train, X_test, y_test, mask_test):\n \"\"\"\n Trains a linear regression model for the passed X_train and y_train,\n predicts target for the passed X_test using the trained model,\n groups data by player to find expected number of wickets for the entire season,\n and finally calculates explained variance and MSE.\n \"\"\"\n print(\"**** LINEAR REGRESSION ****\")\n lin_mod = sm.OLS(y_train, sm.add_constant(X_train))\n fit_lin = lin_mod.fit()\n print(fit_lin.summary())\n\n y_pred_test = fit_lin.predict(sm.add_constant(X_test))\n df_test = pd.concat([df[mask_test][['player','wkts','year1_wkts_pm']].reset_index(),\n pd.DataFrame(y_pred_test).reset_index()],axis=1,)\n df_test = df_test.drop('index',axis=1)\n df_test.columns = ['player','wkts','wkts_baseline','wkts_exp']\n\n df_by_player = df_test.groupby('player').sum()\n\n print('Explained Variance (LR model): ' + str(explained_variance_score(df_by_player.wkts,df_by_player.wkts_exp)))\n print('Explained Variance (Baseline): ' + str(explained_variance_score(df_by_player.wkts,df_by_player.wkts_baseline)))\n print('----')\n print('Mean Squared Error (LR model): ' + str(mean_squared_error(df_by_player.wkts,df_by_player.wkts_exp)))\n print('Mean Squared Error (Baseline): ' + str(mean_squared_error(df_by_player.wkts,df_by_player.wkts_baseline)))\n print('----')\n print(' ')\n\n\n\n\ndef fit_rf_model(df, X_train, y_train, X_test, y_test, mask_test):\n \"\"\"\n Runs a grid-search to find the best random forest model for the passed X_train and y_train,\n predicts target for the passed X_test using the best grid-searched model,\n displays the winning model's parameters,\n displays the feature importances,\n groups data by player to find expected number of wickets for the entire season,\n and finally calculates explained variance and MSE.\n \"\"\"\n print (\"**** RANDOM FOREST Grid Search ****\")\n random_forest_grid = {'max_depth': [3, None],\n 'max_features': ['sqrt', 'log2', round(X_train.shape[1]/3), None],\n 'min_samples_split': [2, 4],\n 'min_samples_leaf': [1, 2, 4],\n 'bootstrap': [True, False],\n 'n_estimators': [100,300,500],\n 'random_state': [10]}\n\n rf_gridsearch = GridSearchCV(RandomForestRegressor(),\n random_forest_grid,\n n_jobs=-1,\n verbose=True,\n scoring='neg_mean_squared_error')\n rf_gridsearch.fit(X_train, y_train)\n print(\"Best Parameters:\", rf_gridsearch.best_params_)\n print(' ')\n\n best_rf_model = rf_gridsearch.best_estimator_\n\n feature_importance = {}\n for label, importance in zip(X_train.columns, best_rf_model.feature_importances_):\n feature_importance[label] = importance\n print(\"Sorted Feature Importance:\")\n sorted_feature_imp = sorted(feature_importance.items(), key=lambda x: (-x[1]))\n for e in sorted_feature_imp:\n print(e)\n\n y_pred_test = best_rf_model.predict(X_test)\n df_test = pd.concat([df[mask_test][['player','wkts','year1_wkts_pm']].reset_index(),\n pd.DataFrame(y_pred_test).reset_index()],axis=1,)\n df_test = df_test.drop('index',axis=1)\n df_test.columns = ['player','wkts','wkts_baseline','wkts_exp']\n\n df_by_player = df_test.groupby('player').sum()\n\n print(' ')\n print('Explained Variance (RF model): ' + str(explained_variance_score(df_by_player.wkts,df_by_player.wkts_exp)))\n print('Explained Variance (Baseline): ' + str(explained_variance_score(df_by_player.wkts,df_by_player.wkts_baseline)))\n print('----')\n print('Mean Squared Error (RF model): ' + str(mean_squared_error(df_by_player.wkts,df_by_player.wkts_exp)))\n print('Mean Squared Error (Baseline): ' + str(mean_squared_error(df_by_player.wkts,df_by_player.wkts_baseline)))\n print('----')\n print(' ')\n\n\n\n\ndef fitting_lr_and_rf(file, test_yr, fit_lr, fit_rf):\n \"\"\"\n Loads the passed file into pandas dataframe,\n defines masks for training and test data for the passed test_yr,\n creates training and test data based on those masks,\n defines four different sets of features,\n and finally for each set of features, calls fit_lr_model and fit_rf_model.\n\n Parameters\n ----------\n file: String\n Input file name.\n test_yr: Numeric\n Year for which test will be run. Training will be done using last 6 years' data.\n fit_lr: Boolean\n Whether to fit the linear regression model.\n fit_rf: Boolean\n Whether to fit the grid-searched random forest model.\n \"\"\"\n df = pd.read_csv(file)\n\n mask_test = (df.year == test_yr)\n mask_train = (df.year >= test_yr-6) & (df.year <= test_yr-1)\n\n target = 'wkts'\n\n features_full = ['year1_mtchs_pld', 'year2_mtchs_pld', 'year3_mtchs_pld', 'year4_mtchs_pld', 'year5_mtchs_pld',\n 'year1_wkts_pm', 'year2_wkts_pm', 'year3_wkts_pm','year4_wkts_pm', 'year5_wkts_pm',\n 'bowler_agnst_oppo', 'oppo_agnst_bowl_typ', 'bowl_home_adv', 'ground_bowl_typ']\n features_small = ['year1_wkts_pm', 'year2_wkts_pm', 'year3_wkts_pm', 'year4_wkts_pm', 'year5_wkts_pm',\n 'bowler_agnst_oppo', 'oppo_agnst_bowl_typ', 'bowl_home_adv', 'ground_bowl_typ']\n features_smaller = ['year1_wkts_pm', 'year2_wkts_pm', 'year3_wkts_pm', 'year4_wkts_pm', 'year5_wkts_pm',\n 'bowl_home_adv', 'ground_bowl_typ']\n features_smallest = ['year1_wkts_pm', 'year2_wkts_pm', 'year3_wkts_pm', 'year4_wkts_pm', 'year5_wkts_pm']\n\n print(\"*********************************************\")\n print(\"**** RUNNING MODELS FOR FULL FEATURE SET ****\")\n print(\"*********************************************\")\n\n features = features_full.copy()\n\n X_train = df[mask_train][features]\n y_train = df[mask_train][target]\n X_test = df[mask_test][features]\n y_test = df[mask_test][target]\n\n if fit_lr:\n fit_lr_model(df, X_train, y_train, X_test, y_test, mask_test)\n\n if fit_rf:\n fit_rf_model(df, X_train, y_train, X_test, y_test, mask_test)\n\n\n print(\"**********************************************\")\n print(\"**** RUNNING MODELS FOR SMALL FEATURE SET ****\")\n print(\"**********************************************\")\n\n features = features_small.copy()\n\n X_train = df[mask_train][features]\n y_train = df[mask_train][target]\n X_test = df[mask_test][features]\n y_test = df[mask_test][target]\n\n if fit_lr:\n fit_lr_model(df, X_train, y_train, X_test, y_test, mask_test)\n\n if fit_rf:\n fit_rf_model(df, X_train, y_train, X_test, y_test, mask_test)\n\n\n print(\"************************************************\")\n print(\"**** RUNNING MODELS FOR SMALLER FEATURE SET ****\")\n print(\"************************************************\")\n\n features = features_smaller.copy()\n\n X_train = df[mask_train][features]\n y_train = df[mask_train][target]\n X_test = df[mask_test][features]\n y_test = df[mask_test][target]\n\n if fit_lr:\n fit_lr_model(df, X_train, y_train, X_test, y_test, mask_test)\n\n if fit_rf:\n fit_rf_model(df, X_train, y_train, X_test, y_test, mask_test)\n\n\n print(\"*************************************************\")\n print(\"**** RUNNING MODELS FOR SMALLEST FEATURE SET ****\")\n print(\"*************************************************\")\n\n features = features_smallest.copy()\n\n X_train = df[mask_train][features]\n y_train = df[mask_train][target]\n X_test = df[mask_test][features]\n y_test = df[mask_test][target]\n\n if fit_lr:\n fit_lr_model(df, X_train, y_train, X_test, y_test, mask_test)\n\n if fit_rf:\n fit_rf_model(df, X_train, y_train, X_test, y_test, mask_test)\n\n\n\n\nif __name__ == \"__main__\":\n input_file = '../../data/bowling_data_enhanced.csv'\n for yr in range(2011,2017):\n fitting_lr_and_rf(input_file, test_yr=yr, fit_lr=True, fit_rf=True)\n" }, { "alpha_fraction": 0.7787054181098938, "alphanum_fraction": 0.792620062828064, "avg_line_length": 123.37179565429688, "blob_id": "c1f4af6732b45230c650ec8a265d46f0bdb34f63", "content_id": "918599fd60baf4e15a1952a4af75eb5b14e41dd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9708, "license_type": "no_license", "max_line_length": 920, "num_lines": 78, "path": "/README.md", "repo_name": "prantik-ghosh/bowling_performance_predictor_in_test_cricket", "src_encoding": "UTF-8", "text": "# Bowling Performance Prediction in Test Cricket\n\n\n## __Abstract__:\nOn the game of cricket, Sir Neville Cardus once famously said, \"We remember not the scores and the results in after years; it is the men who remain in our minds, in our imagination.\" That may be true, but ultimately those scores and results definitely help make those men memorable. Here's another one of his famous quotes, \"In cricket, as in no other game, a great master may well go back to the pavilion scoreless.... In no other game does the law of averages get to work so potently, so mysteriously.\" Anybody who watches cricket know how true these words are. The unpredictable nature of the game does make it notoriously difficult to predict the result of a game and gauge an individual player's performance.\n\nIn this project, I have tried to achieve exactly that for a bowler. Bowlers often get less accolades than their batting counterparts, but they are the ones win matches for their team especially in the longer version of the game, because a team cannot win a test match unless its bowlers are capable of capturing twenty opposition wickets. In this study, I have tried to predict the number of test wickets a bowler will take in the upcoming season.\n\n\n## __Technology__:\n* Python\n - Pandas and Numpy for data processing/cleaning\n - SciKit Learn and Statsmodels for model fitting (Linear Regression, Random Forest Regressor, and Gradient Boost Regressor)\n - matplotlib for plotting/visualization\n\n* Database\n - PostgreSQL for table creation, data loading, and querying\n - PL/pgSQL for data manipulation/feature engineering\n\n\n## __Data Retrieval__:\nThe data (bowler's performance by match) was pulled from popular ESPN Cricinfo website's STATSGURU property (URL: http://stats.espncricinfo.com/ci/engine/stats/index.html?class=1;filter=advanced;type=bowling). Unfortunately, it didn't have all the features like bowler type (pace or spin), bowling arm (right or left) and home/away information available in the output. However, the query form allowed to query on those parameters, which helped to retrieve those features in an indirect fashion.\nFollowing filters were applied before retrieving the data:\n1. Data was retrieved for years 2000 to 2017 only. As the game changes pretty rapidly, I believed older data may not be quite relevant.\n2. A bowler's performance was counted only for those matches where he bowled at least 60 deliveries, which is equivalent to 10 overs.\n\n\n## __Data Cleaning__:\nAt the next step, data files were loaded into pandas dataframes, pulled into a single dataframe and then the following cleaning were performed (1_initial_data_load_and_manipulation.ipynb):\n1. Player names were extracted.\n2. Players' countries were extracted and standardized.\n3. Opposition country name cleaned.\n4. Year extracted from the start date.\n5. Redundant columns were dropped.\n6. Filtered to keep only major test playing nations with respect to number of matches played.\n7. Data from the modified dataframe were dumped into a csv file to be loaded into SQL database for further manipulation and feature extraction.\n\n\n## __Feature Engineering__:\nNext, in order to perform feature engineering, a table was created in postgresql database and data were loaded from the csv file (psql_create_and_load_sql_table.sql). Several processes were run to update the table. Following features were extracted:\n1. For the last 5 years, how many test matches this player has played and how many wickets per match this player has taken each year (psql_func1_update_bowler_stat.sql)? These features are supposed to measure the bowler's past performance.\n2. What is the ratio of average wickets taken per match by this player against this opposition vs the same against all oppositions (psql_func2_update_bowler_oppo_stat.sql)? This feature is supposed to measure if this bowler does better or worse on average against this particular opposition.\n3. A measure between 0 and 1 to indicate how well this player performs at home vs how well he does at away venues on average (psql_func3_update_bowler_home_adv_stat.sql).\n4. What is the ratio of average wickets taken per match by bowler of this type (pace/spin and right/left arm) against this opponent vs bowler of all types against this opponent in the \"last\" 5 years(psql_func4_update_oppo_bowltyp_stat.sql)? This feature is supposed to provide a measure how this particular opposition fared against this particular type of bowling.\n5. What is the ratio of average wickets taken per match by bowler of this type (pace/spin) in this ground vs average wickets taken per match by bowler of all types in this ground (psql_func5_update_ground_bowltyp_stat.sql)? This feature is supposed to measure how much this particular ground supports pace or spin bowling.\nFinally, created a dump of the engineered data in form of a csv file.\n\n*__Note__: Since I needed data from the last 5 years to calculate the engineered features, out of the 2000-2017 data I started with, I could only get these features for 2005-2017 data.*\n\n\n## __Cross-validation Strategy__:\nOut of the data I had from 2005 to 2017, the idea was to train and validate the models on 2000 to 2016 data, and then perform the final testing on 2017 data. However, because of the time series type nature of the data, a standard cross validation wouldn't make sense here. Hence, I decided to work on a rolling window of 6 years data to train a model and use it to predict the following year's performance. So, I started with the years 2005 to 2010 to train a model and validated with 2011 data. Next, I would use 2006-2011 to train the model and validate on 2012. Going forward like this, the last training set would be 2010-2015 data and the corresponding validation data would be 2016. After running the model for all these different training and validation sets, I would calculate average score to compare a model with another. The scores I used for this purpose were MSE (Mean Squared Error) and Explained Variance.\n\n\n## __Target (Grouping by Player)__:\nThe idea here was that the model would forecast expected number of wickets for each player for each match in the upcoming season and then we would group that data by players to forecast the expected total number of wickets to be captured by a player in the entire season. Thus, for each bowler, the target would be the number of wickets taken in the entire season, not in each match.\n\n\n## __Setting the Baseline__:\nLast year’s performance is generally a very good indicator of a player’s current year’s performance. Average number of wickets taken per match is a straightforward measure of performance. Hence, before jumping into model fitting, I set the baseline for each player to be the average number of wickets taken per match in the previous year multiplied with the number of matches in the current year.\n\n\n## __Model fitting and feature selection__:\nInitially, I tried Linear Regression and a Grid-Searched Random Forest (run_lr_and_rf_for_various_feature_sets.py). Unfortunately, not one model was consistently superior. Next, I tried a Grid-Searched Gradient Boosting model (run_gb_for_various_feature_sets). After comparing all three models, still none of the models was consistently superior; however, Gradient Boosting came out on top more often than others.\n\nAs far as features are concerned, I tried different sets of features and also compared feature importance information returned by the various models. After comparing the features for various models, it was evident that none of the features involving number of matches played in the last 5 years was significant. Also, the feature involving the bowler's relative performance against this particular opposition as well as the feature related to this opposition's relative performance against this particular type of bowling were not significant either. That leaves us with the smaller feature set involving the wickets per match captured by this bowler in each of the last 5 years, the home/away factor, and how the particular ground (venue) supports the bowing type (pace or spin).\n\nTill now, to choose the optimum model, I was solely using test scores. Next, I took the winning GB model and calculated training score (run_models_for_years.py). I found that across all the traning/validation sets, the model's traning score was always much higher than the test score - an average explained variance of 95% on the training data vs an average explained variance of 78% on the validation data. Normally, this would mean the model was overfitting. So, I tried to underfit the GB model by tuning its various hyperparameters. But none of those variants could better the performance of the chosen model. In each case both the training and test score went down. The conclusion to be drawn from here is that, because of the time series type nature of the problem, the training and the validation data are not identically distributed and so there will always be a significant gap between the two scores.\n\n\n## __Final model run with 2017 test data__:\nRan the optimized GB model for the final test data to predict bowlers' performance in the year 2017 (final_model_run_on_test_data.py). Got an explained variance score of 81% against the baseline score of 66% and a MSE (Mean Squared Error) of 30.2 against a baseline MSE of 59.9.\n\n\n## __Future Considerations__:\n- Consider bowler subtype in the fray. For instance, what kind of spinner - a leg-break, an off-break, a left-arm-orthodox or a chinaman bowler?\n- Consider weather data and how it would interact with bowler type. For instance, cloudy heavey conditions support swing bowlers.\n- Perhaps consider domestic performance for those bowlers who are new to test cricket.\n\n" }, { "alpha_fraction": 0.7298488616943359, "alphanum_fraction": 0.743073046207428, "avg_line_length": 23.045454025268555, "blob_id": "96f05f7eccef82ba0fb188fb2dac326effa2e0df", "content_id": "a6149d187ec74046e1d35feecba168b579d5ff0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1588, "license_type": "no_license", "max_line_length": 108, "num_lines": 66, "path": "/src/psql_scripts/psql_create_and_load_sql_table.sql", "repo_name": "prantik-ghosh/bowling_performance_predictor_in_test_cricket", "src_encoding": "UTF-8", "text": "DROP TABLE IF EXISTS\n bowling_data;\n\nCREATE TABLE bowling_data(\n overs double precision\n ,mdns int\n ,runs int\n ,wkts int\n ,econ double precision\n ,ave double precision\n ,strike_rate double precision\n ,opposition varchar(30)\n ,ground varchar(50)\n ,home_away int\n ,bowling_arm int\n ,pace_spin int\n ,player varchar(50)\n ,country varchar(30)\n ,year int\n);\n\n\nCOPY\n bowling_data\nFROM\n '/home/prantik/galvanize/dsi-capstone-bowler-performance/data/bowling_data_raw_idx_n_header_deleted.csv'\nWITH\n (FORMAT csv);\n\n\nALTER TABLE bowling_data\n ADD COLUMN balls int\n ,ADD COLUMN year1_mtchs_pld int\n ,ADD COLUMN year2_mtchs_pld int\n ,ADD COLUMN year3_mtchs_pld int\n ,ADD COLUMN year4_mtchs_pld int\n ,ADD COLUMN year5_mtchs_pld int\n ,ADD COLUMN year1_wkts_pm double precision\n ,ADD COLUMN year2_wkts_pm double precision\n ,ADD COLUMN year3_wkts_pm double precision\n ,ADD COLUMN year4_wkts_pm double precision\n ,ADD COLUMN year5_wkts_pm double precision\n ,ADD COLUMN bowler_agnst_oppo double precision\n ,ADD COLUMN oppo_agnst_bowl_typ double precision\n ,ADD COLUMN bowl_home_adv double precision\n ,ADD COLUMN ground_bowl_typ double precision\n;\n\n\nUPDATE\n bowling_data\nSET\n balls = round(overs)*6 + (overs-round(overs))*10\n;\n\n\n/* All of the above are executed at the start before running the functions to create/manipulate the stats */\n/* The below should be run at the end after the stat creation/manipulation is over */\n\n\nCOPY\n bowling_data\nTO\n '/home/prantik/galvanize/dsi-capstone-bowler-performance/data/bowling_data_enhanced.csv'\nWITH\n (FORMAT CSV, HEADER);\n\n" }, { "alpha_fraction": 0.5685245990753174, "alphanum_fraction": 0.5804917812347412, "avg_line_length": 40.78082275390625, "blob_id": "f49123fa1f8f168e61c30ceada5ad3f5952d211a", "content_id": "0cad420fce6eee1141d1ce2e979d47d34681490c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6100, "license_type": "no_license", "max_line_length": 114, "num_lines": 146, "path": "/src/python_scripts/final_model_run_on_test_data.py", "repo_name": "prantik-ghosh/bowling_performance_predictor_in_test_cricket", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.metrics import explained_variance_score\nfrom sklearn.metrics import mean_squared_error\n\n\n\n\ndef final_model_run(file, show_feat_imp, show_mse, show_graph1, show_graph2, show_graph3):\n \"\"\"\n Loads data from the passed file into pandas dataframe,\n defines masks for training and test data for the final test year 2017,\n creates training and test data based on those masks,\n trains the fixed model on the traning data for the fixed set of features,\n predicts on the test data,\n computes scores explained variance and MSE on training and test data,\n computes baseline explained variance and MSE\n and finally displays some visuals.\n\n Parameters\n ----------\n file: String\n Input file name.\n show_feat_imp: Boolean\n Whether to display feature importances and its bar graph.\n show_mse: Boolean\n Whether to calculate and display train and test MSEs.\n show_graph1: Boolean\n Whether to display the scatter plot of actual and expected #wickets by player.\n show_graph2: Boolean\n Whether to display the line plot of actual and expected #wickets by player.\n show_graph3: Boolean\n Whether to display the scatter plot of actual #wickets vs the residuals.\n \"\"\"\n model = GradientBoostingRegressor(learning_rate=0.01, n_estimators=300, max_depth=3, max_features=2,\n subsample=0.5, verbose=0, random_state=10)\n features = ['year1_wkts_pm', 'year2_wkts_pm', 'year3_wkts_pm', 'year4_wkts_pm', 'year5_wkts_pm',\n 'bowl_home_adv', 'ground_bowl_typ']\n target = 'wkts'\n\n print('++++++++++ MODEL ++++++++++')\n print(model)\n print('++++++++++ MODEL ++++++++++')\n print('')\n print('++++++++ FEATURES +++++++++')\n print(features)\n print('++++++++ FEATURES +++++++++')\n\n df = pd.read_csv(file)\n\n test_yr = 2017\n\n print('')\n\n mask_test = (df.year == test_yr)\n mask_train = (df.year >= test_yr-6) & (df.year <= test_yr-1)\n\n X_train = df[mask_train][features]\n y_train = df[mask_train][target]\n X_test = df[mask_test][features]\n y_test = df[mask_test][target]\n\n model.fit(X_train, y_train)\n\n if (show_feat_imp):\n print('')\n print('Feature Importance:')\n feature_importance = {}\n for label, importance in zip(X_train.columns, model.feature_importances_):\n feature_importance[label] = importance\n print(\"Sorted Feature Importance:\")\n sorted_feature_imp = sorted(feature_importance.items(), key=lambda x: (-x[1]))\n for e in sorted_feature_imp:\n print(e)\n\n importances = model.feature_importances_\n indices = np.argsort(importances)[::-1]\n feature_names = list(X_train.columns[indices])\n print (importances[indices])\n plt.figure(figsize=(20,5))\n plt.title(\"Feature Importances\")\n plt.bar(range(7), importances[indices], color=\"#334079\", align=\"center\")\n # #664079\n plt.xticks(range(7), feature_names,rotation='45')\n plt.xlim([-1, 7])\n\n y_pred_train = model.predict(X_train)\n y_pred_test = model.predict(X_test)\n\n df_train = pd.concat([df[mask_train][['player','wkts','year1_wkts_pm']].reset_index(),\n pd.DataFrame(y_pred_train).reset_index()],axis=1,)\n df_train = df_train.drop('index',axis=1)\n df_train.columns = ['player','wkts','wkts_baseline','wkts_exp']\n df_train_by_player = df_train.groupby('player').sum()\n\n df_test = pd.concat([df[mask_test][['player','wkts','year1_wkts_pm']].reset_index(),\n pd.DataFrame(y_pred_test).reset_index()],axis=1,)\n df_test = df_test.drop('index',axis=1)\n df_test.columns = ['player','wkts','wkts_baseline','wkts_exp']\n df_test_by_player = df_test.groupby('player').sum()\n\n print(' ')\n print('Explained Variance (Train): ' + str(explained_variance_score(df_train_by_player.wkts,\n df_train_by_player.wkts_exp)))\n print('Explained Variance (Test): ' + str(explained_variance_score(df_test_by_player.wkts,\n df_test_by_player.wkts_exp)))\n print('Explained Variance (Test-Baseline): ' + str(explained_variance_score(df_test_by_player.wkts,\n df_test_by_player.wkts_baseline)))\n print('----')\n\n if (show_mse):\n print('Mean Squared Error (Train): ' + str(mean_squared_error(df_train_by_player.wkts,\n df_train_by_player.wkts_exp)))\n print('Mean Squared Error (Test): ' + str(mean_squared_error(df_test_by_player.wkts,\n df_test_by_player.wkts_exp)))\n print('Mean Squared Error (Test-Baseline): ' + str(mean_squared_error(df_test_by_player.wkts,\n df_test_by_player.wkts_baseline)))\n print('----')\n\n if (show_graph1):\n df_test_by_player.plot(kind='scatter',x='wkts',y='wkts_exp',figsize=(7,5))\n plt.title(\"Actual vs Expected #Wkts by Player\")\n plt.show()\n\n if (show_graph2):\n df_test_by_player[['wkts','wkts_exp']].plot(figsize=(12,5))\n plt.title(\"Actual and Expected #Wkts by Player\")\n plt.show()\n\n if (show_graph3):\n df_test_by_player['residual'] = df_test_by_player.wkts - df_test_by_player.wkts_exp\n df_sorted = df_test_by_player.sort_values(['wkts','residual'])\n df_sorted.plot(kind='scatter',x='wkts',y='residual',figsize=(8,5),c='m')\n plt.title(\"Actual #Wkts by Player vs Residual\")\n plt.show()\n\n print(' ')\n\n\n\n\nif __name__ == \"__main__\":\n input_file = '../../data/bowling_data_enhanced.csv'\n final_model_run(input_file, True, True, True, True, True)\n" }, { "alpha_fraction": 0.562572717666626, "alphanum_fraction": 0.5737078189849854, "avg_line_length": 39.11333465576172, "blob_id": "92654d14dd61080963795ab76d6572462d9bcd20", "content_id": "b909c0ca31e46853593eef4d4feb8dce5ba747a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6017, "license_type": "no_license", "max_line_length": 122, "num_lines": 150, "path": "/src/python_scripts/run_gb_for_various_feature_sets.py", "repo_name": "prantik-ghosh/bowling_performance_predictor_in_test_cricket", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import explained_variance_score\nfrom sklearn.metrics import mean_squared_error\n\n\n\n\ndef fit_gb_model(df, X_train, y_train, X_test, y_test, mask_test):\n \"\"\"\n Runs a grid-search to find the best gradient boost model for the passed X_train and y_train,\n predicts target for the passed X_test using the best grid-searched model,\n displays the winning model's parameters,\n displays the feature importances,\n groups data by player to find expected number of wickets for the entire season,\n and finally calculates explained variance and MSE.\n \"\"\"\n print (\"**** GRADIENT BOOSTING Grid Search ****\")\n gradient_boosting_grid = {'max_depth': [3, None],\n 'max_features': ['sqrt', 'log2', round(X_train.shape[1]/3), None],\n 'n_estimators': [100,300,500],\n 'learning_rate': [0.1,0.05,0.01],\n 'subsample': [0.5,1.0],\n 'random_state': [10]}\n\n gb_gridsearch = GridSearchCV(GradientBoostingRegressor(),\n gradient_boosting_grid,\n verbose=1,\n scoring='neg_mean_squared_error')\n gb_gridsearch.fit(X_train, y_train)\n print(\"Best Parameters:\", gb_gridsearch.best_params_)\n print(' ')\n\n best_gb_model = gb_gridsearch.best_estimator_\n\n feature_importance = {}\n for label, importance in zip(X_train.columns, best_gb_model.feature_importances_):\n feature_importance[label] = importance\n print(\"Sorted Feature Importance:\")\n sorted_feature_imp = sorted(feature_importance.items(), key=lambda x: (-x[1]))\n for e in sorted_feature_imp:\n print(e)\n\n y_pred_test = best_gb_model.predict(X_test)\n df_test = pd.concat([df[mask_test][['player','wkts','year1_wkts_pm']].reset_index(),\n pd.DataFrame(y_pred_test).reset_index()],axis=1,)\n df_test = df_test.drop('index',axis=1)\n df_test.columns = ['player','wkts','wkts_baseline','wkts_exp']\n\n df_by_player = df_test.groupby('player').sum()\n\n print(' ')\n print('Explained Variance (GB model): ' + str(explained_variance_score(df_by_player.wkts,df_by_player.wkts_exp)))\n print('Explained Variance (Baseline): ' + str(explained_variance_score(df_by_player.wkts,df_by_player.wkts_baseline)))\n print('----')\n print('Mean Squared Error (GB model): ' + str(mean_squared_error(df_by_player.wkts,df_by_player.wkts_exp)))\n print('Mean Squared Error (Baseline): ' + str(mean_squared_error(df_by_player.wkts,df_by_player.wkts_baseline)))\n print('----')\n print(' ')\n\n\n\n\ndef fitting_gb_models(file, test_yr):\n \"\"\"\n Loads the passed file into pandas dataframe,\n defines masks for training and test data for the passed test_yr,\n creates training and test data based on those masks,\n defines four different sets of features,\n and finally for each set of features, calls fit_gb_model.\n \"\"\"\n df = pd.read_csv(file)\n\n mask_test = (df.year == test_yr)\n mask_train = (df.year >= test_yr-6) & (df.year <= test_yr-1)\n\n target = 'wkts'\n\n features_full = ['year1_mtchs_pld', 'year2_mtchs_pld', 'year3_mtchs_pld', 'year4_mtchs_pld', 'year5_mtchs_pld',\n 'year1_wkts_pm', 'year2_wkts_pm', 'year3_wkts_pm','year4_wkts_pm', 'year5_wkts_pm',\n 'bowler_agnst_oppo', 'oppo_agnst_bowl_typ', 'bowl_home_adv', 'ground_bowl_typ']\n features_small = ['year1_wkts_pm', 'year2_wkts_pm', 'year3_wkts_pm', 'year4_wkts_pm', 'year5_wkts_pm',\n 'bowler_agnst_oppo', 'oppo_agnst_bowl_typ', 'bowl_home_adv', 'ground_bowl_typ']\n features_smaller = ['year1_wkts_pm', 'year2_wkts_pm', 'year3_wkts_pm', 'year4_wkts_pm', 'year5_wkts_pm',\n 'bowl_home_adv', 'ground_bowl_typ']\n features_smallest = ['year1_wkts_pm', 'year2_wkts_pm', 'year3_wkts_pm', 'year4_wkts_pm', 'year5_wkts_pm']\n\n print(\"*********************************************\")\n print(\"**** RUNNING MODELS FOR FULL FEATURE SET ****\")\n print(\"*********************************************\")\n\n features = features_full.copy()\n\n X_train = df[mask_train][features]\n y_train = df[mask_train][target]\n X_test = df[mask_test][features]\n y_test = df[mask_test][target]\n\n fit_gb_model(df, X_train, y_train, X_test, y_test, mask_test)\n\n\n print(\"**********************************************\")\n print(\"**** RUNNING MODELS FOR SMALL FEATURE SET ****\")\n print(\"**********************************************\")\n\n features = features_small.copy()\n\n X_train = df[mask_train][features]\n y_train = df[mask_train][target]\n X_test = df[mask_test][features]\n y_test = df[mask_test][target]\n\n fit_gb_model(df, X_train, y_train, X_test, y_test, mask_test)\n\n\n print(\"************************************************\")\n print(\"**** RUNNING MODELS FOR SMALLER FEATURE SET ****\")\n print(\"************************************************\")\n\n features = features_smaller.copy()\n\n X_train = df[mask_train][features]\n y_train = df[mask_train][target]\n X_test = df[mask_test][features]\n y_test = df[mask_test][target]\n\n fit_gb_model(df, X_train, y_train, X_test, y_test, mask_test)\n\n\n print(\"*************************************************\")\n print(\"**** RUNNING MODELS FOR SMALLEST FEATURE SET ****\")\n print(\"*************************************************\")\n\n features = features_smallest.copy()\n\n X_train = df[mask_train][features]\n y_train = df[mask_train][target]\n X_test = df[mask_test][features]\n y_test = df[mask_test][target]\n\n fit_gb_model(df, X_train, y_train, X_test, y_test, mask_test)\n\n\n\n\nif __name__ == \"__main__\":\n input_file = '../../data/bowling_data_enhanced.csv'\n for yr in range(2011,2017):\n fitting_gb_models(input_file, test_yr=yr)\n" } ]
5
keypunch416/MMA8452Q
https://github.com/keypunch416/MMA8452Q
37a5ce6a1f0a63a6f1264899450780345e495e8c
eac1e4a5aa43f5237db86afd083bcf43adcf4470
8d2cc02d064e6fd3878b592ac933211c8d9f816c
refs/heads/master
2021-06-07T20:37:48.913863
2016-11-14T11:25:02
2016-11-14T11:25:02
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5942028760910034, "alphanum_fraction": 0.6489533185958862, "avg_line_length": 23.594058990478516, "blob_id": "df3c8c02ff6a26e2e3b335674e069d7a78313396", "content_id": "3562062553462c42763fa3e26c064532a17475c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2484, "license_type": "no_license", "max_line_length": 109, "num_lines": 101, "path": "/Particle/MMA8452Q.ino", "repo_name": "keypunch416/MMA8452Q", "src_encoding": "UTF-8", "text": "// Distributed with a free-will license.\n// Use it any way you want, profit or free, provided it fits in the licenses of its associated works.\n// MMA8452Q\n// This code is designed to work with the MMA8452Q_I2CS I2C Mini Module available from ControlEverything.com.\n// https://www.controleverything.com/content/Accelorometer?sku=MMA8452Q_I2CS#tabs-0-product_tabset-2\n\n#include <application.h>\n#include <spark_wiring_i2c.h>\n\n// MMA8452Q I2C address is 0x1C(28)\n#define Addr 0x1C\n\nint xAccl = 0, yAccl = 0, zAccl = 0;\nvoid setup()\n{\n // Set variable\n Particle.variable(\"i2cdevice\", \"MMA8452Q\");\n Particle.variable(\"xAccl\", xAccl);\n Particle.variable(\"yAccl\", yAccl);\n Particle.variable(\"zAccl\", zAccl);\n \n // Initialise I2C communication as MASTER\n Wire.begin();\n // Initialise Serial Communication, set baud rate = 9600\n Serial.begin(9600);\n\n // Start I2C Transmission\n Wire.beginTransmission(Addr);\n // Select control register\n Wire.write(0x2A);\n // StandBy mode\n Wire.write(0x00);\n // Stop I2C Transmission\n Wire.endTransmission();\n\n // Start I2C Transmission\n Wire.beginTransmission(Addr);\n // Select control register\n Wire.write(0x2A);\n // Active mode\n Wire.write(0x01);\n // Stop I2C Transmission\n Wire.endTransmission();\n\n // Start I2C Transmission\n Wire.beginTransmission(Addr);\n // Select configuration register\n Wire.write(0x0E);\n // Set range to +/- 2g\n Wire.write(0x00);\n // Stop I2C Transmission\n Wire.endTransmission();\n delay(300);\n}\n\nvoid loop()\n{\n unsigned int data[7];\n\n // Request 7 bytes of data\n Wire.requestFrom(Addr, 7);\n \n // Read 7 bytes of data\n // staus, xAccl lsb, xAccl msb, yAccl lsb, yAccl msb, zAccl lsb, zAccl msb\n if(Wire.available() == 7) \n {\n data[0] = Wire.read();\n data[1] = Wire.read();\n data[2] = Wire.read();\n data[3] = Wire.read();\n data[4] = Wire.read();\n data[5] = Wire.read();\n data[6] = Wire.read();\n }\n delay(300); \n \n // Convert the data to 12-bits\n xAccl = ((data[1] * 256) + data[2]) / 16;\n if (xAccl > 2047)\n {\n xAccl -= 4096;\n }\n \n yAccl = ((data[3] * 256) + data[4]) / 16;\n if (yAccl > 2047)\n {\n yAccl -= 4096;\n }\n \n zAccl = ((data[5] * 256) + data[6]) / 16;\n if (zAccl > 2047)\n {\n zAccl -= 4096;\n }\n\n // Output data to dashboard\n Particle.publish(\"Acceleration in X-Axis : \", String(xAccl));\n Particle.publish(\"Acceleration in Y-Axis : \", String(yAccl));\n Particle.publish(\"Acceleration in Z-Axis : \", String(zAccl));\n delay(500); \n}\n" }, { "alpha_fraction": 0.5745111107826233, "alphanum_fraction": 0.6817262172698975, "avg_line_length": 28.26530647277832, "blob_id": "92136ced4b5f2fa916a8f86873a2dac031b88686", "content_id": "a11508d9eef5b36a982985eaef892429e49660be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1483, "license_type": "no_license", "max_line_length": 108, "num_lines": 49, "path": "/Python/MMA8452Q.py", "repo_name": "keypunch416/MMA8452Q", "src_encoding": "UTF-8", "text": "# Distributed with a free-will license.\r\n# Use it any way you want, profit or free, provided it fits in the licenses of its associated works.\r\n# MMA8452Q\r\n# This code is designed to work with the MMA8452Q_I2CS I2C Mini Module available from ControlEverything.com.\r\n# https://www.controleverything.com/content/Accelorometer?sku=MMA8452Q_I2CS#tabs-0-product_tabset-2\r\n\r\nimport smbus\r\nimport time\r\n\r\n# Get I2C bus\r\nbus = smbus.SMBus(1)\r\n\r\n# MMA8452Q address, 0x1C(28)\r\n# Select Control register, 0x2A(42)\r\n#\t\t0x00(00)\tStandBy mode\r\nbus.write_byte_data(0x1C, 0x2A, 0x00)\r\n# MMA8452Q address, 0x1C(28)\r\n# Select Control register, 0x2A(42)\r\n#\t\t0x01(01)\tActive mode\r\nbus.write_byte_data(0x1C, 0x2A, 0x01)\r\n# MMA8452Q address, 0x1C(28)\r\n# Select Configuration register, 0x0E(14)\r\n#\t\t0x00(00)\tSet range to +/- 2g\r\nbus.write_byte_data(0x1C, 0x0E, 0x00)\r\n\r\ntime.sleep(0.5)\r\n\r\n# MMA8452Q address, 0x1C(28)\r\n# Read data back from 0x00(0), 7 bytes\r\n# Status register, X-Axis MSB, X-Axis LSB, Y-Axis MSB, Y-Axis LSB, Z-Axis MSB, Z-Axis LSB\r\ndata = bus.read_i2c_block_data(0x1C, 0x00, 7)\r\n\r\n# Convert the data\r\nxAccl = (data[1] * 256 + data[2]) / 16\r\nif xAccl > 2047 :\r\n\txAccl -= 4096\r\n\r\nyAccl = (data[3] * 256 + data[4]) / 16\r\nif yAccl > 2047 :\r\n\tyAccl -= 4096\r\n\r\nzAccl = (data[5] * 256 + data[6]) / 16\r\nif zAccl > 2047 :\r\n\tzAccl -= 4096\r\n\r\n# Output data to screen\r\nprint \"Acceleration in X-Axis : %d\" %xAccl\r\nprint \"Acceleration in Y-Axis : %d\" %yAccl\r\nprint \"Acceleration in Z-Axis : %d\" %zAccl\r\n" } ]
2
mochyopiannas/Visi_Komputer
https://github.com/mochyopiannas/Visi_Komputer
936b878d7a0e6e677952de1818f477a4f83d2d1a
f885b5fe2e2ce1ff9904406ebcf177e03bf13e42
341d95b229423912dcaf46388c93feb0c89cf3c0
refs/heads/main
2023-04-04T02:18:45.208491
2021-04-11T08:04:11
2021-04-11T08:04:11
356,804,674
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.43866172432899475, "alphanum_fraction": 0.48327139019966125, "avg_line_length": 42.33333206176758, "blob_id": "e8ae9ab9114c18debcdc71858820a1bfc142a277", "content_id": "c3979e2e77242ed9e0f856e17aa0fd67478304f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 269, "license_type": "no_license", "max_line_length": 64, "num_lines": 6, "path": "/Hello.py", "repo_name": "mochyopiannas/Visi_Komputer", "src_encoding": "UTF-8", "text": "print (\"--------Biodata--------\")\r\nprint (\"=======================\")\r\nprint (\"Nama Lengkap : Moch Yopi Annas\")\r\nprint (\"NIM : B34180028\")\r\nprint (\"Kelas : Teknik Informatika 2018 A\")\r\nprint (\"Kampus : Universitas Nahdlatul Ulama Sidoarjo\") " } ]
1
ashishsinhaiitr/Web-Scrapper
https://github.com/ashishsinhaiitr/Web-Scrapper
a24cfa075f58c42468f6d7881474ce1e39b76abe
ab173bbb2ec251e6f9a7b87aca7564aaf6d320e4
2de662d83a46c468198e168fd74f4158fd9668dd
refs/heads/master
2017-12-20T21:47:20.276300
2017-06-04T05:39:55
2017-06-04T05:39:55
76,259,621
0
0
null
2016-12-12T13:39:45
2016-12-12T13:40:21
2016-12-13T11:25:06
Python
[ { "alpha_fraction": 0.6806853413581848, "alphanum_fraction": 0.6993769407272339, "avg_line_length": 21.068965911865234, "blob_id": "933c07dfad6bfbba7acc43b1164c487786f02b74", "content_id": "d75cbb52170ebed084a9cc0d23b262d4e0a3e00e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 642, "license_type": "no_license", "max_line_length": 51, "num_lines": 29, "path": "/CS109-SCRAPER.py", "repo_name": "ashishsinhaiitr/Web-Scrapper", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup \nfrom time import sleep\nurl=\"http://cs109.github.io/2015/pages/videos.html\"\nr=requests.get(url)\nsoup=BeautifulSoup(r.text)\nlinks=soup.findAll('a')\nvideo_urls=[]\nfor i in links:\n\tlink=i.get('href')\n\tif \"matterhorn\" in link:\n\t\tvideo_urls.append(link)\n\nsleep(1)\n\nfor i in range(len(video_urls)):\n\tdownload(video_urls[i],i+1)\n\tsleep(1)\n\ndef download(url,n):\n\t\"\"\"\n\tsoup=BeautifulSoup(requests.get(url).text)\n\tlinks=findAll('source')\n\tfor i in links:\n\t\tlink=i.get('src')\n\t\twith open(\"lecture%s\"%(n),\"wb\") as file:\n\t\t\tfile.write(link.read())\n\t\tsleep(1)\"\"\"\n\t#try selenium then load page and then apply\n\t\n" }, { "alpha_fraction": 0.7886179089546204, "alphanum_fraction": 0.7886179089546204, "avg_line_length": 11.300000190734863, "blob_id": "4c454dabe1bacdbc4f7100bb352df27d602c31eb", "content_id": "ddc0a195e19a001d244ceeedf734a9a2ce622d76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 123, "license_type": "no_license", "max_line_length": 47, "num_lines": 10, "path": "/README.md", "repo_name": "ashishsinhaiitr/Web-Scrapper", "src_encoding": "UTF-8", "text": "# Web-Scrapper\nPython script for scrapping data from a website\n\n### Requirements\n`\nScrapy\nMongoDB\nRequests\nBeautifulSoup\n`\n" }, { "alpha_fraction": 0.6819923520088196, "alphanum_fraction": 0.6896551847457886, "avg_line_length": 16.46666717529297, "blob_id": "dab4523bb916b46219770ab4a2379e138e926ad4", "content_id": "4fb8d98d5ff4e1c453482c450f86246a1e7c1582", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "no_license", "max_line_length": 51, "num_lines": 15, "path": "/Checksum.py", "repo_name": "ashishsinhaiitr/Web-Scrapper", "src_encoding": "UTF-8", "text": "import hashlib\n\nold=hashlib.md5(open(\"old.txt\").read()).hexdigest()\nprint \"old=\", old\n\nwith open(\"new.txt\") as file:\n\tdata=file.read()\n\tnew=hashlib.md5(data).hexdigest()\n\nprint \"new=\", new\n\nif old is new :\n\tprint \"same contents\"\nelse:\n\tprint \"contents not same\"" }, { "alpha_fraction": 0.7647058963775635, "alphanum_fraction": 0.7735294103622437, "avg_line_length": 33, "blob_id": "8f6aeb9235fa1d16f943bc5826448948c59f9fd0", "content_id": "f38d72585bdd5aa0d6624f884f61dde0fda7bebf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 340, "license_type": "no_license", "max_line_length": 89, "num_lines": 10, "path": "/WisdomQuotes.py", "repo_name": "ashishsinhaiitr/Web-Scrapper", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\nimport csv\nfrom urllib open urlopen\nhtml=urlopen(\"https://litemind.com/best-famous-quotes\").read()\n#file=open\nsoup=BeautifulSoup(hmtl)\ndata=soup.findAll('div',{\"class\":\"wp_quotepage\"})\nfor quote in data:\n\tprint quote.findChildren()[0].renderContents(), quote.findChildren()[1].renderContents()\n" }, { "alpha_fraction": 0.6553846001625061, "alphanum_fraction": 0.6676923036575317, "avg_line_length": 26.08333396911621, "blob_id": "4180bca328020e781960337e47fc4d698fbf2b88", "content_id": "1881d8479cffff6818ce6ac57cb9c74a09a1a655", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1300, "license_type": "no_license", "max_line_length": 57, "num_lines": 48, "path": "/data.py", "repo_name": "ashishsinhaiitr/Web-Scrapper", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\nurl=\"http://www.imdb.com/list/ls055592025/\"\nr=requests.get(url)\nsoup=BeautifulSoup(r.content)\ndata=soup.find_all('div',{\"class\":\"list detail\"})\nfor i in data:\n\tprint i.text\n\neven=\"even\"\nodd=\"odd\"\nfor i in range(1,101):\n\tif i%2 is 0:\n\t\tdata=soup.find_all('div',{\"class\":\"list_item even\"})\n\telse:\n\t\tdata=soup.find_all('div',{\"class\":\"list_item odd\"})\n\tfor piece in data:\n\t\tprint piece.text\n\ndata=soup.find_all('div',{\"class\":\"list detail\"})\ndata_odd=soup.find_all('div',{\"class\":\"list_item odd\"})\ndata_even=soup.find_all('div',{\"class\":\"list_item even\"})\n\n\nfor item in data:\n order=item.find_all('div',{\"class\":\"number\"})\n info=item.find_all('div',{\"class\":\"item_description\"})\n name=item.find_all('b')\n awards=item.find_all('div',{\"class\":\"description\"})\n rating=item.find_all(\"span\",{\"class\":\"value\"})\n year=item.find_all(\"span\",{\"class\":\"year_type\"})\n print order\n print name\n print info\n print awards\n\n data_odd=soup.find_all('div',{\"class\":\"list_item odd\"})\ndata_even=soup.find_all('div',{\"class\":\"list_item even\"})\n\nfor item in data\n\norder=soup.find_all('div',{\"class\":\"number\"})\nname=soup.find_all('a').get('href')\ninfo=soup.find_all('div',{\"class\":\"item_description\"})\nprint order\nfor i in name:\n\tprint i.get('href')\nprint info\n" }, { "alpha_fraction": 0.6564659476280212, "alphanum_fraction": 0.6771964430809021, "avg_line_length": 23.731706619262695, "blob_id": "4fb987a9d10a03ba429f9e967f09fc8c679b86fc", "content_id": "cd3ebbc0a7c4dabb9071e233282433689096a060", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1013, "license_type": "no_license", "max_line_length": 73, "num_lines": 41, "path": "/FacultyProfile.py", "repo_name": "ashishsinhaiitr/Web-Scrapper", "src_encoding": "UTF-8", "text": "import requests\nimport csv\nfrom urllib import urlopen\nfrom bs4 import BeautifulSoup\nurl=\"http://www.iitr.ac.in/departments/MT/pages/People+Faculty_List.html\"\nr=requests.get(url)\nsoup=BeautifulSoup(r.content)\ng_data=soup.findAll('div',{\"class\":\"list-wrapper\"})\nFaculty_List=[]\nfor item in g_data:\n\ttry:\n\t\tname=item.contents[1].findAll('a')[0].text.encode('utf-8')\n\texcept:\n\t\tpass\n\ttry:\n\t\tpost=item.contents[1].findAll('div')[2].text.encode('utf-8')\n\texcept:\n\t\tpass\n\ttry:\n\t\tinterests=item.contents[1].findAll('p')[0].text.encode('utf-8')\n\texcept :\n\t\tpass\n\ttry:\n\t\temail=item.contents[1].findAll('span')[0].text.encode('utf-8')\n\texcept:\n\t\tpass\n\ttry:\n\t\tphone=item.contents[1].findAll('span')[1].text.encode('utf-8')\n\texcept:\n\t\tpass\n\tFaculty=[name,post,interests,email,phone]\n\tFaculty_List.append(Faculty)\n\nfor i in Faculty_List:\n\tprint i[0],\"\\t\\t\",i[1],\"\\t\\t\", i[2],\"\\t\\t\", i[3],\"\\t\\t\", i[4],\"\\n\\n\"\n\n\nwith open ('name.cv','wb') as file:\n writer=csv.writer(file)\n for row in Faculty_List:\n writer.writerow(row)" }, { "alpha_fraction": 0.6654135584831238, "alphanum_fraction": 0.6654135584831238, "avg_line_length": 22.086956024169922, "blob_id": "0c3792dac851113e68adb856b7b104587f671783", "content_id": "82187ecc024a889746f28a40000c80eebd0af6fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 532, "license_type": "no_license", "max_line_length": 42, "num_lines": 23, "path": "/diff.py", "repo_name": "ashishsinhaiitr/Web-Scrapper", "src_encoding": "UTF-8", "text": "\nold_path=\"old.txt\"\nnew_path=\"new.txt\"\n\nold_lines=file(old_path).read().split(' ')\nnew_lines=file(new_path).read().split(' ')\n\nold_lines_set=set(old_lines)\nnew_lines_set=set(new_lines)\n\nold_added=old_lines_set - new_lines_set\nold_removed=new_lines_set - old_lines_set\n\nfor line in old_lines:\n\tif line in old_added:\n\t\tprint \"-\",line.strip('\\n')\n\telif line in old_removed:\n\t\tprint \"+\",line.strip('\\n')\n\nfor line in new_lines:\n\tif line in old_added:\n\t\tprint \"-\",line.strip('\\n')\n\telif line in old_removed:\n\t\tprint \"+\",line.strip('\\n')\n" }, { "alpha_fraction": 0.7099892497062683, "alphanum_fraction": 0.7121374607086182, "avg_line_length": 27.212121963500977, "blob_id": "e5b2a9ad5193ac790374d820671c057c69aadd59", "content_id": "f4f0c2ded20954e4ed4a6324653c0561d7f2551c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 931, "license_type": "no_license", "max_line_length": 77, "num_lines": 33, "path": "/stack/stack/stack/pipelines.py", "repo_name": "ashishsinhaiitr/Web-Scrapper", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\n\nimport pymongo\nfrom scrapy.conf import settings\nfrom scrapy.exceptions import DropItem\nfrom scrapy import log\n\"\"\"\nclass StackPipeline(object):\n def process_item(self, item, spider):\n return item\n\"\"\"\nclass MongoDBPipeline(object):\n def __init__(self):\n\tconnection=pymongo.MongoClient(\n\t settings['MONGODB_SERVER'],\n\t settings['MONGO_PORT']\n\t)\n\tdb=connection[settings['MONGO_DB']]\n\tself.collection=db[settings['MONGO_COLLECTION']]\n\n def process_item(self,item,spider):\n\tfor data in item:\n\t if not data:\n\t\traise DropItem('Missing {0}!\".format(data))\n\tself.collection.update({'url'=item['url']},dict(item),upsert=True)\n\tlog.msg(\"Question added t oMongoDB database!\",level=log.DEBUG,spider=spider)\n return item\n" }, { "alpha_fraction": 0.6497461795806885, "alphanum_fraction": 0.6710659861564636, "avg_line_length": 27.171428680419922, "blob_id": "173cdf2f138319b18f28990aba0f7df9b5a06c42", "content_id": "a088289ddf0ddc2f2df02d431e46484050ef150d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 985, "license_type": "no_license", "max_line_length": 142, "num_lines": 35, "path": "/FieldData.py", "repo_name": "ashishsinhaiitr/Web-Scrapper", "src_encoding": "UTF-8", "text": "import csv\nimport requests \nfrom bs4 import BeautifulSoup\nurl = \"http://www.pga.com/golf-courses/search?searchbox=Course+Name&searchbox_zip=ZIP&distance=50&price_range=0&course_type=both&has_events=0\"\nr = requests.get(url)\n\nsoup = BeautifulSoup(r.content)\n\ng_data1=soup.find_all(\"div\",{\"class\":\"views-field-nothing-1\"})\ng_data2=soup.find_all(\"div\",{\"class\":\"views-field-nothing\"})\n\n\ncourses_list=[]\n\nfor item in g_data2:\n try:\n name=item.contents[1].find_all(\"div\",{\"class\":\"views-field-title\"})[0].text\n except:\n name=''\n try:\n address1=item.contents[1].find_all(\"div\",{\"class\":\"views-field-address\"})[0].text\n except:\n address1=''\n try:\n address2=item.contents[1].find_all(\"div\",{\"class\":\"views-field-city-state-zip\"})[0].text\n except:\n address2=''\n course=[name,address1,address2]\n courses_list.append(course)\n\n \nwith open ('filename.cv','wb') as file:\n writer=csv.writer(file)\n for row in course_list:\n writer.writerow(row)" } ]
9
sureshdsk/sample-fastapi-app
https://github.com/sureshdsk/sample-fastapi-app
ea5e59833c0abe7a0b1c5f46e252737c70d193cd
62bc406b68b27e82a905da4f9c5cdfe8acdb5b96
0f18c348d271f1f05fd84fbc22f66e696e8efa23
refs/heads/main
2023-07-29T03:03:56.237539
2021-09-09T17:09:25
2021-09-09T17:09:25
399,794,930
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.6500553488731384, "alphanum_fraction": 0.6622369885444641, "avg_line_length": 19.522727966308594, "blob_id": "0674a4034ff55b90499b5431227c71bf849d4905", "content_id": "0f83e62894166618eb3d77da061ca20fc4473a50", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 903, "license_type": "permissive", "max_line_length": 69, "num_lines": 44, "path": "/app/main.py", "repo_name": "sureshdsk/sample-fastapi-app", "src_encoding": "UTF-8", "text": "import asyncio\nfrom fastapi import FastAPI\nfrom opentelemetry.instrumentation.fastapi import FastAPIInstrumentor\nimport requests\nimport random\nrandom.seed(54321)\n\n\napp = FastAPI()\n\n\[email protected](\"/\")\nasync def read_root():\n return {\"Hello\": \"World\"}\n\n\[email protected](\"/ping\")\nasync def health_check():\n return \"pong\"\n\n\[email protected](\"/items/{item_id}\")\nasync def read_item(item_id: int, q: str = None):\n if item_id % 2 == 0:\n # mock io - wait for x seconds\n seconds = random.uniform(0, 3)\n await asyncio.sleep(seconds)\n return {\"item_id\": item_id, \"q\": q}\n\n\[email protected](\"/invalid\")\nasync def invalid():\n raise ValueError(\"Invalid \")\n\n\[email protected](\"/external-api\")\ndef external_api():\n seconds = random.uniform(0, 3)\n response = requests.get(f\"https://httpbin.org/delay/{seconds}\")\n response.close()\n return \"ok\"\n\n\nFastAPIInstrumentor.instrument_app(app, excluded_urls=\"ping\")\n" }, { "alpha_fraction": 0.6797752976417542, "alphanum_fraction": 0.7191011309623718, "avg_line_length": 21.25, "blob_id": "6d6d6988c2cc1582532a9573ea3e925f4130b9e7", "content_id": "4c2acc6b2e09cac99602d32f2d607d6590306978", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 356, "license_type": "permissive", "max_line_length": 98, "num_lines": 16, "path": "/Dockerfile", "repo_name": "sureshdsk/sample-fastapi-app", "src_encoding": "UTF-8", "text": "FROM tiangolo/uvicorn-gunicorn:python3.7\n\n# open port\nEXPOSE 5000\n\n# add requirements\nCOPY ./app/requirements.txt /app/requirements.txt\n\n# install requirements\nRUN pip install -r /app/requirements.txt\n\n# copy source code\nCOPY ./app /app/app\n\n# Init command\nCMD [\"opentelemetry-instrument\", \"uvicorn\", \"app.main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"5000\"]\n" }, { "alpha_fraction": 0.7207325100898743, "alphanum_fraction": 0.7423152327537537, "avg_line_length": 28.980392456054688, "blob_id": "4120e917af1ffc2c83a0ca64c103cabe2d578dde", "content_id": "34e76eefa4ed44c568ff46631682a81bff9cd1e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1529, "license_type": "permissive", "max_line_length": 179, "num_lines": 51, "path": "/README.md", "repo_name": "sureshdsk/sample-fastapi-app", "src_encoding": "UTF-8", "text": "# FastAPI with SigNoz observability integration\n### Prerequisite\nSigNoz should be installed in your local machine or any server. To install SigNoz follow the instructions at https://signoz.io/docs/deployment/docker/\n\n\n### Run instructions for sending data to SigNoz\n\n#### Run with docker\nBuild docker image\n```\ndocker build -t sample-fastapi-app .\n```\n\nRun fast api app\n```\n# If you have your SigNoz IP Address, replace <IP of SigNoz> with your IP Address. \n\ndocker run -d --name fastapi-container \\\n-e OTEL_METRICS_EXPORTER='none' \\\n-e OTEL_RESOURCE_ATTRIBUTES='service.name=fastapiApp' \\\n-e OTEL_EXPORTER_OTLP_ENDPOINT='http://<IP of SigNoz>:4317' \\\n-p 5000:5000 sample-fastapi-app\n\n\n# If you are running signoz through official docker-compose setup, run `docker network ls` and find clickhouse network id. It will be something like this clickhouse-setup_default \n# and pass network id by using --net <network ID>\n\ndocker run -d --name fastapi-container \\ \n--net clickhouse-setup_default \\ \n--link clickhouse-setup_otel-collector_1 \\\n-e OTEL_METRICS_EXPORTER='none' \\\n-e OTEL_RESOURCE_ATTRIBUTES='service.name=fastapiApp' \\\n-e OTEL_EXPORTER_OTLP_ENDPOINT='http://clickhouse-setup_otel-collector_1:4317' \\\n-p 5000:5000 sample-fastapi-app\n\n```\n\n\n### Send Traffic \n```\npip install locust\n```\n\n```\nlocust -f locust.py --headless --users 10 --spawn-rate 1 -H http://localhost:5000\n```\n\n\n### Trobleshooting\nIf you face any problem in instrumenting with OpenTelemetry, refer to docs at \nhttps://signoz.io/docs/instrumentation/python\n" }, { "alpha_fraction": 0.5578446984291077, "alphanum_fraction": 0.5736925601959229, "avg_line_length": 23.269229888916016, "blob_id": "76ff9a3ea1d5060132feaf107d114b13afbd09b2", "content_id": "b9a0e6ef5539e014c5daa8b3c8f16816b0a2adc1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 631, "license_type": "permissive", "max_line_length": 66, "num_lines": 26, "path": "/locust.py", "repo_name": "sureshdsk/sample-fastapi-app", "src_encoding": "UTF-8", "text": "import time\nfrom locust import HttpUser, task, between\n\n\nclass QuickstartUser(HttpUser):\n wait_time = between(1, 5)\n\n @task\n def hello_world(self):\n self.client.get(\"/\", name=\"/home\")\n\n @task\n def invalid(self):\n self.client.get(\"/invalid\", name=\"/invalid\")\n\n @task(3)\n def view_items(self):\n for item_id in range(10):\n self.client.get(f\"/items/{item_id}\", name=\"/items\")\n time.sleep(1)\n\n @task(3)\n def make_external_api_calls(self):\n for item_id in range(10):\n self.client.get(\"/external-api\", name=\"/external-api\")\n time.sleep(1)\n" }, { "alpha_fraction": 0.7833333611488342, "alphanum_fraction": 0.8500000238418579, "avg_line_length": 21.5, "blob_id": "221a1487ea8d3f7b69f34dc0e240c7d31fec21f8", "content_id": "7f547333f48ab5944a29207c117e5534d4570cd7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 180, "license_type": "permissive", "max_line_length": 37, "num_lines": 8, "path": "/app/requirements.txt", "repo_name": "sureshdsk/sample-fastapi-app", "src_encoding": "UTF-8", "text": "fastapi==0.68.1\npython-dotenv==0.19.0\nuvicorn==0.15.0\nrequests\nopentelemetry-distro\nopentelemetry-instrumentation\nopentelemetry-exporter-otlp\nopentelemetry-instrumentation-fastapi\n" } ]
5
kubasiak/DNNdemo
https://github.com/kubasiak/DNNdemo
f37560b4e0ef1402463a78c6e6402efd41b9e90b
07d9c8f50987c180d3dd6b4ea8194425305a5d46
1c1070b81a953cfd9551c5ecb4f375a2d73279ad
refs/heads/master
2023-02-19T20:40:20.749005
2022-10-27T11:10:54
2022-10-27T11:10:54
237,430,857
2
0
null
2020-01-31T13:00:28
2022-10-27T11:11:03
2023-02-15T23:50:39
Jupyter Notebook
[ { "alpha_fraction": 0.5285032391548157, "alphanum_fraction": 0.7162314057350159, "avg_line_length": 17.992000579833984, "blob_id": "e462c3ecd3dbe416e03dd48e02687c98eb2ae1eb", "content_id": "48e9f0dbce9c9ea2ad5c23fca425e62bd3022b78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 7122, "license_type": "no_license", "max_line_length": 52, "num_lines": 375, "path": "/requirements.txt", "repo_name": "kubasiak/DNNdemo", "src_encoding": "UTF-8", "text": "absl-py==0.9.0\nadal==1.2.2\nalabaster==0.7.12\nanaconda-client==1.7.2\nanaconda-project==0.8.3\nappdirs==1.4.3\napplicationinsights==0.11.9\nasn1crypto==1.3.0\nastor==0.8.1\nastroid==2.3.3\nastropy==4.0\natomicwrites==1.3.0\nattrs==19.3.0\naudioread==2.1.8\nAutomat==0.8.0\nazure-cognitiveservices-vision-computervision==0.7.0\nazure-common==1.1.24\nazure-core==1.3.0\nazure-graphrbac==0.61.1\nazure-identity==1.2.0\nazure-mgmt-authorization==0.60.0\nazure-mgmt-containerregistry==2.8.0\nazure-mgmt-keyvault==2.0.0\nazure-mgmt-network==10.2.0\nazure-mgmt-resource==8.0.0\nazure-mgmt-storage==7.1.0\nazure-nspkg==3.0.2\nazure-storage==0.36.0\nazure-storage-queue==12.1.5\nazureml==0.2.7\nazureml-automl-core==0.1.0.32573435\nazureml-automl-runtime==0.1.0.32573435\nazureml-contrib-dataset==0.1.0.32573435\nazureml-contrib-pipeline-steps==1.0.85\nazureml-core==1.27.0\nazureml-dataprep==1.9.3\nazureml-dataprep-native==14.2.1\nazureml-defaults==0.1.0.32573435\nazureml-explain-model==1.1.5\nazureml-interpret==0.1.0.32573435\nazureml-model-management-sdk==1.0.1b6.post1\nazureml-pipeline==1.9.0\nazureml-pipeline-core==1.9.0\nazureml-pipeline-steps==1.9.0\nazureml-sdk==1.9.0\nazureml-telemetry==1.9.0\nazureml-train==0.1.0.32573435\nazureml-train-automl==0.1.0.32573435\nazureml-train-automl-client==0.1.0.32573435\nazureml-train-automl-runtime==0.1.0.32573435\nazureml-train-core==0.1.0.32573435\nazureml-train-restclients-hyperdrive==0.1.0.32573435\nazureml-widgets==1.0.85\nBabel==2.8.0\nbackcall==0.1.0\nbackports.os==0.1.1\nbackports.shutil-get-terminal-size==1.0.0\nbackports.tempfile==1.0\nbackports.weakref==1.0.post1\nbcrypt==3.1.7\nbeautifulsoup4==4.8.2\nbitarray==1.2.1\nbkcharts==0.2\nblaze==0.11.3\nbleach==3.1.0\nbokeh==1.4.0\nboto==2.49.0\nboto3==1.12.11\nbotocore==1.15.11\nBottleneck==1.3.1\ncachetools==4.0.0\ncertifi==2020.6.20\ncffi==1.13.2\nchardet==3.0.4\nClick==7.0\ncloudpickle==1.2.2\nclyent==1.2.2\ncolorama==0.4.1\ncomet-git-pure==0.19.16\ncomet-ml==3.1.9\ncomtypes==1.1.7\nconfigobj==5.0.6\nconfigparser==3.7.4\nconstantly==15.1.0\ncontextlib2==0.6.0.post1\ncryptography==2.8\ncycler==0.10.0\nCython==0.29.14\ncytoolz==0.10.1\ndask==2.10.0\ndatashape==0.5.4\ndecorator==4.4.1\ndefusedxml==0.6.0\ndill==0.3.1.1\ndistributed==2.10.0\ndistro==1.4.0\ndocker==4.1.0\ndocopt==0.6.2\ndocutils==0.15.2\ndotnetcore2==2.1.14\neditdistance==0.5.3\nefficientnet==1.0.0\nentrypoints==0.3\nessential-generators==0.9.2\net-xmlfile==1.0.1\neverett==1.0.2\nfastcache==1.1.0\nfilelock==3.0.12\nfire==0.2.1\nflake8==3.7.9\nFlask==1.0.3\nFlask-Cors==3.0.8\nfonttools==4.13.0\nfsspec==0.6.2\nfusepy==3.0.1\nfuture==0.18.2\ngast==0.2.2\ngensim==3.8.1\ngevent==1.4.0\nglob2==0.7\ngoogle-auth==1.11.0\ngoogle-auth-oauthlib==0.4.1\ngoogle-pasta==0.1.8\ngreenlet==0.4.15\ngrpcio==1.26.0\ngunicorn==19.9.0\nh5py==2.10.0\nHeapDict==1.0.1\nhtml5lib==1.0.1\nhttpie==2.2.0\nhyperlink==19.0.0\nhypothesis==4.54.2\nidna==2.8\nimageio==2.6.1\nimagesize==1.2.0\nimgaug==0.4.0\nimportlib-metadata==1.4.0\nincremental==17.5.0\ninterpret-community==0.6.0\ninterpret-core==0.1.20\nipykernel==5.1.4\nipython==7.11.1\nipython-genutils==0.2.0\nipywidgets==7.5.1\nisodate==0.6.0\nisort==4.3.21\nitsdangerous==1.1.0\njdcal==1.4.1\njedi==0.16.0\njeepney==0.4.2\nJinja2==2.10.3\njmespath==0.9.4\njoblib==1.2.0\njson-logging-py==0.2\njson5==0.8.5\nJsonForm==0.0.2\njsonpickle==1.2\njsonschema==3.2.0\nJsonSir==0.0.2\njupyter==1.0.0\njupyter-client==5.3.4\njupyter-console==6.1.0\njupyter-core==4.6.1\njupyterlab==1.2.5\njupyterlab-launcher==0.13.1\njupyterlab-server==1.0.6\nKeras==2.3.1\nKeras-Applications==1.0.8\nkeras-ocr==0.8.4\nKeras-Preprocessing==1.1.0\nkeras2onnx==1.6.0\nkeyring==20.0.0\nkiwisolver==1.1.0\nlazy-object-proxy==1.4.3\nliac-arff==2.4.0\nlibarchive-c==2.8\nlibrosa==0.7.2\nlightgbm==2.3.0\nllvmlite==0.31.0\nlocket==0.2.0\nlxml==4.4.2\nMarkdown==3.1.1\nMarkupSafe==1.1.1\nmatplotlib==3.1.1\nmccabe==0.6.1\nmenuinst==1.4.16\nmistune==0.8.4\nmkl-fft==1.0.15\nmkl-random==1.1.0\nmkl-service==2.3.0\nmock==3.0.5\nmore-itertools==8.0.2\nmpmath==1.1.0\nmsal==1.1.0\nmsal-extensions==0.1.3\nmsgpack==0.6.1\nmsrest==0.6.10\nmsrestazure==0.6.2\nmultipledispatch==0.6.0\nnbconvert==5.6.1\nnbformat==5.0.4\nndg-httpsclient==0.5.1\nnetifaces==0.10.9\nnetworkx==2.4\nnimbusml==1.6.1\nnltk==3.4.5\nnose==1.3.7\nnotebook==6.0.3\nnum2words==0.5.10\nnumba==0.47.0\nnumexpr==2.7.0\nnumpy==1.16.2\nnumpydoc==0.9.2\nnvidia-ml-py3==7.352.0\noauthlib==3.1.0\nodo==0.5.1\nolefile==0.46\nonnx==1.6.0\nonnxconverter-common==1.6.0\nonnxmltools==1.4.1\nopencv-python==4.3.0.38\nopenpyxl==3.0.3\nopt-einsum==3.1.0\npackaging==20.1\npandas==0.23.4\npandocfilters==1.4.2\nparso==0.6.0\npartd==1.1.0\npath==13.1.0\npathlib2==2.3.5\npathspec==0.7.0\npatsy==0.5.1\npep8==1.7.1\npickleshare==0.7.5\nPillow==7.0.0\npkginfo==1.5.0.1\npluggy==0.13.1\nply==3.11\npmdarima==1.1.1\nportalocker==1.5.2\nprometheus-client==0.7.1\nprompt-toolkit==3.0.3\nprotobuf==3.11.2\npsutil==5.6.7\npy==1.8.1\npy-cpuinfo==5.0.0\npyarrow==0.15.1\npyasn1==0.4.8\npyasn1-modules==0.2.7\npyclipper==1.2.0\npycodestyle==2.5.0\npycosat==0.6.3\npycparser==2.19\npycrypto==2.6.1\npycurl==7.43.0.4\npydub==0.24.1\npyflakes==2.1.1\nPygments==2.5.2\nPyHamcrest==2.0.0\nPyJWT==1.7.1\npylint==2.4.4\npyodbc==4.0.27\npyOpenSSL==19.1.0\npyparsing==2.4.6\npypiwin32==223\npyreadline==2.1\npyrsistent==0.15.7\nPySocks==1.7.1\npytesseract==0.3.5\npytest==5.0.1\npytest-arraydiff==0.3\npytest-astropy==0.7.0\npytest-astropy-header==0.1.1\npytest-doctestplus==0.5.0\npytest-openfiles==0.4.0\npytest-remotedata==0.3.2\npython-dateutil==2.8.1\nPython-EasyConfig==0.1.7\npytz==2019.3\nPyWavelets==1.1.1\npywin32==227\npywin32-ctypes==0.2.0\npywinpty==0.5.7\nPyYAML==5.2\npyzmq==18.1.1\nQtAwesome==0.6.0\nqtconsole==4.6.0\nQtPy==1.9.0\nregex==2020.5.14\nrequests==2.22.0\nrequests-oauthlib==1.3.0\nresampy==0.2.2\nResource==0.2.1\nrope==0.16.0\nrsa==4.0\nruamel-yaml==0.15.87\nruamel.yaml.clib==0.2.0\ns3transfer==0.3.3\nsacremoses==0.0.43\nscikit-image==0.15.0\nscikit-learn==0.20.3\nscipy==1.4.1\nseaborn==0.9.0\nSecretStorage==3.1.2\nSend2Trash==1.5.0\nsentencepiece==0.1.91\nservice-identity==18.1.0\nshap==0.34.0\nShapely==1.7.0\nsimplegeneric==0.8.1\nsingledispatch==3.4.0.3\nsix==1.14.0\nskl2onnx==1.4.9\nsklearn==0.0\nsklearn-pandas==1.7.0\nsmart-open==1.9.0\nsnowballstemmer==2.0.0\nsortedcollections==1.1.2\nsortedcontainers==2.1.0\nSoundFile==0.10.3.post1\nsoupsieve==1.9.5\nSphinx==2.3.1\nsphinxcontrib-applehelp==1.0.1\nsphinxcontrib-devhelp==1.0.1\nsphinxcontrib-htmlhelp==1.0.2\nsphinxcontrib-jsmath==1.0.1\nsphinxcontrib-qthelp==1.0.2\nsphinxcontrib-serializinghtml==1.1.3\nsphinxcontrib-websupport==1.1.2\nspyder==3.3.6\nspyder-kernels==0.5.2\nSQLAlchemy==1.3.13\nstatsmodels==0.10.2\nstyle==1.1.0\nsympy==1.5.1\ntables==3.6.1\nTBB==0.1\ntblib==1.6.0\ntensorboard==2.1.0\ntensorflow==2.1.0\ntensorflow-estimator==2.1.0\ntermcolor==1.1.0\nterminado==0.8.3\ntestpath==0.4.4\ntokenizers==0.5.2\ntoolz==0.10.0\ntorch==1.5.0+cpu\ntorchvision==0.6.0+cpu\ntornado==6.0.3\ntqdm==4.42.0\ntraitlets==4.3.3\ntransformers==2.8.0\nTwisted==19.10.0\ntyping-extensions==3.7.4.1\nunicodecsv==0.14.1\nupdate==0.0.1\nurllib3==1.25.8\nvalidators==0.17.1\nwcwidth==0.1.8\nwebencodings==0.5.1\nwebsocket-client==0.57.0\nWerkzeug==0.16.1\nwidgetsnbextension==3.5.1\nwin-inet-pton==1.1.0\nwin-unicode-console==0.5\nwincertstore==0.2\nwrapt==1.11.2\nwurlitzer==2.0.0\nxlrd==1.2.0\nXlsxWriter==1.2.7\nxlwings==0.17.0\nxlwt==1.3.0\nzict==1.0.0\nzipp==0.6.0\nzope.interface==4.7.1\n" }, { "alpha_fraction": 0.6265060305595398, "alphanum_fraction": 0.6289156675338745, "avg_line_length": 15.428571701049805, "blob_id": "b76d0cbe7ac12e28c709844ccf700b96fa112e59", "content_id": "a7919f53e97ec867baafe7e6cfb7b26a9bf3cdad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 830, "license_type": "no_license", "max_line_length": 88, "num_lines": 49, "path": "/score.py", "repo_name": "kubasiak/DNNdemo", "src_encoding": "UTF-8", "text": "import json\r\r\nimport numpy as np\r\r\nimport os\r\r\nimport pickle\r\r\nfrom keras.models import model_from_json\r\r\nfrom azureml.core.model import Model\r\r\n\r\r\ndef init():\r\r\n global model \r\r\n model_root = Model.get_model_path('DNNdemo')\r\r\n # load json and create model\r\r\n json_file = open(os.path.join(model_root, 'model.json'), 'r')\r\r\n model_json = json_file.read()\r\r\n json_file.close()\r\r\n model = model_from_json(model_json)\r\r\n # load weights into new model\r\r\n model.load_weights(os.path.join(model_root, \"model.h5\")) \r\r\n model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\r\r\n \r\r\n \r\r\ndef run(raw_data):\r\r\n data = np.array(json.loads(raw_data)['data'])\r\r\n # make prediction\r\r\n y_hat = np.argmax(model.predict(data), axis=1)\r\r\n return y_hat.tolist()\r\n" } ]
2
alxcoh/Peioa3yhedniuw4nrxdiwuyahebnquiekjhba2niquyjkehadlm2idjniuy4wkgjdbhniabhn7iguahj2qagny427dy42yfgnyda
https://github.com/alxcoh/Peioa3yhedniuw4nrxdiwuyahebnquiekjhba2niquyjkehadlm2idjniuy4wkgjdbhniabhn7iguahj2qagny427dy42yfgnyda
249eb9b522bcbb5c65407e8cd5f6b4f0103f769e
85c90669e6a44f5f4dc89786d887c450809426ea
5426c1e55105a675f92cb5acf0416353628ebc17
refs/heads/master
2020-03-28T19:07:42.150285
2014-01-07T04:52:27
2014-01-07T04:52:27
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4491303563117981, "alphanum_fraction": 0.4843774139881134, "avg_line_length": 28.008928298950195, "blob_id": "342f8e1315109e56628cc679a7ec21954c9d6a5e", "content_id": "aab1e48f123651e230f6171e7aaecd60bb574b39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6497, "license_type": "no_license", "max_line_length": 146, "num_lines": 224, "path": "/EclipseShitzProjects/MathThing/src/root/nested/main.py", "repo_name": "alxcoh/Peioa3yhedniuw4nrxdiwuyahebnquiekjhba2niquyjkehadlm2idjniuy4wkgjdbhniabhn7iguahj2qagny427dy42yfgnyda", "src_encoding": "UTF-8", "text": "import random\nimport decimal\nimport commonFunctions\nfrom decimal import *\nclass Character:\n def __init__(self, ordNum, prob):\n self.ordNum=ordNum\n self.prob=prob\n self.state=1 #1 is alive 0 is dead\n \n def shoot(self, a): #a is who is being shot\n randy=random.randrange(self.prob)\n if randy==0:\n #print 'shot connected from', self.ordNum\n a.state=0\n #print a.ordNum, ' is dead'\n return 1 #person killed\n else:\n #print 'shot missed from', self.ordNum\n return 0 #person alive\n \n def logicA1(self, b, c):\n if b.state==1 and c.state==1:\n return None\n elif b.state==0 and c.state==0:\n return 10 #game over charA wins\n elif b.state==0:\n if self.shoot(c)==1:\n return c.ordNum\n elif c.state==0:\n if self.shoot(b)==1:\n return b.ordNum\n \n return 100\n \n def logicA2(self, b, c):\n if (b.state==1 and c.state==1) or (b.state==0 and c.state==1):\n if self.shoot(c)==1:\n return c.ordNum\n elif b.state==1 and c.state==0:\n if self.shoot(b)==1:\n return b.ordNum\n elif b.state==0 and c.state==0:\n return 10\n \n return 100\n \n def logicA3(self, b, c):\n if (b.state==1 and c.state==1) or (b.state==1 and c.state==0):\n if self.shoot(b)==1:\n return b.ordNum\n elif c.state==1 and b.state==0:\n if self.shoot(c)==1:\n return c.ordNum\n elif b.state==0 and c.state==0:\n return 10\n \n return 100\n\n def logicA4(self, b, c):\n if b.state==1 and c.state==1:\n randy=random.randrange(3)\n if randy==0:\n return None\n if randy==1:\n if self.shoot(b)==1:\n return b.ordNum\n if randy==2:\n if self.shoot(c)==1:\n return c.ordNum\n elif b.state==0 and c.state==0:\n return 10\n \n elif b.state==1 and c.state==0:\n if self.shoot(b)==1:\n return b.ordNum\n \n elif b.state==0 and c.state==1:\n if self.shoot(c)==1:\n return c.ordNum\n \n def logicA5(self, b, c):\n if b.state==1 and c.state==1:\n randy=random.randrange(2)\n if randy==0:\n if self.shoot(b)==1:\n return b.ordNum\n if randy==1:\n if self.shoot(c)==1:\n return c.ordNum\n elif b.state==0 and c.state==0:\n return 10\n \n elif b.state==1 and c.state==0:\n if self.shoot(b)==1:\n return b.ordNum\n \n elif b.state==0 and c.state==1:\n if self.shoot(c)==1:\n return c.ordNum\n \n return None\n def turn(self, b, c, f):\n if self.ordNum==0:\n if f==0:\n return charA.logicA1(b, c)\n elif f==1:\n return charA.logicA2(b, c)\n elif f==2:\n return charA.logicA3(b, c)\n elif f==3:\n return charA.logicA4(b, c)\n elif f==4:\n return charA.logicA5(b, c)\n elif self.ordNum==1 or self.ordNum==2:\n if c.state==1:\n if self.shoot(c)==1:\n return c.ordNum\n elif c.state==0 and b.state==0:\n return self.ordNum+10 #a won\n\n elif c.state==0 and b.state==1:\n if self.shoot(b)==1:\n return b.ordNum\n else: return 100\ncharA=Character(0, 3)\ncharB=Character(1, 2)\ncharC=Character(2, 1)\naCount=0\nbCount=0\ncCount=0\n\ngameOn=1\n\ncounty=0;\n\ndef itr(a): #0 is good logic 1 is bad logic\n resA=100\n resB=100\n resC=100\n '''print 'start'\n print charA.state\n print charB.state\n print charC.state'''\n \n if charA.state==1:\n returny=0\n #print 'a turn'\n resA=charA.turn(charB, charC, a)\n if resA==10:\n #print \"Player A wins\"\n returny=1\n return 0, 0\n if charB.state==1:\n #print 'b turn'\n resB=charB.turn(charA, charC, a)\n if resB==11:\n #print \"Player B wins\"\n returny=1\n return 0, 1\n if charC.state==1:\n #print 'c turn'\n resC=charC.turn(charA, charB, a)\n if resC==12:\n #print \"Player C wins\"\n returny=1\n return 0, 2\n \n if returny==0: return 1, 100\ncycleTimes=500000\nlogicNum=5\naCount=[0 for i in range(logicNum)]\nbCount=[0 for i in range(logicNum)]\ncCount=[0 for i in range(logicNum)]\n#print '\\nStarting Bad Logic cycle:'\nfor x in range(logicNum):\n print '\\nStarting cycle for logic ', x+1\n for i in range(cycleTimes):\n gameOn=1\n charA.state=1\n charB.state=1\n charC.state=1\n while gameOn==1:\n res=0\n addr=0\n try:\n res, addr=itr(x)\n except TypeError:\n print 'exception'\n res=0\n addr=100\n \n gameOn=res\n if addr==100:\n continue\n if addr==0:\n aCount[x]+=1\n county+=1\n if addr==1:\n bCount[x]+=1\n county+=1\n if addr==2:\n cCount[x]+=1\n county+=1\n if county%10000==0:\n print county\n \n gameCount=1\n county=0\n\n\nfor x in range(logicNum):\n print '\\nFor logic ', x+1, ':'\n print '\\nA won ',aCount[x], ' times, ', Decimal(aCount[x]*100)/Decimal(cycleTimes), '% of the time'\n print '\\nB won ',bCount[x], ' times, ', Decimal(bCount[x]*100)/Decimal(cycleTimes), '% of the time'\n print '\\nC won ',cCount[x], ' times, ', Decimal(cCount[x]*100)/Decimal(cycleTimes), '% of the time'\n \naCounter=[0 for i in range(logicNum)]\n\nfor x in range(1, logicNum):\n aCounter[x]=Decimal(aCount[x]*100)/Decimal(cycleTimes)\n print '\\nDiffernce in percent won between good strategy and strategy ', x+1, ': ', Decimal(aCount[0]*100)/Decimal(cycleTimes)-aCounter[x], '%'\n percentIncrease=100*((Decimal(aCount[0])/Decimal(aCount[x]))-1)\n print 'Advantage good strategy gives over strategy ', x+1, ': ', percentIncrease, '%'" }, { "alpha_fraction": 0.4902777671813965, "alphanum_fraction": 0.5368055701255798, "avg_line_length": 18.213333129882812, "blob_id": "c2cb790034827a7ca9747737e61e8dc887e1dfc8", "content_id": "3353d150bd56114f1898e848aa46274117d5df72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1440, "license_type": "no_license", "max_line_length": 54, "num_lines": 75, "path": "/PygameFirst/src/root/nested/main.py", "repo_name": "alxcoh/Peioa3yhedniuw4nrxdiwuyahebnquiekjhba2niquyjkehadlm2idjniuy4wkgjdbhniabhn7iguahj2qagny427dy42yfgnyda", "src_encoding": "UTF-8", "text": "'''\nCreated on Dec 22, 2013\n\n@author: alxcoh\n'''\n\nimport pygame, sys\n#from pygame import *\nfrom pygame.locals import *\ndef main():\n # Initialize screen\n pygame.init()\n screen = pygame.display.set_mode((900, 800))\n pygame.display.set_caption('Basic Pygame program')\n\n # Fill background\n background = pygame.Surface(screen.get_size())\n background = background.convert()\n\n\n topR=252\n lowR=3\n topB=252\n lowB=3\n topG=252\n lowG=3\n rUp=True\n gUp=False\n bUp=True\n rIter=4\n bIter=2\n gIter=3\n r=89\n g=89\n b=89\n background.fill((r, g, b))\n\n\n # Display some text\n font = pygame.font.Font(None, 36)\n text = font.render(\"Hello There\", 1, (10, 10, 10))\n textpos = text.get_rect()\n textpos.centerx = background.get_rect().centerx\n background.blit(text, textpos)\n\n greaterR=0\n greaterG=0\n\n while 1: # Event loop\n background.fill((r, g, b))\n if r==0:\n greaterR=1\n elif r==255:\n greaterR=0\n if greaterR==0:\n r-=1\n elif greaterR==1:\n r+=1\n if g==0:\n greaterG=1\n elif g==255:\n greaterG=0\n if greaterG==0:\n g-=1\n elif greaterG==1:\n g+=1\n for event in pygame.event.get():\n if event.type == QUIT:\n return\n\n screen.blit(background, (0, 0))\n pygame.display.flip()\n\n\nmain()" }, { "alpha_fraction": 0.5351858735084534, "alphanum_fraction": 0.5604475140571594, "avg_line_length": 25.653846740722656, "blob_id": "a9d75f94ca6775f45330e371bb3e4c02854a8055", "content_id": "d247a9d06f4ff2f50329e07f0a417dd30bdc842d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2771, "license_type": "no_license", "max_line_length": 98, "num_lines": 104, "path": "/BouncyBall/src/root/nested/simTest.py", "repo_name": "alxcoh/Peioa3yhedniuw4nrxdiwuyahebnquiekjhba2niquyjkehadlm2idjniuy4wkgjdbhniabhn7iguahj2qagny427dy42yfgnyda", "src_encoding": "UTF-8", "text": "'''\nCreated on Dec 26, 2013\n\n@author: alxcoh\n'''\nfrom commonFunctions import *\n\ndef simTester(side, xPosy, yPosy, xVel, yVel): #0 is left 1 is right, DASCH IST ALEXS FUNCTION\n #btw this is long and unnecessary look at mine\n hit=False #if the sim reaches its end\n side=side\n xPosy=xPosy\n yPosy=yPosy\n xVel=xVel\n yVel=yVel\n maxDown=50\n maxRight=50\n \n if yVel>maxDown:\n yVel=maxDown\n if yVel<-maxDown:\n yVel=-maxDown\n \n if xVel>maxRight:\n xVel=maxRight\n if xVel<-maxRight:\n xVel=-maxRight\n \n counter=0\n #values=dimensionList([4, 100000])\n '''\n if yVel>=0:\n goingDown=True\n startY=True\n elif yVel<0:\n goingDown=False\n startY=False\n if xVel>=0:\n goingRight=True\n start=True\n else:\n goingRight=False\n start=False\n '''\n if side==False:\n while hit==False:\n #print values[counter]\n if xPosy>=940:\n hit=True\n return yPosy\n \n if yPosy>=660:\n yVel*=-1.0\n yPosy=650\n \n if yPosy<=40:\n yVel*=-1.0\n yPosy=50\n\n if xPosy<=60:\n xVel*=-1.0\n xPosy=80\n \n xPosy+=xVel\n yPosy+=yVel\n counter+=1\n #good job your prev one was so dumb and confusing but this is good sim\n #what i was trying to do was make it not simulate but calculate mathematically\n\ndef FORESEETHEFUTURE (side, x, y, Vx, Vy, sizeX, sizeY, paddleSize): #false is left, true is right\n '''more natural to me because physics\n sizeX should be between ball's end and paddle\n sizeY should be total size up/down\n remember to account for paddlesize\n returns y position wanted\n '''\n firstFramesToYWall=0 #time from paddle to first wall\n wavelength=0 #from wall back to wall\n if Vy==0: return y #obvious\n if Vy>0: firstFramesToYWall=(sizeY-y)/Vy\n if Vy<0: firstFramesToYWall=-y/Vy\n newX=Vx*firstFramesToYWall+x\n wavelength=2*sizeY/Vy*Vx\n n=0\n while not side and newX+n*wavelength<930:\n n+=1\n print 'while not loop done: iter'\n \n while side and not newX+n*wavelength>70:\n n+=1\n print 'while not loop done: iter'\n distFromPaddle=0\n if side:\n distFromPaddle=newX+n*wavelength+70\n if Vy>0:\n return sizeY-abs(distFromPaddle/Vx*Vy)\n if Vy<0:\n return abs(distFromPaddle/Vx*Vy)\n if side: \n distFromPaddle=newX+n*wavelength-70\n if Vy>0:\n return sizeY-abs(distFromPaddle/Vx*Vy)\n if Vy<0:\n return abs(distFromPaddle/Vx*Vy)" }, { "alpha_fraction": 0.6455122232437134, "alphanum_fraction": 0.6636446118354797, "avg_line_length": 27.28205108642578, "blob_id": "aa0412e14194e9ffb545a624eb77b4c54dfd8331", "content_id": "cff1529b545b2b5c6ca3b4c6f187986f923d3bbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1103, "license_type": "no_license", "max_line_length": 100, "num_lines": 39, "path": "/EclipseShitzProjects/CommonFunctions/src/root/nested/commonFunctions.py", "repo_name": "alxcoh/Peioa3yhedniuw4nrxdiwuyahebnquiekjhba2niquyjkehadlm2idjniuy4wkgjdbhniabhn7iguahj2qagny427dy42yfgnyda", "src_encoding": "UTF-8", "text": "'''\nCreated on Dec 22, 2013\n\n@author: alxcoh\n'''\nfrom decimal import *\nfrom commonPygame import *\nimport math\nimport random\nimport time\ndef dimensionList(values):\n a=[0 for i in range(values[0])] #first, init base array\n for i in range(1, len(values)): #for number of dimensions:\n a=[a for i in range(values[i])] #the array = the old array but length # of times\n return a #smartness, nice one\n\ndef print2DArray(array): #a readable print of a 2d array, actually in 2 dimensions\n for i in range(len(array)):\n print array[i]\n \ndef rollDice(num,sides):\n total=0\n for i in range(num):\n total+=random.randrange(sides)+1\n return total \n\ndef chanceOfHappen(a, b):\n if a>b:\n print 'Must be first parameter less then second parameter for chance of something happening'\n return None\n randy=random.randrange(b)\n if randy<a:\n return 1 #event did happen\n else: \n return 0 #event did not happen\n \ndef percentChange(a, b): #percentage increase or decrease from a to b\n changy=Decimal(b)/Decimal(a)\n return (changy-1)*100\n" }, { "alpha_fraction": 0.559459924697876, "alphanum_fraction": 0.5946858525276184, "avg_line_length": 30.741758346557617, "blob_id": "f5c38692d2c975b2616c2ef52054a4273740d1c1", "content_id": "450dc3cefa9ddec5ccd5f84685fcbf1fa18f2ddf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11554, "license_type": "no_license", "max_line_length": 155, "num_lines": 364, "path": "/BouncyBall/src/root/nested/main.py", "repo_name": "alxcoh/Peioa3yhedniuw4nrxdiwuyahebnquiekjhba2niquyjkehadlm2idjniuy4wkgjdbhniabhn7iguahj2qagny427dy42yfgnyda", "src_encoding": "UTF-8", "text": "'''\nCreated on Dec 23, 2013\n\n@author: alxcoh and 71619997a\n'''\n\nfrom commonPygame import *\nfrom simTest import *\n\n#Colors\nscoreL=0\nscoreR=0\npause=True\nend=False\ncrazyball=False # :D\nCPU1=True\nCPU2=False\nloopnum=1\nyPos=350.0\nxPos=500.0\nmaxDown=50.0\nmaxRight=50.0\nstartspeedD=8\nstartspeedR=8\ngoingDown=8.0\ngoingRight=8.0\nmaxDown=15\nmaxRight=50\nstartspeedD=8\nstartspeedR=8\ngoingDown=startspeedD\ngoingRight=startspeedR\nW=False\nS=False\nUP=False\nDOWN=False\nrandomness=3 #if you actually want to play crazyball, set this at 4-6 for regular, 6-10 is madness, 10-20 for insanity\ncrazyDelay=5 #how often velocity changes in crazyball\nFPS=60\nfpsClock=pygame.time.Clock()\npaddleHeight=[150, 150]\nglobal passy\npassy=True\npaddleY=[350-(paddleHeight[0]/2), 350-(paddleHeight[1]/2)] # 0 is left, 1 is right\n\npaddleSpeed=[10, 3]\n\npaddleLeft=pygame.Rect(15, paddleY[0], 15, paddleHeight[0])\npaddleRight=pygame.Rect(970, paddleY[1], 15, paddleHeight[1])\n\n\ndef paddleTouched():\n if xPos>=940 and yPos>=paddleY[1]-30 and yPos<=paddleY[1]+paddleHeight[1]+30:\n #print yPos \n return 1\n if xPos<=60 and yPos>=paddleY[0]-30 and yPos<=paddleY[0]+paddleHeight[0]+30:\n return 2\n return 0 \n \ndef CPUTIME(value, howMany): #tru is both, false is just right\n if paddleY[1]+(paddleHeight[1]/2)>value:\n #print 'goingUp'\n paddleY[1]-=paddleSpeed[1]\n elif paddleY[1]+(paddleHeight[1]/2)<value:\n #print 'goingDown'\n paddleY[1]+=paddleSpeed[1]\n \n if howMany:\n if paddleY[0]+(paddleHeight[0]/2)>yPos:\n paddleY[0]-=paddleSpeed[0]\n \n if paddleY[0]+(paddleHeight[0]/2)<yPos:\n paddleY[0]+=paddleSpeed[0]\n \ndef randomizeMovement(mvt, rand):\n return mvt + random.randrange(0, rand)\n\ndef ballCheck(a, b, c, d):\n global goingDown\n global goingRight\n global xPos\n global yPos\n global randomness\n global scoreL\n global scoreR\n global pause\n global val\n global passed\n passed=False\n global passy\n goingDown=a\n goingRight=b\n xPos=c\n yPos=d\n \n if xPos>=940:\n '''\n print 'Expected: ', val\n print 'Real: ', yPos, goingRight, goingDown\n print 'Difference: ', val-yPos\n '''\n pass\n \n if yPos>=660 or yPos<=40:\n goingDown=-goingDown\n if yPos>=660:\n #print 'BOUNCE BOT:', xPos, yPos, goingRight, goingDown\n yPos=650\n else:\n #print 'BOUNCE TOP:', xPos, yPos, goingRight, goingDown\n yPos=50\n\n\n \n \n paddleTouchedVal=paddleTouched() #0 is not touched, 1 is right touched, 2 is left touched\n if paddleTouchedVal==1 or paddleTouchedVal==2:\n '''\n if paddleTouchedVal==1:\n pass\n '''\n goingRight=-goingRight\n randVal=random.randrange(0, randomness+1)\n if goingRight>=0:\n goingRight+=randVal\n elif goingRight<0:\n goingRight-=randVal\n if goingDown>=0:\n goingDown+=randVal\n elif goingDown<0:\n goingDown-=randVal \n \n goingDown+=random.randint(-randomness, randomness+1)\n\n passy=True\n \n if xPos>=930:\n xPos=920\n if xPos<=70:\n xPos=80\n \n if CPU1==True: val=simTester(False, xPos, yPos, goingRight, goingDown)\n #val=FORESEETHEFUTURE(False,xPos,yPos,goingRight,goingDown,900,720,0)\n \n if (goingRight<0 and xPos<800) and passy==True:\n passed=True \n \n if (goingRight>0 and xPos>200) and passy==True:\n passed=True\n \n if passed==True:\n val=simTester(False, xPos, yPos, goingRight, goingDown)\n #print '****************'\n passed=False\n passy=False\n \n if xPos>=970: \n scoreL+=1\n xPos=500\n yPos=350\n paddleY[1]=275\n paddleY[0]=275\n '''\n goingRight=randomizeMovement(0,startspeedR*1.5)\n goingDown=randomizeMovement(0,startspeedD*1.5) \n while not (goingRight<-startspeedR/2 or goingRight>startspeedR/2) and not (goingDown<-startspeedD/2 or goingDown>startspeedD/2):\n goingRight=randomizeMovement(0,startspeedR*1.5)\n goingDown=randomizeMovement(0,startspeedD*0.7) #alex this is much much better than your code b/c it takes the origi\n #thefuck is an origi this doesnt work\n ''' \n rVal=random.randrange(-2, 2)\n dVal=random.randrange(-2, 2)\n if rVal<0:\n goingRight=rVal-4\n elif rVal>=0:\n goingRight=rVal+4\n \n if dVal<0:\n goingDown=dVal-4\n elif dVal>=0:\n goingDown=dVal+4\n\n \n if CPU1==True: val=simTester(False, xPos, yPos, goingRight, goingDown)\n \n pause=True\n \n if xPos<=30:\n scoreR+=1\n xPos=500\n yPos=350\n paddleY[0]=275\n paddleY[1]=275\n '''\n goingRight=randomizeMovement(0,startspeedR*1.5)\n goingDown=randomizeMovement(0,startspeedD*1.5) \n while not (goingRight<-startspeedR/2 or goingRight>startspeedR/2) and not (goingDown<-startspeedD/2 or goingDown>startspeedD/2):\n goingRight=randomizeMovement(0,startspeedR*1.5)\n goingDown=randomizeMovement(0,startspeedD*0.7) #alex this is much much better than your code b/c it takes the original speed into consideration\n '''\n rVal=random.randrange(-2, 2)\n dVal=random.randrange(-2, 2)\n if rVal<0:\n goingRight=rVal-4\n elif rVal>=0:\n goingRight=rVal+4\n \n if dVal<0:\n goingDown=dVal-4\n elif dVal>=0:\n goingDown=dVal+4\n\n \n if CPU1==True: val=simTester(False, xPos, yPos, goingRight, goingDown)\n \n pause=True\n \n return goingDown, goingRight\n\ndef ballMove(a, b, c, d):\n global goingDown\n global goingRight\n global xPos\n global yPos\n global randomness\n goingDown=a\n goingRight=b\n xPos=c\n yPos=d\n if crazyball and loopnum % crazyDelay==0:\n goingRight=randomizeMovement(goingRight,randomness) #randomize every 5 frames for crazyball\n goingDown=randomizeMovement(goingDown,randomness)\n\n while goingRight==0:\n goingRight=randomizeMovement(goingRight,2) # this and\n while goingDown==0:\n goingDown=randomizeMovement(goingDown,2) # this are to prevent stalling\n\n xPos+=goingRight\n yPos+=goingDown\n return xPos, yPos\n\nregularFont = pygame.font.Font(None,60)\nbigFont = pygame.font.Font(None, 240)\n\npauseText = bigFont.render(\"Paused\", 0, BLUE.ROYALBLUE.full) # use .col() to get the actual color itself\ntextpos = pauseText.get_rect()\ntextpos.centerx = background.get_rect().centerx\ntextpos.centery = background.get_rect().centery\ns = pygame.Surface((1000,750)) # the size of your rect\ns.set_alpha(2) # alpha level\ns.fill((255,255,255)) # this fills the entire surface\n\nval=simTester(False, xPos, yPos, goingRight, goingDown)\nwhile not end:\n global val\n if not pause: # ingame\n if goingDown>maxDown:\n goingDown=maxDown\n if goingDown<-maxDown:\n goingDown=-maxDown\n if goingRight>maxRight:\n goingRight=maxRight\n if goingRight<-maxRight:\n goingRight=-maxRight\n loopnum+=1\n screen.blit(background, (0, 0))\n background.fill(BLUE.TEAL.full)\n myBallCenterPos = (int(xPos+0.5), int(yPos+0.5)) #normally casting to int goes to next lowest int, adding 0.5 makes behavior like a roun\n goingDown, goingRight = ballCheck(goingDown, goingRight, xPos, yPos)\n xPos, yPos = ballMove(goingDown, goingRight, xPos, yPos)\n paddleLeft.top=paddleY[0]\n paddleRight.top=paddleY[1]\n #pygame.draw.circle(background, BLACK.full, myBallCenterPos, 30)\n concentricCircle(background, [BLACK.full, RED.FUCHSIA.full], myBallCenterPos, [30, 15])\n pygame.draw.rect(background, YELLOW.GOLDENROD.full, paddleLeft)\n pygame.draw.rect(background, YELLOW.GOLDENROD.full, paddleRight)\n if CPU1: \n if not CPU2:\n CPUTIME(val, False)\n \n if CPU2:\n CPUTIME(val, True)\n \n \n else: # paused\n \n screen.blit(s, (0,0)) # (0,0) are the top-left coordinates\n screen.blit(pauseText, textpos) # use screen.blit to print to front apparently\n # ALL DA TIME\n \n screen.blit(regularFont.render(str(scoreL), 0, BLACK.full),(50,50))\n screen.blit(regularFont.render(str(scoreR), 0, BLACK.full),(923,50))\n pygame.display.flip()\n pygame.display.update()\n \n \n for event in pygame.event.get():\n if event.type == QUIT:\n end=True\n break\n elif event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n end=True\n pygame.quit()\n break\n if event.key == K_p: \n pause=not pause # pause or unpause\n if event.key==K_w:\n W=True\n if event.key==K_s:\n S=True\n if event.key==K_UP:\n UP=True\n if event.key==K_DOWN:\n DOWN=True\n if event.type==KEYUP:\n if event.key==K_w:\n W=False\n if event.key==K_s:\n S=False\n if event.key==K_UP:\n UP=False\n if event.key==K_DOWN:\n DOWN=False\n if not pause:\n if not CPU2:\n if W:\n paddleY[0]-=paddleSpeed[0]\n if paddleY[0]<0: paddleY[0]=0\n if S:\n paddleY[0]+=paddleSpeed[0]\n if paddleY[0]+paddleHeight[0]>700: paddleY[0]=700-paddleHeight[0]\n if not (CPU1 or CPU2):\n if UP:\n paddleY[1]-=paddleSpeed[1]\n if paddleY[1]<0: paddleY[1]=0\n if DOWN:\n paddleY[1]+=paddleSpeed[1]\n if paddleY[1]+paddleHeight[1]>700: paddleY[1]=700-paddleHeight[1]\n \n fpsClock.tick(FPS)\n\n################################### C H A T ###################################\n'''\nsay your name then a colon, then message\nALEX: I have an idea to eliminate processing power. We can modify it so it does a certain constant amount of\n iterations through the prediction each frame after it hits a paddle, but it does not finish in one. \n (It may, for instance, calculate 10 frames in advance every frame, but every time work with the same data\n that it got once it hit the paddle, it just progresses in the simulation using the same data as the frames\n are progressing)\nGABRIEL: Your shit's fucked with fast speeds. I beat it 10-6 and the computer (doing simplest ai) beat it 10-3.\n You probably didn't account for the ball's radius or something. Also, I fixed the points because you\n couldn't score on one side, but occasionally it throws me \n values[counter][0]=xPosy\n IndexError: list index out of range\n so yeah, fix your shit\n\nALEX: I did. It's fucking boss. The stupid AI lost 25-0 when it had a size and speed advantage. I changed it slightly i think but try your best. \n Give it 5 speed, yourself 10 speed, and yourself 200 height while it has 150 height and it will still beat you. Give youself\n more advantage if you want. Right now it is set to half your speed. \n\n'''\n###############################################################################\n" }, { "alpha_fraction": 0.5897436141967773, "alphanum_fraction": 0.7564102411270142, "avg_line_length": 6.181818008422852, "blob_id": "0863e7fdc8c5c4d782fdfc40e4c6aa307d40af6d", "content_id": "5a4e523bff41fe58ef88438bcfc1a252971fb240", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 78, "license_type": "no_license", "max_line_length": 43, "num_lines": 11, "path": "/README.md", "repo_name": "alxcoh/Peioa3yhedniuw4nrxdiwuyahebnquiekjhba2niquyjkehadlm2idjniuy4wkgjdbhniabhn7iguahj2qagny427dy42yfgnyda", "src_encoding": "UTF-8", "text": "dasch ist el projects we are good TEST ING \nTESITING\n1\n2\n3\n3\n33\n3\n3\n32123\nvkeb" } ]
6
JorgeRios/aplicacion
https://github.com/JorgeRios/aplicacion
6f2f16c99b05340c7d292191f30e5cced2abc638
fa0fb3255f75be7f1eaa635188e2cdaf118fed29
4db1ff59dd7bf4ad229670e376db7682252a2a4b
refs/heads/master
2016-09-03T02:32:22.458182
2013-10-17T14:33:34
2013-10-17T14:33:34
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6661620140075684, "alphanum_fraction": 0.6707040071487427, "avg_line_length": 22.175437927246094, "blob_id": "180b41429f275ff4e631cfc9f4e22da91334dfae", "content_id": "75a5056592ebc20fd629f2c59819a47e24cb7a3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1321, "license_type": "no_license", "max_line_length": 95, "num_lines": 57, "path": "/models.py", "repo_name": "JorgeRios/aplicacion", "src_encoding": "UTF-8", "text": "from sqlalchemy import (\n Column,\n Index,\n Integer,\n Text,\n String,\n )\n\nfrom sqlalchemy.ext.declarative import declarative_base\n\nfrom sqlalchemy.orm import (\n scoped_session,\n sessionmaker,\n )\n\nfrom zope.sqlalchemy import ZopeTransactionExtension\n\nDBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))\nBase = declarative_base()\n\n\nclass MyModel(Base):\n __tablename__ = 'models'\n id = Column(Integer, primary_key=True)\n name = Column(Text)\n value = Column(Integer)\n\n def __init__(self, name, value):\n self.name = name\n self.value = value\n\nclass Usuario(Base):\n __tablename__ = 'usuario'\n id=Column(Integer, primary_key=True)\n user=Column(String)\n password=Column(String)\n\n def __init__(self,user,password):\n \tself.user=user\n\tself.password=password\n\n @property\n def json(self):\n\treturn dict(id=self.id,user=self.user.encode(\"utf-8\"),password=self.password.encode(\"utf-8\") )\n\nclass Comentario(Base):\n __tablename__ ='comentario'\n id=Column(Integer, primary_key=True)\n cuerpo=Column(String)\n \n def __ini__(self,id,body):\n\tself.id=id\n\tself.body=body\n @property\n def json(self):\n\treturn dict(id=self.id, body=self.body.enconde('utf-8'))\t\nIndex('my_index', MyModel.name, unique=True, mysql_length=255)\n" }, { "alpha_fraction": 0.6619898080825806, "alphanum_fraction": 0.6626275777816772, "avg_line_length": 23.5, "blob_id": "ca4da4a5eedea3601246bde91ae312e82daee18e", "content_id": "a379f28a370be4ec493ce1131e2523d7d95600d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1568, "license_type": "no_license", "max_line_length": 108, "num_lines": 64, "path": "/aplicacion/models.py", "repo_name": "JorgeRios/aplicacion", "src_encoding": "UTF-8", "text": "from sqlalchemy import (\n Column,\n Integer,\n Text,\n String,\n ForeignKey\n )\n\nfrom sqlalchemy.ext.declarative import declarative_base\n\nfrom sqlalchemy.orm import (\n scoped_session,\n sessionmaker,\n relationship,\n backref\n )\n\nfrom zope.sqlalchemy import ZopeTransactionExtension\n\nDBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))\nBase = declarative_base()\n\n\nclass MyModel(Base):\n __tablename__ = 'models'\n id = Column(Integer, primary_key=True)\n name = Column(Text, unique=True)\n value = Column(Integer)\n\n def __init__(self, name, value):\n self.name = name\n self.value = value\n\nclass Usuario(Base):\n __tablename__ = 'usuarios'\n id = Column(Integer, primary_key=True)\n user = Column(String)\n password=Column(String)\n def __init__(self, user, pasword):\n self.user = user\n\tself.password = password \n\n @property\n def json(self):\n return dict(id=self.id, user=self.user.encode(\"utf-8\"), password=self.password.encode('utf-8'))\n\n @property\n def nombre(self):\n return self.user\n\nclass Comentario(Base):\n __tablename__ = 'comentarios'\n id = Column(Integer, primary_key=True)\n id_user = Column(Integer, ForeignKey('usuarios.id'))\n comentario=Column(String)\n\n user= relationship('Usuario', backref=backref('comentarios', order_by=id))\n\n def __init__(self,comentario):\n self.comentario=comentario\n\n @property\n def json(self):\n return dict(id=self.id, id_user=self.id_user, comentario=self.comentario)\n" } ]
2
michellelfloyd/python_projects
https://github.com/michellelfloyd/python_projects
e3c7172e4e03fc303bf205ca68df2284d44af295
478a8b0ef69a5ba80afad550db467593da3e5de9
9579b9b0d825c4b12c1f4c40e8c781ac9fe83fa8
refs/heads/master
2020-06-02T19:29:18.886246
2014-12-09T01:31:42
2014-12-09T01:31:42
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5871710777282715, "alphanum_fraction": 0.6184210777282715, "avg_line_length": 16.371429443359375, "blob_id": "7869b706b6d424eeb6a6a65c5a915daf5b73690e", "content_id": "388a66249b30552d1f682a9f844c79495d4cda01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 608, "license_type": "no_license", "max_line_length": 66, "num_lines": 35, "path": "/sample2.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "\nfrom array import array\n\n# Create an array for the counters.\nzeros = [0 for x in range(127)]\n\n\ntheCounters = array( 'i', zeros )\n\n# for i in range(len(theCounters)):\n# theCounters[i]=0\n# print len(theCounters)\n\n# Open the text file for reading and extract each letter.\n\ntheFile = open( 'project_5.py', 'r' )\n\nfor line in theFile :\n\n for letter in line :\n\n code = ord( letter )\n\n theCounters[code] += 1\n\n# Close the file\n\ntheFile.close()\n\n# Print the results.\n\nfor i in range( 26 ) :\n\n print( \"%c - %4d %c - %4d\" % \\\n\n (chr(65+i), theCounters[65+i], chr(97+i), theCounters[97+i]) )" }, { "alpha_fraction": 0.5847457647323608, "alphanum_fraction": 0.5915254354476929, "avg_line_length": 23.625, "blob_id": "af67582440b3cc1794a485d325de3eb472795396", "content_id": "6f512c743568f2bfb5bbf216b8cf886c2eaa6790", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 590, "license_type": "no_license", "max_line_length": 112, "num_lines": 24, "path": "/inheritance_in_class.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "class Person(object):\n\n def __init__(self,name,age, role=\"\"):\n self.name = name\n self.age = age\n self.role = role\n def __str__(self):\n return \"My name is %s. I am %d years old. I am %s at ABC Primary School.\"%(self.name,self.age,self.role)\n\nclass Student(Person):\n def __init__(self, name, age):\n super(Student, self).__init__(name, age,'studying')\n\nclass Teacher(Person):\n def __init__(self,name, age):\n super(Teacher, self).__init__(name, age,'teaching')\n\n\n\nsteve = Student('Steve', 10)\nbob = Teacher('Bob', 65)\n\nprint steve\nprint bob" }, { "alpha_fraction": 0.4727272689342499, "alphanum_fraction": 0.5090909004211426, "avg_line_length": 17.33333396911621, "blob_id": "e403d76a61cefd4423589d7df4bf483615ecb2d7", "content_id": "4c2ac91891dac5ae06f82b723e1082e895be5db3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 275, "license_type": "no_license", "max_line_length": 66, "num_lines": 15, "path": "/in class recursion sum.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "#def sum_list(l):\n # \"\"\"\"returns the sums of the contents of a list of numbers \"\"\"\n # sum = 0\n # for i in l:\n # sum += i\n # return sum\n\n\ndef sum_list(l):\n if not l:\n return 0\n\n return l.pop() + sum_list(l)\n\nprint sum_list([4, 6, 3, 6, 7, 4, 3, 8])\n" }, { "alpha_fraction": 0.530434787273407, "alphanum_fraction": 0.5380434989929199, "avg_line_length": 19, "blob_id": "22df002722ac19b1b5e6150c705cb6d8c0a0c262", "content_id": "73e503cb34cb365feee507c7d61f710bda7c4d2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 920, "license_type": "no_license", "max_line_length": 71, "num_lines": 46, "path": "/project_6.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "import string\nimport random\n\n\nf = open(\"project_six.dat\", \"w\")\n\n\ndef random_string(size=50, chars=string.ascii_letters + string.digits):\n final_string = ''\n for num in range(size):\n random_char = random.choice(chars)\n final_string += random_char\n f.write(final_string + \"\\n\")\n\n\ndef generate_strings():\n for x in range(0, 10):\n random_string()\n\n\ngenerate_strings()\n\n\ncars = {}\n\nf = open(\"project_six.dat\", \"r\")\nfor line in f:\n cleaned_line = line.replace(\"\\n\", \"\")\n print \"******* Begin Random String *******\"\n print cleaned_line\n for char in cleaned_line:\n if char in cars:\n cars[char] += 1\n else:\n cars[char] = 1\n\n # build final count string\n final_count = ''\n for key in cars:\n final_count += \"%s ==> %s; \" % (key, cars[key])\n print final_count\n print\"***********************************\"\n cars = {}\n\n\nf.close()\n" }, { "alpha_fraction": 0.6529411673545837, "alphanum_fraction": 0.6627451181411743, "avg_line_length": 29, "blob_id": "1934d5eb28963728df7b8d60ebe522326402ced9", "content_id": "68996d296882fd457c3481f1620171ff119a7177", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 510, "license_type": "no_license", "max_line_length": 66, "num_lines": 17, "path": "/project_5.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "import time\nimport datetime\nf = open(\"dates.txt\", \"r\")\n\nfor t in f:\n #datetime is function converting epoch second to date and time\n #time.time is now in epoch seconds(float)\n now = datetime.datetime.fromtimestamp(time.time())\n now_e = time.mktime(now.timetuple())\n diff = float(now_e) - float(t)\n past = datetime.date.fromtimestamp(float(t))\n sec_day = 86400\n day_ago = diff / sec_day\n pretty_ago = int(round(day_ago))\n print past, 'happened', pretty_ago, 'days ago.'\n\nf.close()\n" }, { "alpha_fraction": 0.5751789808273315, "alphanum_fraction": 0.5799522399902344, "avg_line_length": 25.1875, "blob_id": "f6e85e65be05f764b529c6cfa7f91df4b2e8d439", "content_id": "b5a4adc7405673c29c856fae9d3d925b84e27f93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 419, "license_type": "no_license", "max_line_length": 103, "num_lines": 16, "path": "/inheritance2_in_class.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "class Job(object):\n def __init__(self, title):\n self.title = title\n\n\nclass Employee(object):\n def __init__(self, name, age, title):\n self.name = name\n self.age = age\n self.job = Job(title)\n\n def __str__(self):\n return \"My name is %s, I am %d years old and I am a %s\" % (self.name, self.age, self.job.title)\n\nmorgan = Employee('Morgan Williams', 24, 'software developer')\nprint morgan\n" }, { "alpha_fraction": 0.7079365253448486, "alphanum_fraction": 0.7174603343009949, "avg_line_length": 15.578947067260742, "blob_id": "68ebf8865f296924d7cbe5819c795574a0986877", "content_id": "a368ed96019616a6eda7960dd2d9f97e10b29ff9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 315, "license_type": "no_license", "max_line_length": 51, "num_lines": 19, "path": "/sample.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "from array import Array\n\nimport random\n\n# The constructor is called to create the array.\n\nvalueList = Array(100)\n\n# Fill the array with random floating-point values.\n\nfor i in range(len(valueList)):\n\n valueList[i] = random.random()\n\n# Print the values, one per line.\n\nfor value in valueList:\n\n print( value )\n" }, { "alpha_fraction": 0.5902438759803772, "alphanum_fraction": 0.7089430689811707, "avg_line_length": 54.90909194946289, "blob_id": "006eeb87325e32fdb66a3bfc718b6e073054a1a6", "content_id": "f4f147db01c76e0df8bd013dfa3cb8144e481c72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 615, "license_type": "no_license", "max_line_length": 112, "num_lines": 11, "path": "/project_3.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "x = int(float(raw_input('Please enter a speed in miles/hour:')))\n\nprint 'You entered', x, 'miles/hour'\n#There are 1609.34 meters in a mile, 117.647 barleycorn in a meter, 24 hours in a day\nprint 'That is equal to', 1609.344 * 117.647 * 24 * x, 'barleycorn/day'\n#There are 1760 yards in a mile, a furlong is 220 yards, there are 8 furloughs in a mile, a fortnight is 2 weeks\nprint 'It is equal to', 8 * 336 * x, 'furlongs/fortnight'\n#1 mach is 761.2 mph\nprint 'Converted to a mach number', x / 761.2\n#The speed of light is 670616629 mph\nprint 'Converted to the percentage of speed of light', 100 * (x / 670616629.0)\n" }, { "alpha_fraction": 0.4684014916419983, "alphanum_fraction": 0.535315990447998, "avg_line_length": 15.8125, "blob_id": "4750084d9a0f5a3842643015fc9a77ede67a797a", "content_id": "3c9dfa2b93c770ae644b2fdb78b9735a3539eea3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 269, "license_type": "no_license", "max_line_length": 35, "num_lines": 16, "path": "/in class generator ex 13.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "def frange(start, stop, increment):\n while start < stop:\n\n yield start\n start += increment\n\nfor n in frange(0, 4, 0.5):\n print n\n\nx = frange(0, 7, 0.75)\n\ny = frange(0, 10000, 250)\n\n# while True:\n# print x.next()\n# print y.next()\n" }, { "alpha_fraction": 0.5163934230804443, "alphanum_fraction": 0.5430327653884888, "avg_line_length": 26.11111068725586, "blob_id": "f343011cff5a00b04d93d67db764de95d647b4b2", "content_id": "557f173349c8f46518e36bcd91ac4db53e6f0c3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 488, "license_type": "no_license", "max_line_length": 49, "num_lines": 18, "path": "/project_7.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "\nf = open(\"project_seven.dat\", \"w\")\n\nprint \"**********************\"\nprint \"Project 7 Menu\"\nprint \"**********************\"\nprint \"1. Write input to file\"\nprint \"2. Write input to screen\"\nprint \"3. Quit\"\n\nwhile input != \"3\":\n input = raw_input(\"Enter your choice [1-3]:\")\n if input == \"1\":\n input1 = raw_input(\"Enter a phrase:\")\n f.write(input1)\n elif input == \"2\":\n input2 = raw_input(\"Enter a phrase:\")\n print input2\nprint \"This program will now quit\"" }, { "alpha_fraction": 0.6213991641998291, "alphanum_fraction": 0.6687242984771729, "avg_line_length": 27.647058486938477, "blob_id": "861d2ab709d25561f9b767f398f7cddb8b91339a", "content_id": "307c0c25d6a26a14de26baf15c117c21200a87be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 486, "license_type": "no_license", "max_line_length": 94, "num_lines": 17, "path": "/project_4.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "try:\n x = int(raw_input('Please enter number of years into the future:'))\nexcept:\n x = int(raw_input('Please enter a number:'))\nsec_minute = 60\nsec_hour = sec_minute * 60\nsec_day = sec_hour * 24\nsec_year = sec_day * 365\nbirths = sec_year / 7\ndeath = sec_year / 13\nnew_immigrant = sec_year / 35\nt = births - death\nt += new_immigrant\nchange = t * x\nprint 'You entered:', x\nprint 'In', x, 'years the population will change by', change, 'to make it', 307357870 + change\nprint sec_year" }, { "alpha_fraction": 0.6337385773658752, "alphanum_fraction": 0.6930091381072998, "avg_line_length": 46, "blob_id": "960e66bfb3b65458002dc7aac39372313f41b17f", "content_id": "d0c5a9376ae99e23ac12914b15637621e5bbfd73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 658, "license_type": "no_license", "max_line_length": 71, "num_lines": 14, "path": "/project_2.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "try:\n x = int(float(raw_input('Please enter number of gallons of gas:')))\nexcept:\n x = int(float(raw_input('Please enter a number:')))\nprint 'You entered', x, 'gallons'\n# There are 3.7854 liters in a gallon\nprint 'This is the equivalent of', x * 3.7854, 'liters'\n# It takes 1 barrel of oil to make 19.5 gallons of gas\nprint 'It takes', x / 19.5, 'barrels of oil to make that much gas'\n#One gallon of gas produces 20 pounds of co2\nprint 'That much gas produces', x * 20, 'pounds of CO2'\n#One gallon of ethanol produces 75700 BTUs\nprint 'That much ethanol produces', x * 75700, 'BTUs'\nprint 'That much gas costs $', x * 4.00, 'based on $4.00 per gallon'\n" }, { "alpha_fraction": 0.38333332538604736, "alphanum_fraction": 0.5083333253860474, "avg_line_length": 6.800000190734863, "blob_id": "e4479ea656148627044531aa31236622c59ef482", "content_id": "d89632a967d9855ffe0fd7107c2da7dade7a1639", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 120, "license_type": "no_license", "max_line_length": 30, "num_lines": 15, "path": "/euler.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "\nnum = 1\nnum2 = 2\n\nfor i in range(0, 4000000, 2):\n\n\n thr = num + num2\n num = num2\n num2 = thr\n\n\n\n\n\nprint thr\n\n\n" }, { "alpha_fraction": 0.5916334390640259, "alphanum_fraction": 0.5916334390640259, "avg_line_length": 40.33333206176758, "blob_id": "76bac6ab531ff97bee900f899a6af4bce1979816", "content_id": "b6c99a6af5eb3b37057fb2b3ae335ea0a76dc2c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 502, "license_type": "no_license", "max_line_length": 88, "num_lines": 12, "path": "/project_1.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "try:\n x = int(raw_input(\"Please enter your first integer: \"))\nexcept:\n x = int(raw_input(\"Please enter an integer:\"))\ntry:\n y = int(raw_input(\"Please enter your second integer:\"))\nexcept:\n y = int(raw_input(\"Please enter an integer:\"))\nprint \"The sum of\", x, \"and\", y, \"is:\", x + y\nprint \"The result of subtracting\", y, \"from\", x, \"is:\", x - y\nprint \"The product of\", x, \"and\", y, \"is:\", x * y\nprint \"The quotient of\", x, \"divided by\", y, \"is:\", x / y, \"with a remainder of:\", x % y\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5957446694374084, "alphanum_fraction": 0.6063829660415649, "avg_line_length": 28.33333396911621, "blob_id": "35edca8a9dc5839e1ec5c142ee131d7d419611d0", "content_id": "e5f65a6526448247cb431b58f469b22963d7207c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 94, "license_type": "no_license", "max_line_length": 36, "num_lines": 3, "path": "/project_8.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "with open(\"project_8.dat\")as player:\n for list in sorted(player):\n print list\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5341246128082275, "alphanum_fraction": 0.574184000492096, "avg_line_length": 24, "blob_id": "e41baac2048425c93a61debeebce113f9d30f9f6", "content_id": "f9eab3a1b57bd3efbe96660ffffd98673ad30976", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 674, "license_type": "no_license", "max_line_length": 77, "num_lines": 27, "path": "/object oriented time.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "class Time(object):\n def __init__(self,hours,minutes,seconds):\n self.hours = hours\n self.minutes = minutes\n self.seconds = seconds\n\n def __str__(self):\n return \"%d:%d:%d\" %(self.hours, self.minutes, self.seconds)\n\n def __cmp__(self,other):\n left_time = self.hours * 1000 + self.minutes * 100 + self.seconds\n right_time = other.hours * 1000 + other.minutes * 100 + other.seconds\n if left_time < right_time:\n return -1\n elif left_time > right_time:\n return 1\n return 0\n\nthen = (4 , 12, 32)\nnow = (7, 32, 54)\n\nprint now\nprint then\n\nprint now > then\nprint now < then\nprint now == then" }, { "alpha_fraction": 0.6314102411270142, "alphanum_fraction": 0.6378205418586731, "avg_line_length": 16.33333396911621, "blob_id": "bf00a83fe2c034b4267a58d1880f1e1a239cd422", "content_id": "73d8cec0f195e7a9ee13a0e317cd251fb73aa33d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 312, "license_type": "no_license", "max_line_length": 52, "num_lines": 18, "path": "/in class exceptions.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "def fileOpen(self, file):\n open(file)\n\n\n\ndef fileOpenAgain(self):\n\n try:\n open(\"non_existent_file.txt\")\n except IOError:\n print \"Error: can\\'t find file or read data\"\n\ntry:\n fileOpen(1, \"non_existent_file.txt\")\nexcept:\n print \"Error: can\\'t find file or read data\"\n\nfileOpenAgain(1)\n" }, { "alpha_fraction": 0.5830815434455872, "alphanum_fraction": 0.6132930517196655, "avg_line_length": 16.473684310913086, "blob_id": "df38a14c8a37d60c7986bcc4eed7747c080c01d3", "content_id": "5746df6ae99e754186ada1072ed10dab55bf50be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 331, "license_type": "no_license", "max_line_length": 45, "num_lines": 19, "path": "/in class reursion exponent.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "def exponent(base, exp, current_value=1):\n if exp == 0:\n return current_value\n current_value *= base\n exp -= 1\n\n return exponent(base, exp, current_value)\n\nprint exponent(5, 6)\n\n\n\ndef raising_to(base, exp):\n if exponent == 0:\n return 1\n return base * raising_to(base, exp -1)\n\n\nprint raising_to(2,3)" }, { "alpha_fraction": 0.44954127073287964, "alphanum_fraction": 0.46483179926872253, "avg_line_length": 14.619047164916992, "blob_id": "a864825c3b0ec6c7b92d069ed34760a12574316a", "content_id": "903695529da2304255423d0057477dc9f2adfd44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 327, "license_type": "no_license", "max_line_length": 37, "num_lines": 21, "path": "/in class generator.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "def primes():\n i = 1\n\n while True:\n\n for divisor in range(i/2, i):\n if i % divisor == 0:\n i += 1\n\n break\n else:\n yield i\n i += 1\n\nprime_gen = primes()\n\n\nprint prime_gen.next()\nprint prime_gen.next()\nprint prime_gen.next()\nprint prime_gen.next()" }, { "alpha_fraction": 0.5130784511566162, "alphanum_fraction": 0.5352112650871277, "avg_line_length": 34.35714340209961, "blob_id": "bb60175ea761ec3109d45af5f22455c8bcd05df7", "content_id": "b187fb9cc7cccba47a1e62631e99257ca1899ccd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 497, "license_type": "no_license", "max_line_length": 61, "num_lines": 14, "path": "/object_oriented class intro.py", "repo_name": "michellelfloyd/python_projects", "src_encoding": "UTF-8", "text": "class Person(object):\n def __init__(self, name, age, birthday, address):\n self.name = name\n self.age = age\n self.birthday = birthday\n self.address = address\n\n def __str__(self):\n return 'Person name: ' + self.name + \\\n '\\nPerson age: ' + str(self.age) + \\\n '\\nPerson birthday: ' + str(self.birthday) + \\\n '\\nPerson address: '+ str(self.address)\nperson = Person('Bob', 45,'08/31/56', '123 Fake Way')\nprint person\n\n\n" } ]
20
malikkhalil/Random_Code
https://github.com/malikkhalil/Random_Code
c6314f9540c3085d043aee35015868767c3a26ce
1fd9ab7b85e58e7f11ada4886a46bdbe23fdbecc
e5f5f1214e64e1331dac33d7ec66c7ba86f8e064
refs/heads/master
2021-01-01T05:15:02.460404
2016-05-01T03:34:50
2016-05-01T03:34:50
57,186,566
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6124048233032227, "alphanum_fraction": 0.6274070739746094, "avg_line_length": 24.970930099487305, "blob_id": "a51fb08464b43b226ddd4d6aadda6d9b639c584c", "content_id": "5f3a4f45834a867b1c404c2fbba5a17a813049d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4466, "license_type": "no_license", "max_line_length": 79, "num_lines": 172, "path": "/Tetris.py", "repo_name": "malikkhalil/Random_Code", "src_encoding": "UTF-8", "text": "from os import system\nfrom random import randint\nfrom sys import exit\nROWS = 10\nCOLUMNS = 10\nLEGAL_INPUTS =['a','s','d','r']\n\nclass Tetris:\n\tdef __init__(self):\n\t\t\"\"\"\n\t\t\tConstructor. Sets up the playing field.\n\t\t\"\"\"\n\t\tself.matrix = [ ['-']*COLUMNS for x in range(ROWS)]\n\t\tself.round = 1\n\t\tself.current_letter = 'a'\n\tdef play(self):\n\t\t\"\"\"\n\t\t\tDisplays controls and initiates the game.\n\t\t\"\"\"\n\t\tprint((\"Welcome to Malik's Tetris game.\"\n\t\t\t\"\\nCommands:\"\n\t\t\t\"\\na : move left\"\n\t\t\t\"\\ns : do nothing\"\n\t\t\t\"\\nd : move right\"\n\t\t\t\"\\nr : rotate clockwise -- not implemented yet\"\n\t\t\t\"\\nMemorize above then type 'standy' to play. \"))\n\t\tif input().strip() == \"standy\":\n\t\t\tself._game_loop()\n\n\tdef _game_loop(self):\n\t\t\"\"\"\n\t\t\tGame loop.\n\t\t\"\"\"\n\t\tsystem(\"clear\")\n\t\tself.current_block = Block()\n\t\tself.current_block.set_letter(self.current_letter)\n\t\tself._draw_block(self.current_block)\n\t\tself.display_board()\n\t\twhile True:\n\t\t\tcmd = None\n\t\t\twhile(cmd not in LEGAL_INPUTS):\n\t\t\t\tprint(\"\\nEnter command: \", end=\"\")\n\t\t\t\tcmd = input().strip()\n\t\t\told_location = tuple((tuple(x) for x in self.current_block.get_locations()))\n\t\t\tif cmd == 'a':\n\t\t\t\tself._erase_block(self.current_block)\n\t\t\t\tself.current_block.left()\n\t\t\telif cmd == 'd':\n\t\t\t\tself._erase_block(self.current_block)\n\t\t\t\tself.current_block.right()\n\t\t\telif cmd == 's':\n\t\t\t\tself._erase_block(self.current_block)\n\t\t\t\tself.current_block.nothing()\n\t\t\telif cmd == 'r':\n\t\t\t\tself._erase_block(self.current_block)\n\t\t\t\tself.current_block.rotate()\n\t\t\tif self._check_collision(self.current_block):\n\t\t\t\tself.current_block.set_locations([list(x) for x in list(old_location)])\n\t\t\t\tself._draw_block(self.current_block)\n\t\t\t\tself.current_block = Block()\n\t\t\t\tself._next_letter()\n\t\t\t\tself.current_block.set_letter(self.current_letter)\n\t\t\t\tif self._check_collision(self.current_block):\n\t\t\t\t\tprint(\"Game over!\")\n\t\t\t\t\texit(0)\n\t\t\tself._draw_block(self.current_block)\n\t\t\tself.display_board()\n\t\t\tself.round += 1\n\n\n\tdef _check_collision(self, block):\n\t\t\"\"\"\n\t\t\tTests if the passed block at its proposed new location\n\t\t\twould collide with an existing block.\n\t\t\"\"\"\n\t\tif isinstance(block, Block):\n\t\t\tfor location in block.get_locations():\n\t\t\t\tif self.matrix[location[0]][location[1]] != '-':\n\t\t\t\t\treturn True\n\t\t\t\telif location[0] == ROWS-1:\n\t\t\t\t\treturn True\n\t\t\treturn False\n\t\telse:\n\t\t\traise Exception(\"Block object expected\")\n\n\tdef _erase_block(self, block):\n\t\t\"\"\"\n\t\t\tErase a block's old position before it moves\n\t\t\"\"\"\n\t\tif isinstance(block, Block):\n\t\t\tfor location in block.get_locations():\n\t\t\t\tself.matrix[location[0]][location[1]] = '-'\n\t\telse:\n\t\t\traise Exception(\"Block object expected\")\n\n\tdef _draw_block(self, block):\n\t\t\"\"\"\n\t\t\tDraws the current block to the board\n\t\t\"\"\"\n\t\tif isinstance(block, Block):\n\t\t\tfor location in block.get_locations():\n\t\t\t\tif self.matrix[location[0]][location[1]] != '-':\n\t\t\t\t\traise Exception(\"Oops, this move shouldn't have been allowed.\")\n\t\t\t\telse:\n\t\t\t\t\tself.matrix[location[0]][location[1]] = self.current_letter\n\t\telse:\n\t\t\traise Exception(\"Block object expected\")\n\tdef display_board(self):\n\t\t\"\"\"\n\t\t\tPrints out the game board.\n\t\t\"\"\"\n\t\tsystem(\"clear\")\n\t\tprint(\"Round:\", str(self.round))\n\t\tfor i in range(COLUMNS+1):\n\t\t\tprint(str(i) + \" \", end=\"\")\n\t\tfor i in range(ROWS-1):\n\t\t\tprint(\"\\n\" + str(i+1), end=\"\")\n\t\t\tfor j in range(COLUMNS):\n\t\t\t\tprint(\" \" + str(self.matrix[i][j]), end=\"\")\n\t\tprint() \n\n\tdef _next_letter(self):\n\t\t\"\"\"\n\t\t\tSets the new char for the next block\n\t\t\"\"\"\n\t\tself.current_letter = chr(ord(self.current_letter)+1)\n\n\nclass Block:\n\tPIECES = ( ((0, 0), (1, 0), (2, 0), (3, 0)), \n\t\t\t\t((0, 0), (1, 0), (2, 0), (2, 1)), \n\t\t\t\t((0, 1), (1, 1), (2, 0), (2, 1)), \n\t\t\t\t((0, 0), (0, 1), (1, 0), (1, 1)) )\n\tdef __init__(self):\n\t\tself.locations = [list(x) for x in list(self.PIECES[randint(0, 3)])]\n\n\tdef get_locations(self):\n\t\treturn self.locations\n\n\tdef set_locations(self, new_locations):\n\t\tself.locations = new_locations\n\n\tdef nothing(self):\n\t\tfor location in self.locations:\n\t\t\tlocation[0]+=1\n\n\tdef left(self):\n\t\tfor location in self.locations:\n\t\t\tif location[1] == 0:\n\t\t\t\tself.nothing()\n\t\t\t\treturn\n\t\tfor location in self.locations:\n\t\t\tlocation[1] = location[1] - 1\n\t\tself.nothing()\n\tdef right(self):\n\t\tfor location in self.locations:\n\t\t\tif location[1] == COLUMNS-1:\n\t\t\t\tself.nothing()\n\t\t\t\treturn\n\t\tfor location in self.locations:\n\t\t\tlocation[1] = location[1] + 1\n\t\tself.nothing()\n\tdef rotate(self):\n\n\t\tself.nothing()\n\tdef set_letter(self, letter):\n\t\tself.letter = letter\n\n\nif __name__ == '__main__':\n\tgame = Tetris()\n\tgame.play()" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.625, "avg_line_length": 14, "blob_id": "c1c055d6031d09215823b57afe61aa479b99b634", "content_id": "01c4d5ecdf297ee66c1d65f895db22ba029a4f47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 16, "license_type": "no_license", "max_line_length": 14, "num_lines": 1, "path": "/README.md", "repo_name": "malikkhalil/Random_Code", "src_encoding": "UTF-8", "text": "# Random Code! \n" }, { "alpha_fraction": 0.6356139779090881, "alphanum_fraction": 0.6480944752693176, "avg_line_length": 25.39411735534668, "blob_id": "9222dab979877043aa07d6ece17fda6a27781d8c", "content_id": "d4c27de4530e0bf8cf8c2a7804d09c5d0643660f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4487, "license_type": "no_license", "max_line_length": 95, "num_lines": 170, "path": "/ConnectFour.py", "repo_name": "malikkhalil/Random_Code", "src_encoding": "UTF-8", "text": "#Connect four\n\nfrom os import system\nfrom sys import exit\nDEFAULT_NUM_ROWS = 6\nDEFAULT_NUM_COLS = 7\nUNOCCUPIED_SPACE = 0\n\nclass Space:\n\tdef __init__(self):\n\t\t\"\"\"\n\t\t\tCreates a space class. If player is -1, the space is unoccupied \n\t\t\"\"\"\n\t\tself.player = UNOCCUPIED_SPACE\n\tdef set_player(self, player):\n\t\t\"\"\"\n\t\t\tSets the player, player parameter should be an int\n\t\t\"\"\"\n\t\tself.player = player\n\n\tdef __str__(self):\n\t\treturn str(self.player)\n\nclass ConnectFour:\n\tdef __init__(self):\n\t\tself.board = [[Space() for x in range(DEFAULT_NUM_COLS)] \n\t\tfor y in range(DEFAULT_NUM_ROWS)]\n\tdef print_board(self):\n\t\tfor i in range(len(self.board)):\n\t\t\tfor j in range(len(self.board[0])):\n\t\t\t\tprint(self.board[i][j], end=\"\")\n\t\t\tprint()\n\tdef insert_piece(self, player, column):\n\t\t\"\"\"\n\t\t\tInserts a piece for player player at given column\n\t\t\tReturns false if column is already full, else true\n\t\t\"\"\"\n\t\tindex = 0\n\t\tif str(self.board[index][column]) != str(UNOCCUPIED_SPACE): \n\t\t\treturn False\n\t\twhile str(self.board[index][column]) == str(UNOCCUPIED_SPACE) and index < DEFAULT_NUM_ROWS-1:\n\t\t\tindex = index + 1\n\t\tif str(self.board[index][column]) != str(UNOCCUPIED_SPACE):\n\t\t\tindex -=1\n\t\tself.board[index][column].set_player(player)\n\t\treturn [index, column]\n\tdef _prompt_input(self, player):\n\t\tprint(\"\\nPlayer {}, input column to insert piece: \".format(str(player))\n\t\t\t, end=\"\")\n\t\treturn int(input().strip())\n\n\tdef _check_winner(self, player, index=[]):\n\t\treturn self._check_horizontal(player, index) or \\\n\t\tself._check_vertical(player, index) or \\\n\t\tself._check_diagonal(player, index)\n\n\tdef _check_diagonal(self, player, index=[]):\n\t\tconsecutive_pieces = 1\n\t\trow, col = index\n\t\t#check left diagonal\n\t\twhile row < DEFAULT_NUM_ROWS-1 and col > 0:\n\t\t\trow +=1\n\t\t\tcol -=1\n\t\t\tif str(self.board[row][col]) == str(player):\n\t\t\t\tconsecutive_pieces += 1\n\t\t\t\tif consecutive_pieces == 4:\n\t\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tconsecutive_pieces = 1\n\t\trow, col = index\n\t\twhile row > 0 and col < DEFAULT_NUM_COLS-1:\n\t\t\trow -=1\n\t\t\tcol +=1\n\t\t\tif str(self.board[row][col]) == str(player):\n\t\t\t\tconsecutive_pieces += 1\n\t\t\t\tif consecutive_pieces == 4:\n\t\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tconsecutive_pieces = 1\n\t\treturn False\n\n\n\tdef _check_horizontal(self, player, index=[]):\n\t\tconsecutive_pieces = 0\n\t\tfor i in range(0, index[1]):\n\t\t\tif str(self.board[index[0]][i]) == str(player):\n\t\t\t\tconsecutive_pieces += 1\n\t\t\t\tif consecutive_pieces == 4:\n\t\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tconsecutive_pieces = 0\n\n\t\t#consecutive_pieces += 1\n\t\tif consecutive_pieces == 4:\n\t\t\t\t\treturn True\n\n\t\tfor i in range(index[1], DEFAULT_NUM_COLS):\n\t\t\tif str(self.board[index[0]][i]) == str(player):\n\t\t\t\tconsecutive_pieces +=1\n\t\t\t\tif consecutive_pieces == 4:\n\t\t\t\t\treturn True\n\t\t\telse: \n\t\t\t\tconsecutive_pieces = 0\n\t\treturn False\n\n\tdef _check_vertical(self, player, index=[]):\n\t\tconsecutive_pieces = 0\n\t\tfor i in range(0, index[0]):\n\t\t\tif str(self.board[i][index[1]]) == str(player):\n\t\t\t\tconsecutive_pieces += 1\n\t\t\t\tif consecutive_pieces == 4:\n\t\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tconsecutive_pieces = 0\n\n\t\t#consecutive_pieces += 1\n\t\tif consecutive_pieces == 4:\n\t\t\t\t\treturn True\n\n\t\tfor i in range(index[0], DEFAULT_NUM_ROWS):\n\t\t\tif str(self.board[i][index[1]]) == str(player):\n\t\t\t\tconsecutive_pieces +=1\n\t\t\t\tif consecutive_pieces == 4:\n\t\t\t\t\treturn True\n\t\t\telse: \n\t\t\t\tconsecutive_pieces = 0\n\t\treturn False\n\tdef play_game(self):\n\t\tsystem(\"clear\")\n\t\twhile True:\n\t\t\tcurrent_player = 1\n\t\t\tsystem(\"clear\")\n\t\t\tself.print_board()\n\t\t\tinserted = False\n\t\t\tidx_last_insert = []\n\t\t\twhile not inserted:\n\t\t\t\tresult = self.insert_piece(current_player, \n\t\t\t\t\tself._prompt_input(current_player))\n\t\t\t\tif result:\n\t\t\t\t\tinserted = True\n\t\t\t\t\tidx_last_insert = result\n\t\t\t\t\tself._check_winner(current_player, idx_last_insert)\n\t\t\t\telse:\n\t\t\t\t\tprint(\"You inserted at an invalid location.\")\n\t\t\tsystem(\"clear\")\n\t\t\tself.print_board() \n\t\t\tif self._check_winner(current_player, idx_last_insert):\n\t\t\t\tprint(\"Player {} won!\".format(str(current_player)))\n\t\t\t\texit(0)\n\t\t\tinserted = False\n\t\t\tcurrent_player = 2\n\t\t\twhile not inserted:\n\t\t\t\tresult = self.insert_piece(current_player, \n\t\t\t\t\tself._prompt_input(current_player))\n\t\t\t\tif result:\n\t\t\t\t\tinserted = True\n\t\t\t\t\tidx_last_insert = result\n\t\t\t\t\tself._check_winner(current_player, idx_last_insert)\n\t\t\t\telse:\n\t\t\t\t\tprint(\"You inserted at an invalid location.\")\n\t\t\tif self._check_winner(current_player, idx_last_insert):\n\t\t\t\tsystem(\"clear\")\n\t\t\t\tself.print_board()\n\t\t\t\tprint(\"Player {} won!\".format(str(current_player)))\n\t\t\t\texit(0)\n\n\n\ntestCF = ConnectFour()\ntestCF.play_game()\n" } ]
3
jbpoline/bids2pype
https://github.com/jbpoline/bids2pype
1c693a86bfec8dfaa203f9e53d638488314e87a8
443c11384aad8eff2439c0b43b5a4032119d87a3
4a0f3b5849033fa4f6ca6f6965c3437e5f5db275
refs/heads/master
2021-01-17T14:53:31.223754
2016-08-03T06:30:34
2016-08-03T06:30:34
50,365,669
2
1
null
2016-01-25T16:54:11
2016-03-03T07:07:10
2016-08-03T06:30:34
Python
[ { "alpha_fraction": 0.8051947951316833, "alphanum_fraction": 0.8051947951316833, "avg_line_length": 75, "blob_id": "40389635fbee4042a83018c2137e4b1fbc973539", "content_id": "5d3336e632ab99a8610f23d338ea1d7fdc8b3a22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 77, "license_type": "no_license", "max_line_length": 75, "num_lines": 1, "path": "/README.rst", "repo_name": "jbpoline/bids2pype", "src_encoding": "UTF-8", "text": "# Some code to go from BIDS model description to nipype model specification\n\n" }, { "alpha_fraction": 0.5689237117767334, "alphanum_fraction": 0.5707190036773682, "avg_line_length": 33.66908645629883, "blob_id": "ffa5f23d737a01cb4857a089c3a6d58a27875b16", "content_id": "d5b94d922c426b8f459f9d3ae0df2cce07bd3134", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 33421, "license_type": "no_license", "max_line_length": 100, "num_lines": 964, "path": "/bids2pype/utils.py", "repo_name": "jbpoline/bids2pype", "src_encoding": "UTF-8", "text": "from __future__ import print_function, division\nimport collections\nimport os\nimport os.path as osp\nimport shutil\nimport json\nimport fnmatch\nimport re\n#import glob as gb\n#from six import string_types\nimport numpy as np\nimport pandas as pd\nfrom nipype.interfaces.base import Bunch\n\n\nVERB = {'none':10, 'info':3, 'warn':2, 'bug':1, 'critical':0}\n\nLEVELS = {'Run', 'Session', 'Subject', 'Group'}\nLEVELSJSON = { 'Run':'run_model', 'Session':'ses_model',\n 'Subject':'sub_model', 'Group':'group_model'}\n\nREGKEYS = ['Variable', 'Level', 'HRFModelling', 'ModulationOrder', 'ModulationVar', 'Demean']\nRUNMODKEYS = ['Level', 'DependentVariable', 'Columns', 'Error',\n 'Contrasts', 'HighPassFilterCutoff']\nCONKEYS = ['Column', 'Statistic', 'Weights']\n\nDEFAULTS_PAR = {'order_modulation': 1, 'high_pass_filter_cutoff': 120}\n\ndef _get_json_dict_from_file(json_file):\n \"\"\"\n \"\"\"\n assert osp.isfile(json_file), \"{} is not a file\".format(json_file)\n try:\n with open(json_file) as fjson:\n json_dic = json.load(fjson)\n except:\n raise ValueError(\" {} cannot be loaded by json module\".format(json_file))\n\n return json_dic\n\n\ndef _get_dict_from_tsv_file(tsv_file):\n \"\"\"\n \"\"\"\n assert osp.isfile(tsv_file), \"{} is not a file \".format(tsv_file)\n\n df = pd.read_csv(tsv_file, index_col=False, sep='\\t')\n tsv_dict = df.to_dict(orient='list')\n\n return tsv_dict\n\n\ndef get_json_dict(json_model_fn, level):\n \"\"\"\n get the dict corresponding to this level from the json model file\n\n\n parameters\n ----------\n json_model_fn: string\n file_name of the json file containing model description\n level: string\n one of {'Run', 'Session', 'Subject', 'Group'}\n Returns:\n --------\n dict_level: dict\n contains the json file info\n \"\"\"\n\n try:\n with open(json_model_fn) as fjson:\n model_dic = json.load(fjson)\n except:\n raise ValueError(\"\\n json module cannot load {}\".format(json_model_fn))\n\n json_level = LEVELSJSON[level]\n\n # in this json file, get the level dictionary\n if json_level in model_dic:\n assert model_dic[json_level]['Level'] == level, \\\n \"{} not in {}\".format(level, model_dic[json_level])\n dict_level = model_dic[json_level]\n else:\n assert model_dic['Level'] == level, \\\n \"{} not in {}\".format(level, model_dic)\n dict_level = model_dic\n\n return dict_level\n\n\ndef get_json_model_Ydata(json_model_fn, level='Run', verbose=VERB['none']):\n \"\"\"\n Reads a json model, then search in the base_dir to return the data\n or set of data to which the model should be applied\n\n \"\"\"\n\n # json file like .../models/something.json,\n basedir_to_search = osp.dirname(osp.dirname(json_model_fn))\n if verbose <= VERB['info']:\n print('base dir', basedir_to_search)\n print('json_model_fn', json_model_fn)\n\n dict_level = get_json_dict(json_model_fn, level)\n\n if level == 'Run':\n returned_list = get_runs_data(basedir_to_search, dict_level)\n\n else:\n raise NotImplementedError(\"Level {} not yet implemented\".format(level))\n\n# if level == 'Session':\n# returned_list = get_sessions_data(basedir_to_search, dict_level)\n\n return returned_list\n\n\ndef get_prefix_suffix(level):\n \"\"\"\n \"\"\"\n assert level in LEVELS, \"{} not a model level\".format(level)\n if level == 'Run':\n nii_Y_prefix = 'sub-*'\n nii_Y_suffix = '_run-*.nii.gz'\n else:\n raise NotImplementedError(\" Level {} not implemented\".format(level))\n\n return nii_Y_prefix, nii_Y_suffix\n\n\ndef get_runs_data(basedir, model_dic, verbose=VERB['none']):\n \"\"\"\n search for the runs specified in model_dic in this base directory\n \"\"\"\n data_key = 'DependentVariable'\n assert 'DependentVariable' in model_dic, \\\n \"{} not in {}\".format(data_key, model_dic)\n\n nii_Y_prefix, nii_Y_suffix = get_prefix_suffix('Run')\n nii_to_search = nii_Y_prefix + model_dic['DependentVariable'] + nii_Y_suffix\n if verbose <= VERB['warn']: print(nii_to_search)\n\n return glob_recursive(basedir, nii_to_search)\n\n\ndef _possible_dirpath_for_Ydata(dirname):\n \"\"\"\n return True if this path can contain data\n \"\"\"\n raise NotImplementedError('_possible_dirpath_for_Ydata is not yet implemented')\n #return True\n\n\ndef glob_recursive(source_dir, pattern):\n \"\"\"\n recursive glob in the source_dir\n \"\"\"\n assert osp.isdir(source_dir), \\\n '{} does not seem to be a directory'.format(source_dir)\n matches = []\n for dirpath, dirnames, filenames in os.walk(source_dir):\n for filename in fnmatch.filter(filenames, pattern):\n matches.append(osp.join(dirpath, filename))\n return matches\n\n\ndef _rglob_sorted_by_depth(base_dir, pattern):\n \"\"\"\n recursively find files with pattern in base_dir\n return a list of files found, from root to leaf\n \"\"\"\n def sort_by_dir_len(x):\n return(len(osp.dirname(x)))\n\n filenames = glob_recursive(base_dir, pattern)\n # return the list of directory by order of most root to most leaf\n\n return sorted(filenames, key=sort_by_dir_len)\n\n\ndef associate_model_data(base_dir, model_pattern, level='Run',\n verbose=VERB['none']):\n \"\"\"\n This function creates the link between a given nii or nii.gz\n filename and the model that should be apply to it at the run level\n\n parameters:\n -----------\n base_dir: string\n the base directory of the bids data\n model_pattern:\n glob pattern to identify model files\n\n returns\n ------\n dictionary\n Contains the link between nii files to be processed (keys)\n and their model\n \"\"\"\n all_jsons_sorted = _rglob_sorted_by_depth(base_dir, model_pattern)\n current_dict = {}\n for json_model_fn in all_jsons_sorted:\n # this at the moment may return unwanted data : too liberal\n list_of_data = get_json_model_Ydata(json_model_fn,\n level=level, verbose=verbose)\n dict_level = get_json_dict(json_model_fn, level)\n for data in list_of_data:\n # only associate data and model for data which have an event file:\n if _get_event_filename_for_run(data):\n current_dict[data] = dict_level\n\n return {'data_dict':current_dict, 'base_dir':base_dir}\n\n\ndef data_for_regressor(tsv_dict, datatype, trial):\n \"\"\"\n get the onsets or the duration (called datatype) for this trial\n \"\"\"\n assert datatype in tsv_dict, \\\n \"{} is not in dict {}\".format(datatype, tsv_dict)\n assert trial in tsv_dict['trial_type'], \\\n \"There is no {} in {}\".format(trial, tsv_dict['trial_type'])\n\n trial_data = [ tsv_dict[datatype][i] \\\n for i,_trial in enumerate(tsv_dict['trial_type']) if _trial == trial]\n\n return trial_data\n\n\ndef _check_keys_in(keys, somewhere):\n \"\"\"\n \"\"\"\n for elt in keys:\n assert elt in somewhere, \"{} not in {}\".format(elt, somewhere)\n\n\ndef _get_tsv_lines(tsv_dict, column_name, trial):\n \"\"\"\n This function takes a tsv dictionary, a column name, a trial type,\n and returns the lines of the tsv for corresponding to trial for that column\n \"\"\"\n message = \"\"\n assert column_name in tsv_dict, \\\n \"There is no {} in {}\".format(column_name, tsv_dict.keys())\n\n column_data = np.asarray(tsv_dict[column_name])\n if trial == 'n/a':\n lines_bool = np.ones(column_data.shape, dtype=bool)\n else:\n lines_bool = column_data == trial\n\n # for the moment, fails if no trial of that type\n all_fine = np.any(lines_bool)\n if not all_fine:\n message = \"\\n{} column has no {}\".format(column_name, trial)\n\n return lines_bool, message\n\n\ndef _get_tsv_values(tsv_dict, column_name, lines_bool):\n \"\"\"\n Read the column_name from the tsv_dict, and select the values\n that are True for lines_bool\n \"\"\"\n assert column_name in tsv_dict, \\\n \"There is no {} in {}\".format(column_name, tsv_dict.keys())\n col_array = np.asarray(tsv_dict[column_name])\n col_values = col_array[lines_bool]\n assert len(col_values) > 0, \\\n \"no values for {}\".format(column_name, tsv_dict.keys())\n return list(col_values)\n\n\ndef _run_has_event_file(datafile):\n assert False\n\n\ndef _get_event_filename_for_run(datafile):\n \"\"\"\n input:\n ------\n datafile: string\n a *_bold.nii.gz file\n output:\n -------\n string\n corresponding filename\n \"\"\"\n tsv_file = datafile.split('_bold.nii')[0] + '_events.tsv'\n if osp.isfile(tsv_file): #, \"{} is not a file \".format(tsv_file):\n return tsv_file\n else:\n return ''\n\n\ndef _get_bids_variables(base_dir, datafile, check=False):\n \"\"\"\n \"\"\"\n relative_file = datafile.split(base_dir)[-1]\n run = _get_substr_between(relative_file, '_run-', '_bold', check=check)\n sub = _get_substr_between(relative_file, 'sub-', '_task', check=check)\n grp = _get_substr_between(relative_file, 'grp-', '_', check=check)\n ses = _get_substr_between(relative_file, 'ses-', '_', check=check)\n\n bvar_dict = {'run': run, 'ses': ses, 'sub': sub, 'grp': grp}\n\n return bvar_dict\n\n\ndef _get_file_from_pattern(base_dir, file_pattern, bvar_dict):\n \"\"\"\n Takes a file_pattern and a dict. The pattern will contain {[???]*} substrings,\n and the dictionary contains predefined keys: 'run', 'ses', 'sub', 'grp'\n which values are strings corresponding to the \"value\" in the key-value\n of a BIDS filename.\n This allows to format slighlty differently the values of the k-v pairs\n and form the filename wanted.\n\n\n input:\n ------\n base_dir: string\n pattern: string\n bvar_dict: dict\n contains 'run', 'ses', 'sub', 'grp' keys\n\n output:\n -------\n string\n the filename\n \"\"\"\n\n\n\n # replicate dict but with int\n ivar_dict = {}\n for k in bvar_dict:\n if bvar_dict[k]:\n ivar_dict[k] = int(bvar_dict[k])\n\n # print(ivar_dict)\n\n # find the {[???]*} indicating formatting\n sre = \"(\\{0\\[.{3}\\].*?})\"\n compiled = re.compile(sre)\n find_sre = compiled.findall(file_pattern)\n for substr in find_sre:\n # substr should be '{[run]:01d}', or '{[run]}'\n if substr[-2] == 'd':\n newstr = substr.format(ivar_dict)\n else:\n newstr = substr.format(bvar_dict)\n file_pattern = file_pattern.replace(substr, newstr, 1)\n # 1: replace only first occurence\n # debug: print(substr, newstr, file_pattern)\n\n return osp.join(base_dir, file_pattern)\n\n\ndef _get_other_reg_file_name(base_dir, datafile, pattern):\n \"\"\"\n \"\"\"\n bvar_dict = _get_bids_variables(base_dir, datafile)\n file_name = _get_file_from_pattern(base_dir, pattern, bvar_dict)\n\n return file_name\n\n\ndef _get_other_regressors(file_name, regressor, kreg, verbose=VERB['none']):\n \"\"\"\n from a file that contains columns of values, construct an \"other regressor\"\n\n parameters:\n -----------\n file_name: string\n file that contains the other regressors to be included in the model\n regressor: dict\n the dict described in the json model file\n should have keys:\n \"FileSelector\" : how to get the file\n \"Regressors\" : which columns are we taking from this file\n kreg: string\n the regressor key (name), eg: motion-param\n\n returns:\n --------\n dict_regressors: dict\n keys: names of the other regressors\n values: {'group', 'values'}\n 'group': indicate the name of the original set of regressors\n coming from the same file\n 'values': the values of the regressor, as many as volume in the\n data to be analyzed\n \"\"\"\n #print(file_name)\n #- create file name from pattern and variables\n # pattern = regressor['FileSelector']['pattern']\n #- check that the file exists\n if not file_name:\n raise Exception(\"{} not a file, regressor: {} \".format(file_name, regressor))\n\n assert osp.isfile(file_name)\n\n if verbose <= VERB['info']:\n print(\"_get_other_regressors: file_name {}, regressor: {}\".format(\n file_name, regressor))\n # Read this file, account for one column file\n motpars=np.loadtxt(file_name)\n if motpars.ndim == 1:\n nb_lines, nb_col = 1, motpars.shape[0]\n elif motpars.ndim == 2:\n nb_lines, nb_col = motpars.shape\n else:\n raise Exception(\" array from {} does not seem to be well, motpars.shape\".format(\n file_name, motpars.shape))\n # debug:print(\"nb_col, nb_lines\", nb_col, nb_lines)\n\n all_col_indices = range(nb_col)\n\n # what do we do with it:\n assert \"Regressors\" in regressor\n to_add = regressor[\"Regressors\"] # should be [\"all\", \"deriv1\"]\n # if to_add empty, for the moment raise\n if not to_add:\n print(\"to_add empty, for the moment raise\")\n\n # possible values\n assert set(to_add).issubset({'all', 'deriv1'}), \"{}\".format(set(to_add))\n dict_regressors = collections.OrderedDict()\n\n if \"all\" in to_add:\n # form names\n col_names = [kreg+\"_{:02d}\".format(i+1) for i in all_col_indices]\n for i, name in enumerate(col_names):\n dict_regressors[name] = {}\n dict_regressors[name]['values'] = motpars[:,i]\n dict_regressors[name]['group'] = kreg\n\n if \"deriv1\" in to_add:\n col_names = [kreg+\"_{:02d}_deriv\".format(i+1) for i in all_col_indices]\n for i, name in enumerate(col_names):\n dict_regressors[name] = {}\n td = np.zeros(motpars.shape[0])\n td[1:] = motpars[1:,i] - motpars[:-1,i]\n dict_regressors[name]['values'] = td\n dict_regressors[name]['group'] = kreg+\"_deriv\"\n\n return dict_regressors\n\n\ndef get_run_conditions(base_dir, datafile, model_dict, verbose=VERB['none']):\n \"\"\"\n returns conditions_names, and a list of\n dictionaries (one per condition/trial) containing\n onsets, duration, HRF, ... for this model\n\n parameters:\n -----------\n base_dir: string\n the data base directory, eg /somethin/data/ds005\n datafile: string\n should be a .nii or .nii.gz data\n model_dict: dict\n the run level part of the model\n\n returns\n -------\n dict_regressors: dict\n keys are the name of the regressors,\n values are dict containing onsets, duration, HRFModelling, etc\n dict_other_regressors: dict\n keys are name of other regressors (not to be convolved)\n values are dict with 'values', and possibly other information\n logging:\n\n \"\"\"\n\n # proper logging for latter ...\n logging = {}\n\n # for runs, the datafile is just a filename\n # check data exist ?\n assert osp.isfile(datafile), \"{} is not a file\".format(datafile)\n\n # get tsv filename:\n tsv_file = _get_event_filename_for_run(datafile)\n if not tsv_file:\n raise Exception(\"no tsv_file for {}\".format(datafile))\n tsv_dict = _get_dict_from_tsv_file(tsv_file)\n\n # get condition names:\n # should trial_type be there if only one type of trial_type ?\n _check_keys_in({'onset', 'duration', 'trial_type'}, tsv_dict)\n _check_keys_in({'Columns'}, model_dict)\n #\n regressors = model_dict['Columns']\n dict_regressors = collections.OrderedDict()\n dict_other_regressors = collections.OrderedDict()\n\n for kreg, this_regressor in regressors.items():\n logging[kreg] = {}\n logging[kreg]['is_well'] = True\n logging[kreg]['msg'] = ''\n #dict_regressors[kreg] = {}\n\n # other regressors if we have a FileSelector - not HRF convolved -\n # may contain several columns of data as in motion parameters\n if 'FileSelector' in this_regressor:\n # this kreg not in dict_regressors\n _check_keys_in({'pattern'}, this_regressor['FileSelector'])\n pattern = this_regressor['FileSelector']['pattern']\n file_name = _get_other_reg_file_name(base_dir, datafile, pattern)\n # print(\"the file_name: \", file_name)\n other_regressors = _get_other_regressors(file_name, \\\n this_regressor, kreg, verbose=verbose)\n dict_other_regressors.update(other_regressors)\n\n else: #- this is a standard onset type of reg., will be HRF convolved\n _check_keys_in({'Variable', 'HRFModelling','Level'}, this_regressor)\n\n if verbose <= VERB['info']:\n print('\\nRegress :', kreg,\n 'regressor[Variable]: ', regressor['Variable'])\n\n dict_cond = {}\n dict_cond['HRF'] = this_regressor['HRFModelling']\n\n # First, get the lines through 'Variable' and 'Level':\n #------------------------------------------------------\n trial_level = this_regressor['Level']\n explanatory = this_regressor['Variable']\n col_bool, nothing_there = _get_tsv_lines(tsv_dict,\n explanatory, trial_level)\n\n if nothing_there:\n msg = nothing_there + ' ! \\n' + 'Removing key {} for {}'\\\n .format(kreg, datafile)\n if verbose <= VERB['info']:\n print(msg)\n logging[kreg]['msg'] = msg\n logging[kreg]['is_well'] = False\n # skip this regressor in the returned dictionary\n continue # skip that kreg\n\n # Second, get the values for these lines\n #------------------------------------------------------\n _check_keys_in({'onset', 'duration'}, tsv_dict)\n dict_cond['onset'] = _get_tsv_values(tsv_dict, 'onset', col_bool)\n\n # if there is a \"duration\" key in the model for this regressor,\n # take it and overide values in tsv file\n #------------------------------------------------------\n if \"Duration\" in this_regressor:\n the_duration = this_regressor['Duration']\n dict_cond['duration'] = \\\n list((np.ones(col_bool.shape)*the_duration)[col_bool])\n else:\n dict_cond['duration'] = \\\n _get_tsv_values(tsv_dict, 'duration', col_bool)\n\n # Any parametric modulation ? 'prm_modulation' corresponds\n # to the 'weight'\n #------------------------------------------------------\n if 'ModulationVar' in this_regressor:\n weights = _get_tsv_values(tsv_dict,\n this_regressor['ModulationVar'], col_bool)\n if 'Demean' in this_regressor:\n weights = np.asarray(weights).astype(float)\n weights -= weights.mean()\n\n dict_cond['prm_modulation'] = list(weights)\n dict_cond['name_modulation'] = this_regressor['ModulationVar']\n dict_cond['order_modulation'] = DEFAULTS_PAR['order_modulation']\n if 'ModulationOrder' in this_regressor:\n dict_cond['order_modulation'] = \\\n this_regressor['ModulationOrder']\n\n # No parametric modulation\n #------------------------------------------------------\n else:\n dict_cond['prm_modulation'] = \\\n list(np.ones(col_bool.shape)[col_bool])\n dict_cond['name_modulation'] = None\n dict_cond['order_modulation'] = None\n\n # Any temporal modulation ?\n #------------------------------------------------------\n dict_cond['tmp_modulation'] = False\n if 'tmp_modulation' in this_regressor:\n dict_cond['tmp_modulation'] = this_regressor['ModulationTime']\n\n # Adding the regressor\n #------------------------------------------------------\n dict_regressors[kreg] = dict_cond\n if verbose <= VERB['info']:\n print('\\nkeys for regressor ', kreg, \" are:\", dict_cond.keys())\n print('\\ndict for regressor: ', dict_cond)\n\n\n return dict_regressors, dict_other_regressors, logging\n\n\ndef get_run_contrasts(model_dict):\n \"\"\"\n parameters\n ----------\n model_dict: dict\n see description in ...\n\n returns\n -------\n dict_contrasts: dict\n a dict containing all necessary information for the\n contrasts to be exported\n \"\"\"\n\n _check_keys_in({'Contrasts'}, model_dict)\n regressors = model_dict['Columns']\n contrast_dict = model_dict['Contrasts']\n dict_contrasts = {}\n\n for con_name,val in contrast_dict.items():\n # fill contrast dict\n contrast = {}\n contrast['name'] = con_name\n contrast['conditions'] = val['Columns']\n # check contrast conditions are in regressors\n assert set(contrast['conditions']).issubset(set(regressors.keys())),\\\n \"{} not subset of {}\".format(\n contrast['conditions'], regressors.keys())\n contrast['Weights'] = val['Weights']\n contrast['Statistic'] = val['Statistic']\n\n #- add to dict_contrasts\n dict_contrasts[con_name] = contrast\n\n return dict_contrasts\n\n#------------------------------------------------------------------------------#\n#----------------------- Export functions to nipype from here ----------------#\n#------------------------------------------------------------------------------#\n\n\ndef make_nipype_bunch(dict_regressors, other_reg,\n bunch_type='spm', verbose=VERB['none']):\n \"\"\"\n return a Bunch : the nipype input for model specification\n so far : the spm bunch with pmod and tmod\n \"\"\"\n\n # does it make sense to create a bunch from empty regressors ?\n assert dict_regressors, \\\n \"dict_regressors input is empty: {}\".format(dict_regressors)\n\n conditions = []\n onsets = []\n durations = []\n amplitudes = []\n pmod = []\n\n # condition_names = dict_regressors.keys()\n # mend the order of things condition names\n\n for cond, dic in dict_regressors.items():\n # dic = dict_regressors[cond]\n assert type(dic) == dict, \"{} not a dict\".format(dic)\n if verbose <= VERB['info']:\n print(\"\\nmake_nipype_bunch cond : \", cond, \"dic : \", dic)\n conditions.append(cond),\n onsets.append(dic['onset'])\n durations.append(dic['duration'])\n\n #----- spm type of bunches ------#\n if bunch_type == 'spm':\n if dic['name_modulation']:\n pmod_name = dic['name_modulation']\n pmod_poly = dic['order_modulation']\n pmod_param = dic['prm_modulation']\n pmod.append([Bunch(name=pmod_name,\n poly=pmod_poly,\n param=pmod_param), None])\n else:\n pmod.append([])\n #----- fsl type of bunches ------#\n elif bunch_type == 'fsl':\n # here the parametric modulation values encodes the\n # 'weights' or 'amplitudes'\n amplitudes.append(dic['prm_modulation'])\n else:\n raise Exception(\"unknown bunch type {}\".format(bunch_type))\n\n regressor_names = []\n regressors = []\n if other_reg:\n\n for key, val in other_reg.items():\n regressor_names.append(key)\n regressors.append(val['values'])\n\n if bunch_type == 'spm': # pmod - tmod ?\n return Bunch(conditions=conditions,\n onsets=onsets,\n durations=durations,\n pmod=pmod,\n regressor_names=regressor_names,\n regressors=regressors\n )\n elif bunch_type == 'fsl':\n return Bunch(conditions=conditions,\n onsets=onsets,\n durations=durations,\n amplitudes=amplitudes,\n regressor_names=regressor_names,\n regressors=regressors\n )\n\n\ndef _get_substr_between(thestring, after, before, check=True):\n \"\"\"\n find things that are strictly after after and strictly before before :)\n example:\n\n >>> _get_substr_between('++aaa_the_good_stuff_bbb++', 'aaa', 'bbb')\n '_the_good_stuff_'\n\n \"\"\"\n # check that after and before are in thestring\n if check:\n assert after in thestring, \"{} not in {}\".format(after, thestring)\n assert before in thestring, \"{} not in {}\".format(before , thestring)\n if not (after in thestring and before in thestring):\n return ''\n # get what's after\n whatisafter = thestring.split(after)[-1]\n # get what's before\n between = whatisafter.split(before)[0]\n return between\n\n\ndef _get_task_json_dict(base_dir, datafile):\n \"\"\"\n get the task-???_bold.json dictionary corresponding to the datafile\n These contain repetition time and task name\n \"\"\"\n # get the task-X _bold.json\n taskname = _get_substr_between(datafile, 'task-', '_')\n # in the future: we might have a task-something lower in the hierarchy that\n # should replace the top level one\n # here problematic when files ._* exist\n task_parameter_files = \\\n _rglob_sorted_by_depth(base_dir, 'task-'+taskname+'_bold.json')\n\n # should be only one file:\n if len(task_parameter_files) != 1:\n raise NotImplementedError(\n \"found {}, len != 1 not implemented, taskname {} basedir {} \".\\\n format(task_parameter_files, taskname, base_dir))\n\n task_dict = _get_json_dict_from_file(task_parameter_files[0])\n\n return task_dict\n\n\ndef _get_nipype_contrasts(model_dict):\n \"\"\"\n\n Parameters\n ----------\n model_dict: dict\n The dict corresponding to the json model file\n \"\"\"\n contrasts_dict = get_run_contrasts(model_dict)\n # format for nipype\n list_con = []\n for con,val in contrasts_dict.items():\n this_con = (con, val['Statistic'], val['conditions'], val['Weights'])\n list_con.append(this_con)\n\n return list_con\n\n\ndef _get_nipype_specify_model_inputs(base_dir, model_pattern, bunch_type='spm',\n level='Run', verbose=VERB['none']):\n \"\"\"\n returns information ready for nipype specify_model:\n For spm: returns pmod style of bunch\n\n parameters:\n -----------\n base_dir: string\n model_pattern: string\n a glob would give you the models\n bunch_type: string\n one of {'spm', 'fsl'}\n\n returns\n -------\n inputs_dict: dict\n dict keys are:\n 'time_repetition'\n 'input_units'\n 'high_pas_filter_cutoff'\n bunches: list\n list of Bunch object\n These objects contain the onsets, duration,\n fsl: amplitudes,\n spm: pmod / tmod Bunches\n datafiles:\n the list of nii.gz files (as many as bunches)\n\n \"\"\"\n\n assert level=='Run', \"level {} not implemented\".format(level)\n\n association_dict = associate_model_data(base_dir, model_pattern,\n level=level, verbose=verbose)\n data_n_models = association_dict['data_dict']\n datafiles = list(data_n_models.keys())\n\n #------ params supposed to be unique across models: take the first one ---#\n\n # assumes for the moment high pass filter must be the same for all runs\n first_model = data_n_models[datafiles[0]]\n if 'HighPassFilterCutoff' in first_model:\n high_pass_filter_cutoff = first_model['HighPassFilterCutoff']\n else:\n high_pass_filter_cutoff = DEFAULTS_PAR['high_pass_filter_cutoff']\n\n # assumes for the moment task info is the same for all runs\n task_dict = _get_task_json_dict(base_dir, datafiles[0])\n\n inputs_dict={}\n inputs_dict['time_repetition'] = task_dict['RepetitionTime']\n inputs_dict['input_units'] = 'secs'\n inputs_dict['high_pass_filter_cutoff'] = high_pass_filter_cutoff\n\n # create a list of bunches, one per datafile\n bunches = []\n for datafile, model_dict in data_n_models.items():\n #task_dict = _get_task_json_dict(base_dir, datafile)\n dict_regressors, other_reg, _log = get_run_conditions(base_dir,\n datafile, model_dict,\n verbose=verbose)\n if verbose <= VERB['info']:\n cond_with_issues = [k for k in _log if not _log[k]['is_well']]\n print('issue with keys {}'.format(cond_with_issues))\n bunches.append(make_nipype_bunch(dict_regressors, other_reg,\n bunch_type=bunch_type, verbose=verbose))\n\n # bunches here is the \"info\" in Russ' ds005 notebook\n return inputs_dict, bunches, datafiles\n\n# specify_model = pe.Node(interface=model.SpecifyModel(), name=\"specify_model\")\n# specify_model.inputs.input_units = 'secs'\n# specify_model.inputs.time_repetition = 3.\n# specify_model.inputs.high_pass_filter_cutoff = 120\n# specify_model.inputs.subject_info =\n\n\ndef create_empty_bids(source_dir, dest_dir, list_pattern, verbose=VERB['none']):\n \"\"\"\n recursive walk in the source_dir: cp whatever is in pattern\n otherwise touch\n\n parameters:\n -----------\n source_dir: string\n the directory to be \"copied\"\n dest_dir: string\n where it is copied\n list_pattern: list\n will only actually copy these patterns (strings)\n\n \"\"\"\n def _mkdir(_dir):\n if not osp.isdir(_dir):\n try:\n os.makedirs(_dir)\n except:\n raise Exception(\"cannot create directory {}\".format(_dir))\n\n def _touch(fname, times=None):\n try:\n with open(fname, 'a'):\n os.utime(fname, times)\n except:\n raise Exception(print(fname))\n\n\n assert osp.isdir(source_dir), \\\n '{} does not seem to be a directory'.format(source_dir)\n\n for dirpath, dirnames, filenames in os.walk(source_dir):\n newpath = dirpath.replace(source_dir, dest_dir)\n _mkdir(dirpath)\n for dirname in dirnames:\n _mkdir(osp.join(newpath, dirname))\n for _file in filenames:\n for pattern in list_pattern:\n # print(_file, pattern, fnmatch.filter([_file], pattern))\n if _file in fnmatch.filter([_file], pattern):\n if verbose <= VERB['info']: print(\"copy \", _file)\n shutil.copy(osp.join(dirpath, _file), osp.join(newpath, _file))\n break\n else:\n _touch(osp.join(newpath, _file))\n\n\n\"\"\" Notes ----\n\n1- associate data and model.\n - find most top level model (or just one model)\n - instanciate default model_dict\n - get list of data\n * for runs, get the nii.gz\n * for ses, sub, grp :\n find all ses, sub, or grp directories, create a unique key for each\n for each, find data as list of files\n associate key and list of files\n - once list of data is found, with a top level model, for each of these element go down\n the directory tree and update the model if necessary\n\n ASSOCIATION OF DATA AND MODEL SHOULD BE COMPLEMENTED BY state_dict{'run','ses','sub','grp'}\n\n2. Once data and model are associated:\n - Create an internal data structure to represent the model\n this would be one object per set of data\n To be implementated\n -----------------------------\n X demean\n X get movement parameter regressors\n -\n\n3. Take this internal data structure and export it in spm / fsl like type of nipype inputs\n\n\nOutstanding question for Satra/Chris\n-------------------------------------\n - seems that pmod structure has only 1 element even when there are 2 runs (2 onsets, etc)\n - the model specification that is generic to both contains specific spm stuff ?\n\n\"\"\"\n\n\n\n\n# def get_nipype_run_info(datafile, model_dict, verbose=VERB['none'], **kwargs):\n# \"\"\"\n# returns what's needed by nipype: conditions, onsets, durations\n# \"\"\"\n# dict_regressors = get_run_conditions(datafile, model_dict, verbose=verbose)\n# condition_names = dict_regressors.keys()\n#\n# nipype_run_info = {}\n# nipype_run_info['condition_names'] = condition_names\n# nipype_run_info['onsets'] = [dict_regressors[cond]['onset'] for cond in condition_names]\n# nipype_run_info['durations'] = [dict_regressors[cond]['duration'] for cond in condition_names]\n# nipype_run_info['prm_modulation'] = \\\n# [dict_regressors[cond]['prm_modulation'] for cond in condition_names]\n# nipype_run_info['tmp_modulation'] = \\\n# [dict_regressors[cond]['tmp_modulation'] for cond in condition_names]\n# nipype_run_info['HRF'] = [dict_regressors[cond]['HRF'] for cond in condition_names]\n#\n# return nipype_run_info\n" }, { "alpha_fraction": 0.6449612379074097, "alphanum_fraction": 0.734883725643158, "avg_line_length": 41.33333206176758, "blob_id": "507e3633054ba396f9cd13b06dbaf62a519da5d1", "content_id": "2c86e1ea21b85ce7a786a5e53dc62fc7544710c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 645, "license_type": "no_license", "max_line_length": 99, "num_lines": 15, "path": "/bids2pype/examples_models_n_spec/models/cp_models_to_data.sh", "repo_name": "jbpoline/bids2pype", "src_encoding": "UTF-8", "text": "#!bash\n\necho `pwd`\nbidsdata='/home/jb/data/bids'\necho \"cp ds-005*_model.json \"$bidsdata\"/ds005/models\"\ncp ds-005_*model.json $bidsdata\"/ds005/models\"\necho \"cp ds-105_level-all_model.json\" $bidsdata\"/ds105/models\"\ncp ds-105_level-all_model.json $bidsdata\"/ds105/models\"\necho \"cp ds-105_level-run_model.json\" $bidsdata\"/ds105/models\"\ncp ds-105_level-run_model.json $bidsdata\"/ds105/models\"\necho \"ds-105_level-run_sub-2_model.json\" $bidsdata\"/ds005/sub-2/models\"\ncp ds-105_level-run_sub-2_model.json $bidsdata\"/ds105/sub-2/func/models\"\n\n\n# /home/jb/code/bids2pype/bids2pype/examples_models_n_spec/models/ds-105_level-run_sub-2_model.json\n \n" }, { "alpha_fraction": 0.4862440228462219, "alphanum_fraction": 0.5145933032035828, "avg_line_length": 39.37681198120117, "blob_id": "3d8e54397c9ac3cce72ff0dc64f7b5153abe9b62", "content_id": "bad9d9f9752cb0c5404c9f4763c81a5ca8b054a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8360, "license_type": "no_license", "max_line_length": 85, "num_lines": 207, "path": "/bids2pype/tests/test_bids2pipe.py", "repo_name": "jbpoline/bids2pype", "src_encoding": "UTF-8", "text": "from __future__ import print_function, division\nfrom .. import utils\nimport numpy as np\nimport os \nimport os.path as osp\nimport json\n\n#print(\"\\n__name__ == \",__name__, \"\\n\")\nprint(\"\\n__file__ == \",__file__, \"\\n\")\n\nLEVELS = {'Run', 'Session', 'Subject', 'Group'}\n\ntest_case_105a = {\n 'base_dir': '/home/jb/data/bids/ds105',\n 'model_pattern': \"ds-105_level-run_sub*_model.json\"\n}\ntest_case_105b = {\n 'base_dir': '/home/jb/data/bids/ds105',\n 'model_pattern': \"ds-105_level-all_model.json\"\n}\ntest_case_005 = {\n #'base_dir': '/home/jb/data/bids/ds005',\n 'base_dir': './data/ds005',\n 'model_pattern': \"*_model.json\"\n}\ntest_case_005r = {\n #'base_dir': '/home/jb/data/bids/ds005',\n 'base_dir': 'data/ds005',\n 'model_pattern': \"ds-005_type-russ*_model.json\"\n}\n\n#test_case = test_case_005\ntest_case = test_case_005r\n#test_case = test_case_105a\n#test_case = test_case_105b\n\nbase_dir, model_pattern = test_case['base_dir'], test_case['model_pattern']\n\ndef test_associate_model_data():\n \"\"\"\n \"\"\"\n pattern_mvt = u'derivatives/mcflirt/par/_runcode_{0[run]:1d}/' + \\\n u'_subject_id_sub-{0[sub]}/sub-{0[sub]}' + \\\n u'_task-mixedgamblestask_run-{0[run]}_bold_mcf.nii.gz.par'\n\n expected = {u'Columns': { \n u'motion-param': { \n u'FileSelector': { \n u'EntitiesKeys': { \n u'run': u'run', \n u'subject': u'sub'},\n u'pattern': \n pattern_mvt\n },\n\n u'Regressors': [u'all', u'deriv1']},\n\n u'param-gain': { u'Demean': True,\n u'HRFModelling': u'Gamma+derivs',\n u'Level': u'n/a',\n u'ModulationOrder': 1,\n u'ModulationVar': u'gain',\n u'Variable': u'trial_type',\n u'duration': 1.3932149481304148},\n u'param-loss': { u'Demean': True,\n u'HRFModelling': u'Gamma+derivs',\n u'Level': u'n/a',\n u'ModulationVar': u'loss',\n u'Variable': u'trial_type',\n u'duration': 1.3932149481304148},\n u'param-rt': { u'Demean': True,\n u'HRFModelling': u'Gamma+derivs',\n u'Level': u'n/a',\n u'ModulationVar': u'RT',\n u'Variable': u'trial_type',\n u'duration': 1.3932149481304148},\n u'task': { u'HRFModelling': u'Gamma',\n u'Level': u'n/a',\n u'Variable': u'trial_type',\n u'duration': 1.3932149481304148}},\n u'Contrasts': { u'param-gain': { u'Columns': [u'param-gain'],\n u'Statistic': u'T',\n u'Weights': [1]},\n u'param-loss-neg': { u'Columns': [u'param-loss'],\n u'Statistic': u'T',\n u'Weights': [-1]},\n u'task>Baseline': { u'Columns': [u'task'],\n u'Statistic': u'T',\n u'Weights': [1]}},\n u'DependentVariable': u'task-mixedgamblestask',\n u'Error': { u'SerialCorrelations': True},\n u'HighPassFilterCutoff': 80,\n u'Level': u'Run'}\n\n assos_model_data = utils.associate_model_data(base_dir, model_pattern, \n verbose=utils.VERB['none'])\n\n data_dict = assos_model_data['data_dict']\n #print(data_dict)\n datafile0 = sorted(data_dict.keys())[0]\n read_from_disk = data_dict[datafile0]\n \n expected_datafile = base_dir + \\\n '/sub-01/func/sub-01_task-mixedgamblestask_run-01_bold.nii.gz'\n assert datafile0 == expected_datafile\n\n\n list1 = read_from_disk['Columns'].keys()\n list2 = expected['Columns'].keys()\n assert set(list1) == set(list2)\n\n exp_contrasts = expected['Contrasts'].keys()\n read_contrasts = data_dict[datafile0]['Contrasts'].keys()\n assert set(exp_contrasts) == set(read_contrasts)\n \n\ndef test_get_nipype_specify_model_inputs(): \n\n specifymodel_inputs, bunches, data = \\\n utils._get_nipype_specify_model_inputs(base_dir, model_pattern, \n bunch_type='fsl', verbose=utils.VERB['none'])\n\n sorted_bunch = [b for (d,b) in sorted(zip(data, bunches))]\n sorted_data = sorted(data)\n\n expected_data0 = base_dir + \\\n '/sub-01/func/sub-01_task-mixedgamblestask_run-01_bold.nii.gz'\n #print(expected_data0)\n assert expected_data0 == sorted_data[0]\n \n exp_param_gain = np.loadtxt(\\\n './data/test_files/test_cond_amplitude.txt').astype(float)\n exp_param_gain -= exp_param_gain.mean()\n index_gain = sorted_bunch[0].conditions.index('param-gain')\n read_param_gain = np.asarray(sorted_bunch[0].amplitudes[index_gain])\n #print(read_param_gain, exp_param_gain)\n assert np.linalg.norm(read_param_gain - exp_param_gain) < 1.e-12\n \ndef test__get_dict_from_tsv_file():\n \"\"\"\n \"\"\"\n fn = './data/test_files/sub-01_task-mixedgamblestask_run-01_events.tsv'\n dic = utils._get_dict_from_tsv_file(fn)\n assert {'onset','duration','trial_type', 'distance from indifference',\n 'RT','parametric gain'}.issubset(set(dic.keys()))\n assert dic['onset'][1] == 4.0\n assert len(dic['onset']) == 86 \n assert dic['duration'][0] == 3\n assert len(dic['duration']) == 86 \n assert dic['RT'][1] == 1.793\n\ndef test_get_json_dict():\n \"\"\"\n \"\"\"\n json_fn = base_dir + '/models/ds-005_type-russ_sub-all_model.json'\n # read json model\n json_dic = utils.get_json_dict(json_fn, \"Run\")\n assert json_dic['Level'] == \"Run\"\n assert json_dic['DependentVariable'] == \"task-mixedgamblestask\"\n assert \"HighPassFilterCutoff\" in json_dic.keys()\n assert \"Columns\" in json_dic.keys()\n\ndef test_get_other_regressors():\n \"\"\"\n \n specifymodel_inputs, bunches, data = \\\n utils._get_nipype_specify_model_inputs(base_dir, model_pattern, \n bunch_type='fsl', verbose=utils.VERB['none'])\n\n \"\"\"\n\n specifymodel_inputs, bunches, data = \\\n utils._get_nipype_specify_model_inputs(base_dir, model_pattern, \\\n bunch_type='fsl', verbose=utils.VERB['none'])\n\n # sort both bunch and data to get predictable output\n sorted_bunch = [b for (d,b) in sorted(zip(data, bunches))]\n sorted_data = sorted(data)\n\n assert sorted_data[0] == base_dir + \\\n '/sub-01/func/sub-01_task-mixedgamblestask_run-01_bold.nii.gz'\n assert sorted_data[2] == base_dir + \\\n '/sub-01/func/sub-01_task-mixedgamblestask_run-03_bold.nii.gz'\n assert sorted_data[-1] == base_dir + \\\n '/sub-16/func/sub-16_task-mixedgamblestask_run-03_bold.nii.gz'\n assert sorted_bunch[0].regressor_names[0] == \"motion-param_01\"\n assert sorted_bunch[0].regressor_names[1] == \"motion-param_02\"\n\n # read file corresponding to the first sub run mvt param:\n mvt = np.loadtxt(base_dir + \\\n '/derivatives/mcflirt/par/_runcode_1/'+\\\n '_subject_id_sub-01/sub-01_task-mixedgamblestask_run-01_bold_mcf.nii.gz.par')\n\n for col_idx, col_mvt in enumerate(mvt.T): \n assert np.linalg.norm(col_mvt - sorted_bunch[0].regressors[col_idx]) < 1.e-12\n\n\n # read file corresponding to sub 01 run 03 mvt param:\n mvt_file = base_dir + \\\n '/derivatives/mcflirt/par/_runcode_3/'+\\\n '_subject_id_sub-01/sub-01_task-mixedgamblestask_run-03_bold_mcf.nii.gz.par'\n #print(mvt_file)\n mvt = np.loadtxt(mvt_file) \n\n\n for col_idx, col_mvt in enumerate(mvt.T): \n assert np.linalg.norm(col_mvt - sorted_bunch[2].regressors[col_idx]) < 1.e-12\n\n\n" } ]
4
doctor-budoka/shared-expenses-site
https://github.com/doctor-budoka/shared-expenses-site
0b3745ab50e4ffc78d34d403340bd46cd06b0289
aba261497676b0678e6bc074c1d28a2ec1546f22
e963e058a062b366b408cf43befaa79e4d62a79a
refs/heads/master
2023-01-24T00:15:21.495294
2020-08-03T16:00:34
2020-08-03T16:00:34
274,590,158
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8453608155250549, "alphanum_fraction": 0.8453608155250549, "avg_line_length": 9.777777671813965, "blob_id": "a5f4b2af6a0cb48e41076bb59639c49716effcff", "content_id": "4b92c0ca03c827b31d1f4f557d06e77e4a8d7dc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 97, "license_type": "no_license", "max_line_length": 16, "num_lines": 9, "path": "/requirements.txt", "repo_name": "doctor-budoka/shared-expenses-site", "src_encoding": "UTF-8", "text": "flask\nflask-wtf\nflask-sqlalchemy\nflask-login\nwtforms\nwtforms[email]\npython-dotenv\nwerkzeug\nclick\n" }, { "alpha_fraction": 0.653257429599762, "alphanum_fraction": 0.6534537076950073, "avg_line_length": 36.31578826904297, "blob_id": "b2379bb338539aca639d9306d06ab7e25b69e970", "content_id": "bc5ebeb8516dea31a652bbe9961daaff4fb86e52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5096, "license_type": "no_license", "max_line_length": 128, "num_lines": 133, "path": "/expenses_app/group/group.py", "repo_name": "doctor-budoka/shared-expenses-site", "src_encoding": "UTF-8", "text": "from flask import render_template, redirect, url_for, flash, Blueprint\r\nfrom flask_login import login_required, current_user\r\nfrom expenses_app.group.forms import CreateGroup, AddUserToGroup, RemoveUserFromGroup, AddAccountToGroup, RemoveAccountFromGroup\r\nfrom expenses_app.models import db, User, Group, Account\r\n\r\ngrp_bp = Blueprint(\r\n 'grp_bp', __name__,\r\n template_folder='templates',\r\n static_folder='static'\r\n)\r\n\r\n\r\n@grp_bp.route(\"/\", methods=[\"GET\", \"POST\"])\r\n@login_required\r\ndef index():\r\n form = CreateGroup()\r\n if form.validate_on_submit():\r\n new_group_name = form.name.data\r\n exists = Group.query.filter(Group.name == new_group_name).first()\r\n if not exists:\r\n current_user.create_group(new_group_name)\r\n db.session.commit()\r\n else:\r\n flash(f\"{new_group_name} has already been taken! Try another name.\")\r\n return render_template(\"index.html\", form=form)\r\n\r\n\r\n@grp_bp.route(\"/groups/<group_name>/summary\", methods=[\"GET\", \"POST\"])\r\n@login_required\r\ndef group_summary(group_name):\r\n group = group_from_group_name(group_name)\r\n\r\n if group and group.has_user(current_user):\r\n return render_template(\"group_summary.html\", group=group)\r\n\r\n return redirect(url_for(\"grp_bp.index\"))\r\n\r\n\r\n@grp_bp.route(\"/groups/<group_name>/access\", methods=[\"GET\", \"POST\"])\r\n@login_required\r\ndef group_access(group_name):\r\n group = group_from_group_name(group_name)\r\n if group and group.has_user(current_user):\r\n add_form = AddUserToGroup()\r\n remove_form = RemoveUserFromGroup.from_group(group, current_user)\r\n\r\n return render_template(\"group_access.html\", group=group, add_form=add_form, remove_form=remove_form)\r\n\r\n return render_template(\"index.html\", group=group)\r\n\r\n\r\n@grp_bp.route(\"/groups/<group_name>/remove_user\", methods=[\"POST\"])\r\n@login_required\r\ndef remove_user_from_group(group_name):\r\n group = group_from_group_name(group_name)\r\n remove_form = RemoveUserFromGroup.from_group(group, current_user)\r\n if remove_form.validate_on_submit():\r\n user_id = remove_form.username.data\r\n old_user = User.query.get(user_id)\r\n group.remove_user(old_user)\r\n db.session.commit()\r\n return redirect(url_for(\"grp_bp.group_access\", group_name=group_name))\r\n\r\n\r\n@grp_bp.route(\"/groups/<group_name>/add_user\", methods=[\"POST\"])\r\n@login_required\r\ndef add_user_to_group(group_name):\r\n group = group_from_group_name(group_name)\r\n add_form = AddUserToGroup()\r\n if add_form.validate_on_submit():\r\n user_name = add_form.username.data\r\n new_user = User.query.filter_by(username=user_name).first()\r\n if new_user:\r\n group.add_user(new_user)\r\n db.session.commit()\r\n else:\r\n flash(f\"{user_name} is not a valid username!\")\r\n return redirect(url_for(\"grp_bp.group_access\", group_name=group_name))\r\n\r\n\r\n@grp_bp.route(\"/groups/<group_name>/accounts\")\r\n@login_required\r\ndef group_accounts(group_name):\r\n group = group_from_group_name(group_name)\r\n\r\n if group and group.has_user(current_user):\r\n add_form = AddAccountToGroup.from_group(group)\r\n remove_form = RemoveAccountFromGroup.from_group(group)\r\n return render_template(\"group_accounts.html\", group=group, add_form=add_form, remove_form=remove_form)\r\n\r\n return redirect(url_for(\"grp_bp.index\"))\r\n\r\n\r\n@grp_bp.route(\"/groups/<group_name>/add_account\", methods=[\"POST\"])\r\n@login_required\r\ndef add_account_to_group(group_name):\r\n group = group_from_group_name(group_name)\r\n add_form = AddAccountToGroup.from_group(group)\r\n if add_form.validate_on_submit():\r\n name = add_form.name.data\r\n name_exists = Account.query.filter(Account.name == name, Account.group_id == group.id).first()\r\n if name_exists and name_exists.status == \"live\":\r\n flash(\"The account name already exists in this group!\")\r\n elif name_exists:\r\n name_exists.status = \"removed\"\r\n db.session.commit()\r\n else:\r\n user_id = add_form.user.data\r\n user = User.query.get(user_id) if user_id > -1 else None\r\n has_balance = add_form.has_balance.data\r\n balance = add_form.starting_balance.data if has_balance else None\r\n Account.create_account(group, name, user, balance)\r\n db.session.commit()\r\n\r\n return redirect(url_for(\"grp_bp.group_accounts\", group_name=group_name))\r\n\r\n\r\n@grp_bp.route(\"/groups/<group_name>/remove_account\", methods=[\"POST\"])\r\n@login_required\r\ndef remove_account_from_group(group_name):\r\n group = group_from_group_name(group_name)\r\n remove_form = RemoveAccountFromGroup.from_group(group)\r\n if remove_form.validate_on_submit():\r\n account_id = remove_form.name.data\r\n old_account = Account.query.get(account_id)\r\n old_account.status = \"removed\"\r\n db.session.commit()\r\n\r\n return redirect(url_for(\"grp_bp.group_accounts\", group_name=group_name))\r\n\r\n\r\ndef group_from_group_name(group_name):\r\n return Group.query.filter(Group.name == group_name).first()\r\n" }, { "alpha_fraction": 0.6993464231491089, "alphanum_fraction": 0.6993464231491089, "avg_line_length": 45.07692337036133, "blob_id": "fa380f1e9d688d1476ac215a1d920135006ac7ba", "content_id": "9ff7a73345c7d3a29391e31686870320283b23cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1224, "license_type": "no_license", "max_line_length": 110, "num_lines": 26, "path": "/expenses_app/auth/forms.py", "repo_name": "doctor-budoka/shared-expenses-site", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\r\nfrom wtforms import StringField, SubmitField, PasswordField\r\nfrom wtforms.validators import InputRequired, Email, EqualTo\r\n\r\n\r\nclass LogInForm(FlaskForm):\r\n email = StringField(\"Email\", [\r\n InputRequired(message=\"You must provide an email address to continue\"),\r\n Email(message=\"Email entered is not a valid email address\")])\r\n password = PasswordField(\"Password\", [InputRequired(message=\"You must provide a password to continue\")])\r\n submit = SubmitField(\"Submit\")\r\n\r\n\r\nclass Register(FlaskForm):\r\n email = StringField(\"Email\", [\r\n InputRequired(message=\"You must provide an email address to continue\"),\r\n Email(message=\"Email entered is not a valid email address\")])\r\n username = StringField(\r\n \"Username\", [InputRequired(message=\"You must profice a username to continue\")]\r\n )\r\n password = PasswordField(\"Password\", [InputRequired(message=\"You must provide a password to continue\")])\r\n confirm = PasswordField(\"Confirm\", [\r\n InputRequired(message=\"You must provide a password to continue\"),\r\n EqualTo(\"password\", message=\"Password and confirmation must be the same!\")\r\n ])\r\n submit = SubmitField(\"Submit\")\r\n" }, { "alpha_fraction": 0.6578131914138794, "alphanum_fraction": 0.658698558807373, "avg_line_length": 36.28813552856445, "blob_id": "b0dd55d5acb02d4623e79fc14e5c6bf8b9ebdf43", "content_id": "35d52dee4e8fab3d41b34438a41acc70826cc1ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2259, "license_type": "no_license", "max_line_length": 132, "num_lines": 59, "path": "/expenses_app/group/forms.py", "repo_name": "doctor-budoka/shared-expenses-site", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\r\nfrom wtforms import StringField, SubmitField, SelectField, FloatField, BooleanField\r\nfrom wtforms.validators import InputRequired\r\n\r\n\r\nclass CreateGroup(FlaskForm):\r\n name = StringField(\"Name\", [InputRequired(message=\"You must provide a name for the group!\")])\r\n create = SubmitField(\"Create\")\r\n\r\n\r\nclass AddUserToGroup(FlaskForm):\r\n username = StringField(\"Username\", [InputRequired(message=\"You must provide a name for the user!\")])\r\n add = SubmitField(\"Add\")\r\n\r\n\r\nclass RemoveUserFromGroup(FlaskForm):\r\n username = SelectField(\r\n \"Username\", coerce=int, validators=[InputRequired(message=\"You must provide a user to remove!\")])\r\n remove = SubmitField(\"Remove\")\r\n\r\n @classmethod\r\n def from_group(cls, group, current_user):\r\n form = cls()\r\n form.username.choices = [\r\n (member.id, member.username) for member in group.members if member != current_user]\r\n return form\r\n\r\n\r\nclass AddAccountToGroup(FlaskForm):\r\n name = StringField(\"Name\", [InputRequired(message=\"You must provide a name for the account!\")])\r\n user = SelectField(\"User\", coerce=int, default=-1)\r\n starting_balance = FloatField(\"Starting Balance\")\r\n has_balance = BooleanField(\"Has Balance?\", default=False)\r\n add = SubmitField(\"Add\")\r\n\r\n @classmethod\r\n def from_group(cls, group):\r\n add_form = cls()\r\n users_with_avatars = set(account.avatar_for for account in group.accounts if account.is_avatar and account.status == \"live\")\r\n add_form.user.choices = [\r\n (user.id, user.username) for user in group.members if user not in users_with_avatars\r\n ]\r\n add_form.user.choices.append((-1, \"None\"))\r\n return add_form\r\n\r\n\r\nclass RemoveAccountFromGroup(FlaskForm):\r\n name = SelectField(\r\n \"Name\", coerce=int, validators=[InputRequired(message=\"You must provide an account to be removed!\")])\r\n remove = SubmitField(\"Remove\")\r\n\r\n @classmethod\r\n def from_group(cls, group):\r\n remove_form = cls()\r\n remove_form.name.choices = [\r\n (account.id, account.name) for account in group.accounts\r\n if account.status == \"live\" and not account.is_avatar\r\n ]\r\n return remove_form\r\n" }, { "alpha_fraction": 0.6316193342208862, "alphanum_fraction": 0.6323868036270142, "avg_line_length": 29.780487060546875, "blob_id": "452cf549ab91893ff6f2cd69917967a1a25928e2", "content_id": "07a871ffd84818d55ba0df91620e9f5e34cb78fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1303, "license_type": "no_license", "max_line_length": 76, "num_lines": 41, "path": "/expenses_app/commands.py", "repo_name": "doctor-budoka/shared-expenses-site", "src_encoding": "UTF-8", "text": "import click\r\nfrom flask import current_app as app\r\nfrom expenses_app.models import db, AuthorisedEmail, User\r\n\r\n\r\[email protected](\"reset-db\")\r\ndef reset_db():\r\n \"\"\"Used to reset the db for the app\"\"\"\r\n click.echo(\"Resetting db...\")\r\n db.drop_all()\r\n db.create_all()\r\n click.echo(\"Done\")\r\n\r\n\r\[email protected](\"create-auth-emails\")\r\[email protected](\"emails\", nargs=-1)\r\ndef create_authorised_emails(emails):\r\n \"\"\"Adds emails to the Authorised emails db\"\"\"\r\n click.echo(\"Emails added to authorised_email:\")\r\n if emails:\r\n for email in emails:\r\n click.echo(f\"\\t'{email}'\")\r\n new_email = AuthorisedEmail()\r\n new_email.email = email\r\n db.session.add(new_email)\r\n db.session.commit()\r\n\r\n\r\[email protected](\"create-user\")\r\[email protected](\"username\")\r\[email protected](\"password\")\r\[email protected](\"email\")\r\ndef create_user(username, password, email):\r\n \"\"\"Adds a user to the db\"\"\"\r\n click.echo(f\"Creating user with email='{email}', username='{username}'\")\r\n auth_email = AuthorisedEmail.query.filter_by(email=email).first()\r\n if auth_email:\r\n User.create_user(auth_email, password, username)\r\n db.session.commit()\r\n else:\r\n raise ValueError(f\"{email} is not an authorised email address!\")\r\n" }, { "alpha_fraction": 0.6397245526313782, "alphanum_fraction": 0.6446176171302795, "avg_line_length": 35.283782958984375, "blob_id": "5d40c0090332b4cb75bded0f778255d97e1740fd", "content_id": "192c0c73f37d86c4b2659781ab794ac56bd3670d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5518, "license_type": "no_license", "max_line_length": 105, "num_lines": 148, "path": "/expenses_app/models.py", "repo_name": "doctor-budoka/shared-expenses-site", "src_encoding": "UTF-8", "text": "import datetime as dt\r\n\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom werkzeug.security import generate_password_hash, check_password_hash\r\nfrom flask_login import UserMixin\r\n\r\ndb = SQLAlchemy()\r\n\r\n\r\nclass AuthorisedEmail(db.Model):\r\n email_id = db.Column(db.Integer, primary_key=True)\r\n email = db.Column(db.String(120), unique=True)\r\n user = db.relationship(\"User\", uselist=False, back_populates=\"email\")\r\n is_registered = db.Column(db.Boolean, nullable=False, default=False)\r\n\r\n def register_user(self, user):\r\n if self.is_registered:\r\n return False\r\n self.user = user\r\n self.is_registered = True\r\n return True\r\n\r\n def __repr__(self):\r\n return f\"<AuthEmail {self.email}>\"\r\n\r\n\r\ngroup_membership_table = db.Table(\r\n \"group_membership\", db.metadata,\r\n db.Column(\"user_id\", db.Integer, db.ForeignKey(\"user.id\")),\r\n db.Column(\"group_id\", db.Integer, db.ForeignKey(\"group.id\"))\r\n)\r\n\r\n\r\nclass User(UserMixin, db.Model):\r\n id = db.Column(db.Integer, primary_key=True)\r\n email_id = db.Column(\r\n db.Integer,\r\n db.ForeignKey(\"authorised_email.email_id\"),\r\n unique=True,\r\n index=True,\r\n nullable=False\r\n )\r\n email = db.relationship(\"AuthorisedEmail\", back_populates=\"user\")\r\n username = db.Column(db.String(50), unique=True, nullable=False)\r\n password_hash = db.Column(db.String(128), nullable=False)\r\n time_joined = db.Column(db.DateTime, default=dt.datetime.utcnow)\r\n owned_groups = db.relationship(\"Group\", back_populates=\"owner\")\r\n groups = db.relationship(\"Group\", secondary=group_membership_table, back_populates=\"members\")\r\n\r\n def set_password(self, password):\r\n self.password_hash = generate_password_hash(password)\r\n\r\n def check_password(self, password):\r\n return check_password_hash(self.password_hash, password)\r\n\r\n @classmethod\r\n def create_user(cls, email, password, username):\r\n new_user = cls()\r\n new_user.set_password(password)\r\n new_user.email = email\r\n new_user.username = username\r\n if email.register_user(new_user):\r\n return new_user\r\n else:\r\n return None\r\n\r\n def create_group(self, name):\r\n new_group = Group()\r\n new_group.name = name\r\n new_group.owner = self\r\n new_group.members.append(self)\r\n self.groups.append(new_group)\r\n\r\n def __repr__(self):\r\n return f\"<User {self.username}>\"\r\n\r\n\r\nclass Group(db.Model):\r\n id = db.Column(db.Integer, primary_key=True)\r\n name = db.Column(db.String(100), unique=True, index=True, nullable=False)\r\n owner_id = db.Column(db.Integer, db.ForeignKey(\"user.id\"), index=True, nullable=False)\r\n owner = db.relationship(\"User\", back_populates=\"owned_groups\")\r\n\r\n members = db.relationship(\"User\", secondary=group_membership_table, back_populates=\"groups\")\r\n accounts = db.relationship(\"Account\", back_populates=\"group\")\r\n\r\n def has_user(self, user):\r\n return user in self.members\r\n\r\n def add_user(self, new_user):\r\n self.members.append(new_user)\r\n\r\n def remove_user(self, old_user):\r\n self.members.remove(old_user)\r\n\r\n def remove_account(self, old_account):\r\n self.accounts.remove(old_account)\r\n\r\n def __repr__(self):\r\n return f\"<Group {self.id}, {self.name}>\"\r\n\r\n\r\nclass Account(db.Model):\r\n id = db.Column(db.Integer, primary_key=True)\r\n name = db.Column(db.String(100), index=True, nullable=False)\r\n group_id = db.Column(db.Integer, db.ForeignKey(\"group.id\"), index=True, nullable=False)\r\n group = db.relationship(\"Group\", uselist=False, back_populates=\"accounts\")\r\n is_avatar = db.Column(db.Boolean, nullable=False, default=False)\r\n avatar_for_user_id = db.Column(db.Integer, db.ForeignKey(\"user.id\"), nullable=True)\r\n avatar_for = db.relationship(\"User\", uselist=False)\r\n has_balance = db.Column(db.Boolean, default=False, nullable=False)\r\n starting_balance_cents = db.Column(db.Integer, nullable=True)\r\n status = db.Column(db.Enum(\"live\", \"removed\", name=\"account_status\"), nullable=False, default=\"live\")\r\n\r\n db.UniqueConstraint(\"name\", \"group_id\", name=\"uix_group_name\")\r\n\r\n @property\r\n def starting_balance(self):\r\n return round(self.starting_balance_cents / 100, 2) if self.starting_balance is not None else None\r\n\r\n @starting_balance.setter\r\n def starting_balance(self, new_balance):\r\n if new_balance is not None:\r\n self.has_balance = True\r\n self.starting_balance_cents = round(new_balance * 100)\r\n else:\r\n self.has_balance = False\r\n self.starting_balance_cents = None\r\n\r\n @classmethod\r\n def create_account(cls, group, name, user, balance):\r\n new_account = cls()\r\n new_account.group = group\r\n new_account.name = name\r\n new_account.is_avatar = user is not None\r\n new_account.avatar_for = user\r\n new_account.starting_balance = balance\r\n return new_account\r\n\r\n\r\nclass Transactions(db.Model):\r\n id = db.Column(db.Integer, primary_key=True)\r\n group_id = db.Column(db.Integer, db.ForeignKey(\"group.id\"), nullable=False)\r\n paid_by_id = db.Column(db.Integer, db.ForeignKey(\"account.id\"), nullable=False)\r\n on_behalf_of_id = db.Column(db.Integer, db.ForeignKey(\"account.id\"), nullable=False)\r\n description = db.Column(db.Text(200), nullable=True)\r\n store = db.Column(db.Text(100), nullable=True)\r\n amount = db.Column(db.Float, nullable=False)\r\n" }, { "alpha_fraction": 0.7792207598686218, "alphanum_fraction": 0.7792207598686218, "avg_line_length": 37.5, "blob_id": "6f82db3f782a6f644b975df80b3d07675b6892df", "content_id": "be30c3cc8528602ef77868a4737ab58dc038581c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 154, "license_type": "no_license", "max_line_length": 48, "num_lines": 4, "path": "/test-user-setup.sh", "repo_name": "doctor-budoka/shared-expenses-site", "src_encoding": "UTF-8", "text": "flask reset-db\nflask create-auth-emails [email protected] [email protected] [email protected]\nflask create-user new-user password [email protected]\nflask create-user other-user password [email protected]\n" }, { "alpha_fraction": 0.6755218505859375, "alphanum_fraction": 0.6755218505859375, "avg_line_length": 24.350000381469727, "blob_id": "22e97595126813bb768be43d3d9133b88aa52c50", "content_id": "921dbb7984bfb71f2914a761d744c81ff65e36b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 527, "license_type": "no_license", "max_line_length": 68, "num_lines": 20, "path": "/config.py", "repo_name": "doctor-budoka/shared-expenses-site", "src_encoding": "UTF-8", "text": "from os import environ\r\nfrom pathlib import Path\r\nfrom dotenv import load_dotenv\r\n\r\nBASE_DIRECTORY = Path(__file__).parent\r\nload_dotenv(BASE_DIRECTORY / \".env\")\r\n\r\n\r\nclass Config:\r\n FLASK_ENV = \"development\"\r\n TESTING = True\r\n DEBUG = True\r\n SECRET_KEY = environ.get(\"SECRET_KEY\")\r\n STATIC_FOLDER = \"static\"\r\n TEMPLATES_FOLDER = \"templates\"\r\n\r\n # Database values\r\n SQLALCHEMY_DATABASE_URI = environ.get(\"SQLALCHEMY_DATABASE_URI\")\r\n SQLALCHEMY_TRACK_MODIFICATIONS = False\r\n SQLALCHEMY_ECHO = True\r\n" }, { "alpha_fraction": 0.6258205771446228, "alphanum_fraction": 0.6269146800041199, "avg_line_length": 31.851852416992188, "blob_id": "c94caefec4e74c7568a17f42e96fdc587c7737e0", "content_id": "1c12aaa4e96ed5c0e907d60aa705766ca6a28a14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2742, "license_type": "no_license", "max_line_length": 84, "num_lines": 81, "path": "/expenses_app/auth/auth.py", "repo_name": "doctor-budoka/shared-expenses-site", "src_encoding": "UTF-8", "text": "from flask import url_for, flash, render_template, make_response\r\nfrom flask import Blueprint\r\nfrom flask_login import login_user, login_required, logout_user\r\nfrom werkzeug.utils import redirect\r\n\r\nfrom expenses_app import db, login_manager\r\nfrom expenses_app.auth.forms import LogInForm, Register\r\nfrom expenses_app.models import AuthorisedEmail, User\r\n\r\n\r\nauth_bp = Blueprint(\r\n 'auth_bp', __name__,\r\n template_folder='templates',\r\n static_folder='static'\r\n)\r\n\r\n\r\n@auth_bp.route(\"/login\", methods=[\"GET\", \"POST\"])\r\ndef login():\r\n form = LogInForm()\r\n if form.validate_on_submit():\r\n email = form.email.data\r\n password = form.password.data\r\n email = AuthorisedEmail.query.filter(AuthorisedEmail.email == email).first()\r\n if email and email.user and email.user.check_password(password):\r\n user = email.user\r\n login_user(user)\r\n return redirect(url_for(\"grp_bp.index\"))\r\n else:\r\n # TODO: Limit number of retries\r\n flash(\"Invalid email or password!\")\r\n\r\n return render_template(\"login.html\", form=form)\r\n\r\n\r\n@auth_bp.route(\"/register\", methods=[\"GET\", \"POST\"])\r\ndef register():\r\n form = Register()\r\n if form.validate_on_submit():\r\n email = form.email.data\r\n username = form.username.data\r\n\r\n username_exists = User.query.filter_by(username=username).first()\r\n auth_email = AuthorisedEmail.query.filter_by(email=email).first()\r\n if auth_email and auth_email.is_registered:\r\n flash(\"You are already registered! Try logging in instead!\")\r\n elif auth_email and username_exists:\r\n flash(\"That username already exists! Try another\")\r\n elif auth_email:\r\n password = form.password.data\r\n user = User.create_user(auth_email, password, username)\r\n db.session.commit()\r\n if user:\r\n login_user(user)\r\n return redirect(url_for(\"grp_bp.index\"))\r\n else:\r\n # TODO: Handle these errors more nicely\r\n return make_response(\"Something went wrong with registration!\", 500)\r\n else:\r\n flash(\"Email is not an authorised email! This is a private service.\")\r\n return render_template(\"register.html\", form=form)\r\n\r\n\r\n@auth_bp.route(\"/logout\")\r\n@login_required\r\ndef logout():\r\n logout_user()\r\n return redirect(url_for(\"auth_bp.login\"))\r\n\r\n\r\n@login_manager.user_loader\r\ndef load_user(user_id):\r\n if user_id is not None:\r\n return User.query.get(user_id)\r\n return None\r\n\r\n\r\n@login_manager.unauthorized_handler\r\ndef unauthorized():\r\n flash('You must be logged in to view that page.')\r\n return redirect(url_for('auth_bp.login'))\r\n" }, { "alpha_fraction": 0.6552845239639282, "alphanum_fraction": 0.6552845239639282, "avg_line_length": 23.625, "blob_id": "2e955dfbb238596210dafa8045d2694f5328a279", "content_id": "186b4e4e9714ac86fbd4d9a4ffb244e00fdaf9ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 615, "license_type": "no_license", "max_line_length": 54, "num_lines": 24, "path": "/expenses_app/__init__.py", "repo_name": "doctor-budoka/shared-expenses-site", "src_encoding": "UTF-8", "text": "from flask import Flask\r\nfrom expenses_app.models import db\r\nfrom flask_login import LoginManager\r\n\r\nlogin_manager = LoginManager()\r\n\r\n\r\ndef create_app():\r\n app = Flask(__name__, template_folder=\"templates\")\r\n app.config.from_object(\"config.Config\")\r\n db.init_app(app)\r\n login_manager.init_app(app)\r\n\r\n with app.app_context():\r\n from expenses_app.auth import auth\r\n app.register_blueprint(auth.auth_bp)\r\n\r\n from expenses_app.group import group\r\n app.register_blueprint(group.grp_bp)\r\n\r\n from expenses_app import commands\r\n\r\n db.create_all()\r\n return app\r\n" } ]
10
sandeshkha/DataAnalysis_Sales
https://github.com/sandeshkha/DataAnalysis_Sales
a0b25bef97e1e46c95c878ea63002d056b982353
f1979effdc30c4d7f4c6c435c944be5b8fc581e9
b56137952f3a3b683519670260a5970e122de236
refs/heads/master
2022-12-25T21:55:54.653566
2020-10-07T20:25:22
2020-10-07T20:25:22
301,859,452
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6979166865348816, "alphanum_fraction": 0.7052364945411682, "avg_line_length": 28.355371475219727, "blob_id": "170d2f2ab4de641eb8f8b343746a466db71cad32", "content_id": "46b79c52c740533be9026343fc11008429bea9fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3552, "license_type": "no_license", "max_line_length": 98, "num_lines": 121, "path": "/main.py", "repo_name": "sandeshkha/DataAnalysis_Sales", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport glob\nimport os\nimport matplotlib.pyplot as plt\nfrom itertools import combinations\nfrom collections import Counter\n\n#combining multiple csv files into one file\nos.chdir('/Sales_Data')\n\nextension = 'csv'\nall_filenames = [i for i in glob.glob(('*.{}'.format(extension)))]\n\ncombined_csv = pd.concat([pd.read_csv(f) for f in all_filenames])\n\ncombined_csv.to_csv(\"totalsales_csv.csv\", index=False, encoding='utf-8-sig')\n\n\n# read the updated dataframe\nall_data = pd.read_csv('totalsales_csv.csv')\n\n#Clean up data\n#find data with NaN\nnan_df = all_data[all_data.isna().any(axis=1)]\n\n#Drop all NaN from data\nall_data = all_data.dropna(how='all')\n\n#Get the month and put it in a new column\nall_data = all_data[all_data['Order Date'].str[0:2] != 'Or']\n\n#Augment data with additional columns\n##Month column added\nall_data['Month'] = all_data['Order Date'].str[0:2]\nall_data['Month'] = all_data['Month'].astype('int32')\n\n#Add column total sales Quantity * Price Each\nall_data['Quantity Ordered'] = pd.to_numeric(all_data['Quantity Ordered'])\nall_data['Price Each'] = pd.to_numeric(all_data['Price Each'])\n\nall_data['Total Sales'] = all_data['Quantity Ordered'] * all_data['Price Each']\n\n#What month had the higest sales\nresults = all_data.groupby('Month').sum()\n\n#What city had the most sales\ndef get_city(address):\n return address.split(',')[1]\n\ndef get_state(address):\n return address.split(',')[2].split(' ')[1]\n\n# Get city and state in a seprate coulumn\nall_data['City'] = all_data['Purchase Address'].apply(lambda x: f\"{get_city(x)} ({get_state(x)})\")\n\n# Plot City Sales Data\ncities = [city for city, df in all_data.groupby('City')]\nCity = all_data['City'].unique()\nplt.bar(cities, results['Sales'])\nplt.xticks('cities', rotation ='vertical', size = 8)\nplt.ylabel('US Cities')\nplt.xlabel('Sales in USD')\nplt.show()\n\n#Time to display advertisments\n\n#Covert Order date to datetime function\nall_data['Order Date'] = pd.to_datetime(all_data['Order Date'])\n\nall_data['Hour'] = all_data['Order Date'].dt.hour\nall_data['Minute'] = all_data['Order Date'].dt.minute\n\n#Graph the sales by the time\nhours = [hour for hour, df in all_data.groupby('Hour')]\n\nplt.plot(hours, all_data.groupby(['Hours']).count())\nplt.xticks(hours)\nplt.grid()\nplt.xlabel('Hour')\nplt.ylabel('Number of orders')\n\n#Create a new dataframe to group all ordered items together\ndf = all_data[all_data['Order ID'].duplicated(keep=False)]\ndf['Grouped'] = df.groupby('Order ID')['Product'].transform(lambda x: ','.join(x))\ndf = df[['Order ID', 'Grouped']].drop_duplicates()\n\ncount = Counter()\n\n# The two most grouped product in sale\nfor row in df['Grouped']:\n row_list = row.split(',')\n count.update(Counter(combinations(row_list, 2)))\n\nfor key, value in count.most_common(10):\n print(key,value)\n\n#\nproduct_data = all_data.groupby['Product']\nquantity_ordered = product_data.sum()['Quantity Ordered']\n\nproducts = [product for product, df in product_data]\n\n#Graph Products and the quantity ordered\nplt.bar(products, quantity_ordered)\nplt.xticks(products, rotation ='vertical', size = 8)\nplt.ylabel('Quantity Ordered')\nplt.xlabel('Product')\nplt.show()\n\n#Comparing two graphs with quantiy and price of the products\nprices = all_data.groupby('Product').mean()['Price Each']\n\nfig, ax1 = plt.subplots()\nax2 = ax1.twinx()\nax1.bar(products, quantity_ordered, 'g-')\nax2.bar(products, prices, 'b-')\n\nax1.set_xlabel(\"Product Name\")\nax1.set_xlabel(\"Quantity Ordered\", color='g')\nax2.set_ylabel(\"Price ($)\", color='b')\nax1.set_xticklabels(products, rotaion='vertical', size=8)\n" }, { "alpha_fraction": 0.7833333611488342, "alphanum_fraction": 0.7833333611488342, "avg_line_length": 59, "blob_id": "b360bbf7fc31bd74964b2877732457bd58d8769c", "content_id": "14a9d9c73e84e13dc2a301f104e628cfa15853d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 60, "license_type": "no_license", "max_line_length": 59, "num_lines": 1, "path": "/DataUsed/ReadMe.txt", "repo_name": "sandeshkha/DataAnalysis_Sales", "src_encoding": "UTF-8", "text": "Here is the Sales Date used to do analysis for the project.\n" } ]
2
dchen496/remote-power-button
https://github.com/dchen496/remote-power-button
53046748c15faad9148158c4a7be0691ebf96490
32d4d3961559cb72ccf54a29bf6fdff0c2d09d92
1af8a0c2174b0f710cd6da0a8a1f9e8f1c1bfe52
refs/heads/master
2021-01-17T10:19:13.875176
2018-12-02T00:24:00
2018-12-02T00:24:00
58,010,343
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6051998138427734, "alphanum_fraction": 0.6220510601997375, "avg_line_length": 30.469696044921875, "blob_id": "cc82468a2f6d3e72a53a26f4aa70e1a2e9f063a7", "content_id": "91883bd27d138711ec7092248614705ad2fb2991", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2077, "license_type": "no_license", "max_line_length": 87, "num_lines": 66, "path": "/reboot.py", "repo_name": "dchen496/remote-power-button", "src_encoding": "UTF-8", "text": "import json\nimport hashlib\nimport getpass\nimport argparse\nimport urllib2\nimport os\n\nhost = 'http://soba.mit.edu'\npbkdf2_rounds = 1000000\npw_hash_len = 32\n\ndef hash_password(pw, salt=None):\n if salt is None:\n salt = os.urandom(pw_hash_len)\n h = hashlib.pbkdf2_hmac('sha256', pw, salt, pbkdf2_rounds, pw_hash_len)\n return h, salt\n\ndef print_password_hash():\n pw = getpass.getpass()\n confirm = getpass.getpass()\n if pw != confirm:\n print 'passwords do not match'\n return\n h, salt = hash_password(pw)\n hash_hex = ', '.join([ '0x'+b.encode('hex') for b in h ])\n print 'static const char password_hash[{}] = {{ {} }};'.format(len(h), hash_hex)\n print '#define PASSWORD_SALT_HEX \"{}\"'.format(salt.encode('hex'))\n\ndef reboot(length):\n if length < 0 or length > 255:\n raise ValueError(\"Length must be between 0 and 255.\")\n length_hex = \"%0.2x\" % length\n\n pw = getpass.getpass()\n\n challenge_json = urllib2.urlopen(urllib2.Request(host + '/challenge')).read()\n challenge_obj = json.loads(challenge_json)\n challenge = challenge_obj['challenge'].decode('hex')\n salt = challenge_obj['salt'].decode('hex')\n\n pw_hash, salt = hash_password(pw, salt)\n h = hashlib.sha256(pw_hash + challenge).digest()\n h_hex = h.encode('hex')\n\n req = urllib2.Request(host + '/reboot/' + h_hex + '/' + length_hex, '')\n resp = urllib2.urlopen(req)\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Reboot a remote computer.')\n parser.add_argument('-p, --password-hash', help='Generate password hash.',\n dest='hash_password', action='store_true')\n parser.add_argument('-l, --length', help='Time to press power button (in seconds)',\n dest='length', type=int, default='1')\n parser.add_argument('-t, --test', help='Test remote endpoint',\n dest='test', action='store_true')\n args = parser.parse_args()\n if args.hash_password:\n print_password_hash()\n elif test:\n test()\n else:\n reboot(args.length)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6199411749839783, "alphanum_fraction": 0.6454278230667114, "avg_line_length": 26.567567825317383, "blob_id": "f94a69048a38326ec2e0a9447c97978239b5133e", "content_id": "28d1604c79ae80ec9211a36b6180ace90b564007", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7141, "license_type": "no_license", "max_line_length": 117, "num_lines": 259, "path": "/remote-power-button.ino", "repo_name": "dchen496/remote-power-button", "src_encoding": "UTF-8", "text": "#include <limits.h>\n#include <ctype.h>\n#include <avr/pgmspace.h>\n\n// https://github.com/jcw/ethercard\n#include <EtherCard.h>\n// https://github.com/rweather/arduinolibs\n#include \"Crypto/Crypto.h\"\n#include \"Crypto/SHA256.h\"\n#include \"Crypto/RNG.h\"\n\n// Use reboot.py to generate the password hash and the salt.\n\n#define HOSTNAME \"soba.mit.edu\"\n#define ETHERNET_CS_PIN 10\nconst static byte mac[] = { 0x30, 0xd2, 0x7d, 0x04, 0x93, 0x0d };\nconst static byte ip[] = { 18, 102, 218, 11 };\nconst static byte gateway[] = { 18, 102, 218, 1 };\nbyte Ethernet::buffer[512];\nstatic BufferFiller bfill;\nstatic char *rxdata;\nstatic uint16_t rxdata_len;\n\n#define RNG_EEPROM_ADDR 0\n\n#define CHALLENGE_EXPIRY 30000 // 30 seconds\n#define CHALLENGE_SIZE 32\nstatic uint8_t challenge[CHALLENGE_SIZE];\nstatic char challenge_hex[2*CHALLENGE_SIZE + 1];\nstatic long challenge_issued;\nstatic bool challenge_valid = false;\n\nstatic uint8_t expected_hash[CHALLENGE_SIZE];\nstatic uint8_t actual_hash[CHALLENGE_SIZE];\n\n#define SWITCH_PIN 19 // pin A5\nstatic uint8_t press_length;\n\nstatic const char get_challenge_route[] PROGMEM = \"GET /challenge\";\nstatic const char post_reboot_route[] PROGMEM = \"POST /reboot/\"; // POST /reboot/[SHA256(password_hash || challenge)]\n\nstatic SHA256 sha256;\n\nstatic void fail() {\n while (1);\n}\n\nvoid setup() {\n Serial.begin(115200);\n\n // pins\n digitalWrite(SWITCH_PIN, HIGH);\n pinMode(SWITCH_PIN, OUTPUT);\n\n // RNG\n Serial.println(F(\"Generating entropy.\"));\n RNG.begin(HOSTNAME, RNG_EEPROM_ADDR);\n // wait for some initial entropy\n while (!RNG.available(CHALLENGE_SIZE))\n RNG.loop();\n\n // Ethernet\n byte firmware_version = ether.begin(sizeof Ethernet::buffer, mac, ETHERNET_CS_PIN);\n Serial.print(\"Firmware version: \");\n Serial.println(firmware_version);\n if (firmware_version == 0)\n {\n Serial.println(F(\"Failed to access Ethernet controller\"));\n fail();\n }\n ether.staticSetup(ip, gateway);\n ether.printIp(\"IP: \", ether.myip);\n ether.printIp(\"Gateway: \", ether.gwip);\n}\n\nstatic void to_hex(uint8_t *in, char *out, size_t nbytes) {\n for (int i = 0; i < nbytes; i++) {\n uint8_t upper = in[i] >> 4;\n out[2*i] = upper < 10 ? upper + '0' : upper - 10 + 'a';\n uint8_t lower = in[i] & 0xf;\n out[2*i+1] = lower < 10 ? lower + '0' : lower - 10 + 'a';\n }\n out[2*nbytes] = '\\0';\n}\n\nstatic void from_hex(char *in, uint8_t *out, size_t nbytes) {\n for (int i = 0; i < nbytes; i++) {\n uint8_t upper = isalpha(in[2*i]) ? in[2*i] - 'a' + 10 : in[2*i] - '0';\n uint8_t lower = isalpha(in[2*i+1]) ? in[2*i+1] - 'a' + 10 : in[2*i+1] - '0';\n out[i] = upper << 4 | lower;\n }\n}\n\nstatic word handle_get_challenge() {\n long now = millis();\n if (challenge_valid && now - challenge_issued < CHALLENGE_EXPIRY) {\n Serial.println(F(\"Reusing challenge.\"));\n } else {\n Serial.print(F(\"Generating challenge: \"));\n challenge_issued = now;\n challenge_valid = true;\n\n // This is sufficient (combined with the initial RNG seeding)\n // to ensure challenges have a very low probability of being reused\n // and also that the attacker cannot predict the next challenge.\n RNG.rand(challenge, sizeof(challenge));\n // This isn't really necessary, but just in case.\n sha256.reset();\n sha256.update(challenge, sizeof(challenge));\n sha256.finalize(challenge, sizeof(challenge));\n to_hex(challenge, challenge_hex, sizeof(challenge));\n\n Serial.println(challenge_hex);\n }\n\n bfill = ether.tcpOffset();\n bfill.emit_p(PSTR(\n \"HTTP/1.1 200 OK\\r\\n\"\n \"Cache-Control: no-cache\\r\\n\"\n \"Content-Type: application/json\\r\\n\"\n \"\\r\\n\"\n \"{\\\"challenge\\\": \\\"$S\\\", \\\"salt\\\": \\\"\" PASSWORD_SALT_HEX \"\\\"}\"\n ), challenge_hex);\n Serial.println(F(\"Request completed.\"));\n return bfill.position();\n}\n\nstatic void bad_request() {\n bfill.emit_p(PSTR(\n \"HTTP/1.1 400 Bad Request\\r\\n\"\n \"Cache-Control: no-cache\\r\\n\"\n \"\\r\\n\"\n ));\n Serial.println(F(\"Bad request.\"));\n}\n\nstatic void forbidden() {\n bfill.emit_p(PSTR(\n \"HTTP/1.1 403 Forbidden\\r\\n\"\n \"Cache-Control: no-cache\\r\\n\"\n \"\\r\\n\"\n ));\n Serial.println(F(\"Forbidden request.\"));\n}\n\nstatic void reboot() {\n Serial.print(F(\"Pressing power button for \"));\n Serial.print(press_length);\n Serial.println(F(\" seconds.\"));\n digitalWrite(SWITCH_PIN, LOW);\n delay(press_length * 1000L);\n digitalWrite(SWITCH_PIN, HIGH);\n Serial.println(F(\"Unpressing power button.\"));\n}\n\nstatic word handle_post_reboot() {\n // compute expected hash\n sha256.reset();\n sha256.update(password_hash, sizeof(password_hash));\n sha256.update(challenge, sizeof(challenge));\n sha256.finalize(expected_hash, sizeof(expected_hash));\n\n char *remaining = rxdata + strlen(post_reboot_route);\n uint16_t remaining_len = rxdata_len - strlen(post_reboot_route);\n\n // check length\n if (remaining_len < sizeof(expected_hash)*2 + 3) {\n bad_request();\n return bfill.position();\n }\n\n // check against actual hash\n from_hex(remaining, actual_hash, sizeof(actual_hash));\n for (int i = 0; i < sizeof(expected_hash); i++) {\n if (actual_hash[i] != expected_hash[i]) {\n forbidden();\n return bfill.position();\n }\n }\n\n // check expiry\n long now = millis();\n if (!challenge_valid || now - challenge_issued >= CHALLENGE_EXPIRY) {\n Serial.println(F(\"Challenge invalid/expired.\"));\n forbidden();\n return bfill.position();\n }\n // invalidate challenge\n challenge_valid = false;\n\n // get the press length\n remaining += sizeof(expected_hash) * 2 + 1;\n remaining_len -= sizeof(expected_hash) * 2 + 1;\n if (remaining_len < 2) {\n bad_request();\n return bfill.position();\n }\n // read the length\n from_hex(remaining, &press_length, sizeof(press_length));\n\n bfill.emit_p(PSTR(\n \"HTTP/1.1 204 No Content\\r\\n\"\n \"Cache-Control: no-cache\\r\\n\"\n \"\\r\\n\"\n ));\n\n Serial.println(F(\"Request completed.\"));\n return bfill.position();\n}\n\n// requires a flash string\nstatic bool match_route(const char *route) {\n int route_len = strlen_P(route);\n bool ret = rxdata_len >= route_len && strncmp_P(rxdata, route, route_len) == 0;\n if (ret) {\n Serial.print(\"Matched route \");\n Serial.println((const __FlashStringHelper *) route);\n }\n return ret;\n}\n\nvoid loop() {\n RNG.loop();\n\n word len = ether.packetReceive();\n word pos = ether.packetLoop(len);\n\n // check if valid tcp data is received\n if (pos) {\n long now = millis();\n // protect against overflow by invalidating whenever now is before the\n // challenge was issued\n if (now - challenge_issued >= CHALLENGE_EXPIRY || now < challenge_issued) {\n challenge_valid = false;\n }\n\n // help the RNG a bit, but don't give it entropy credit\n RNG.stir((uint8_t *) &now, sizeof(now), 0);\n\n rxdata = (char *) Ethernet::buffer + pos;\n rxdata_len = len - pos;\n bfill = ether.tcpOffset();\n word txpos;\n if (match_route(get_challenge_route)) {\n txpos = handle_get_challenge();\n } else if (match_route(post_reboot_route)) {\n txpos = handle_post_reboot();\n } else {\n return;\n }\n ether.httpServerReply(txpos); // send web page data\n pos = 0;\n }\n\n if (press_length > 0) {\n reboot();\n press_length = 0;\n }\n}\n\n" }, { "alpha_fraction": 0.44391560554504395, "alphanum_fraction": 0.48533573746681213, "avg_line_length": 27.528440475463867, "blob_id": "0d8e647f73c58535bfb8483601f62fbdad2ba3f9", "content_id": "a3a9d7f0d06fba32d9e70bb16d88009dfa3e6b55", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 15548, "license_type": "permissive", "max_line_length": 79, "num_lines": 545, "path": "/Crypto/SpeckLowMemory.cpp", "repo_name": "dchen496/remote-power-button", "src_encoding": "UTF-8", "text": "/*\n * Copyright (C) 2015 Southern Storm Software, Pty Ltd.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n#include \"SpeckLowMemory.h\"\n#include \"Crypto.h\"\n#include \"utility/RotateUtil.h\"\n#include \"utility/EndianUtil.h\"\n#include <string.h>\n\n/**\n * \\class SpeckLowMemory SpeckLowMemory.h <SpeckLowMemory.h>\n * \\brief Speck block cipher with a 128-bit block size (low-memory version).\n *\n * This class differs from the Speck class in the following ways:\n *\n * \\li RAM requirements are vastly reduced. The key (up to 256 bits) is\n * stored directly and then expanded to the full key schedule round by round.\n * The setKey() method is very fast because of this.\n * \\li Performance of encryptBlock() is slower than for Speck due to\n * expanding the key on the fly rather than ahead of time.\n * \\li The decryptBlock() function is not supported, which means that CBC\n * mode cannot be used but the CTR, CFB, OFB, and GCM modes can be used.\n *\n * This class is useful when RAM is at a premium, CBC mode is not required,\n * and reduced encryption performance is not a hindrance to the application.\n * Even though the performance of encryptBlock() is reduced, this class is\n * still faster than AES with equivalent key sizes.\n *\n * See the documentation for the Speck class for more information on the\n * Speck family of block ciphers.\n *\n * References: https://en.wikipedia.org/wiki/Speck_%28cipher%29,\n * http://eprint.iacr.org/2013/404\n *\n * \\sa Speck\n */\n\n// The \"avr-gcc\" compiler doesn't do a very good job of compiling\n// code involving 64-bit values. So we have to use inline assembly.\n// It also helps to break the state up into 32-bit quantities\n// because \"asm\" supports register names like %A0, %B0, %C0, %D0\n// for the bytes in a 32-bit quantity, but it does not support\n// %E0, %F0, %G0, %H0 for the high bytes of a 64-bit quantity.\n#if defined(__AVR__)\n#define USE_AVR_INLINE_ASM 1\n#endif\n\n/**\n * \\brief Constructs a low-memory Speck block cipher with no initial key.\n *\n * This constructor must be followed by a call to setKey() before the\n * block cipher can be used for encryption.\n */\nSpeckLowMemory::SpeckLowMemory()\n : rounds(32)\n{\n}\n\nSpeckLowMemory::~SpeckLowMemory()\n{\n clean(k);\n}\n\nsize_t SpeckLowMemory::blockSize() const\n{\n return 16;\n}\n\nsize_t SpeckLowMemory::keySize() const\n{\n // Also supports 128-bit and 192-bit, but we only report 256-bit.\n return 32;\n}\n\n// Pack/unpack byte-aligned big-endian 64-bit quantities.\n#define pack64(data, value) \\\n do { \\\n uint64_t v = htobe64((value)); \\\n memcpy((data), &v, sizeof(uint64_t)); \\\n } while (0)\n#define unpack64(value, data) \\\n do { \\\n memcpy(&(value), (data), sizeof(uint64_t)); \\\n (value) = be64toh((value)); \\\n } while (0)\n\nbool SpeckLowMemory::setKey(const uint8_t *key, size_t len)\n{\n#if USE_AVR_INLINE_ASM\n // Determine the number of rounds to use and validate the key length.\n if (len == 32) {\n rounds = 34;\n } else if (len == 24) {\n rounds = 33;\n } else if (len == 16) {\n rounds = 32;\n } else {\n return false;\n }\n\n // Copy the bytes of the key into the \"k\" array in reverse order to\n // convert big endian into little-endian.\n __asm__ __volatile__ (\n \"1:\\n\"\n \"ld __tmp_reg__,-Z\\n\"\n \"st X+,__tmp_reg__\\n\"\n \"dec %2\\n\"\n \"brne 1b\\n\"\n : : \"x\"(k), \"z\"(key + len), \"r\"(len)\n );\n#else\n if (len == 32) {\n rounds = 34;\n unpack64(k[3], key);\n unpack64(k[2], key + 8);\n unpack64(k[1], key + 16);\n unpack64(k[0], key + 24);\n } else if (len == 24) {\n rounds = 33;\n unpack64(k[2], key);\n unpack64(k[1], key + 8);\n unpack64(k[0], key + 16);\n } else if (len == 16) {\n rounds = 32;\n unpack64(k[1], key);\n unpack64(k[0], key + 8);\n } else {\n return false;\n }\n#endif\n return true;\n}\n\nvoid SpeckLowMemory::encryptBlock(uint8_t *output, const uint8_t *input)\n{\n#if USE_AVR_INLINE_ASM\n uint64_t l[4];\n uint32_t xlow, xhigh, ylow, yhigh;\n uint32_t slow, shigh;\n uint8_t li_in = 0;\n uint8_t li_out = (rounds - 31) * 8;\n\n // Copy the \"k\" array into \"s\" and the \"l\" array.\n __asm__ __volatile__ (\n \"ldd r25,%4\\n\" // r25 = li_out\n\n \"ld __tmp_reg__,Z+\\n\"\n \"std %A0,__tmp_reg__\\n\"\n \"ld __tmp_reg__,Z+\\n\"\n \"std %B0,__tmp_reg__\\n\"\n \"ld __tmp_reg__,Z+\\n\"\n \"std %C0,__tmp_reg__\\n\"\n \"ld __tmp_reg__,Z+\\n\"\n \"std %D0,__tmp_reg__\\n\"\n \"ld __tmp_reg__,Z+\\n\"\n \"std %A1,__tmp_reg__\\n\"\n \"ld __tmp_reg__,Z+\\n\"\n \"std %B1,__tmp_reg__\\n\"\n \"ld __tmp_reg__,Z+\\n\"\n \"std %C1,__tmp_reg__\\n\"\n \"ld __tmp_reg__,Z+\\n\"\n \"std %D1,__tmp_reg__\\n\"\n\n \"1:\\n\" // l[0..] = k[1..]\n \"ld __tmp_reg__,Z+\\n\"\n \"st X+,__tmp_reg__\\n\"\n \"dec r25\\n\"\n \"brne 1b\\n\"\n : \"=Q\"(slow), \"=Q\"(shigh)\n : \"z\"(k), \"x\"(l), \"Q\"(li_out)\n : \"r25\"\n );\n\n // Unpack the input into the x and y variables, converting\n // from big-endian into little-endian in the process.\n __asm__ __volatile__ (\n \"ld %D1,Z\\n\"\n \"ldd %C1,Z+1\\n\"\n \"ldd %B1,Z+2\\n\"\n \"ldd %A1,Z+3\\n\"\n \"ldd %D0,Z+4\\n\"\n \"ldd %C0,Z+5\\n\"\n \"ldd %B0,Z+6\\n\"\n \"ldd %A0,Z+7\\n\"\n \"ldd %D3,Z+8\\n\"\n \"ldd %C3,Z+9\\n\"\n \"ldd %B3,Z+10\\n\"\n \"ldd %A3,Z+11\\n\"\n \"ldd %D2,Z+12\\n\"\n \"ldd %C2,Z+13\\n\"\n \"ldd %B2,Z+14\\n\"\n \"ldd %A2,Z+15\\n\"\n : \"=r\"(xlow), \"=r\"(xhigh), \"=r\"(ylow), \"=r\"(yhigh)\n : \"z\"(input)\n );\n\n // Perform all encryption rounds while expanding the key schedule in-place.\n __asm__ __volatile__ (\n \"mov r23,__zero_reg__\\n\" // i = 0\n \"1:\\n\"\n\n // Adjust x and y for this round using the key schedule word s.\n\n // x = (rightRotate8_64(x) + y) ^ s;\n \"mov __tmp_reg__,%A0\\n\" // x = rightRotate8_64(x)\n \"mov %A0,%B0\\n\"\n \"mov %B0,%C0\\n\"\n \"mov %C0,%D0\\n\"\n \"mov %D0,%A1\\n\"\n \"mov %A1,%B1\\n\"\n \"mov %B1,%C1\\n\"\n \"mov %C1,%D1\\n\"\n \"mov %D1,__tmp_reg__\\n\"\n\n \"add %A0,%A2\\n\" // x += y\n \"adc %B0,%B2\\n\"\n \"adc %C0,%C2\\n\"\n \"adc %D0,%D2\\n\"\n \"adc %A1,%A3\\n\"\n \"adc %B1,%B3\\n\"\n \"adc %C1,%C3\\n\"\n \"adc %D1,%D3\\n\"\n\n \"ldd __tmp_reg__,%A4\\n\" // x ^= s\n \"eor %A0,__tmp_reg__\\n\"\n \"ldd __tmp_reg__,%B4\\n\"\n \"eor %B0,__tmp_reg__\\n\"\n \"ldd __tmp_reg__,%C4\\n\"\n \"eor %C0,__tmp_reg__\\n\"\n \"ldd __tmp_reg__,%D4\\n\"\n \"eor %D0,__tmp_reg__\\n\"\n \"ldd __tmp_reg__,%A5\\n\"\n \"eor %A1,__tmp_reg__\\n\"\n \"ldd __tmp_reg__,%B5\\n\"\n \"eor %B1,__tmp_reg__\\n\"\n \"ldd __tmp_reg__,%C5\\n\"\n \"eor %C1,__tmp_reg__\\n\"\n \"ldd __tmp_reg__,%D5\\n\"\n \"eor %D1,__tmp_reg__\\n\"\n\n // y = leftRotate3_64(y) ^ x;\n \"lsl %A2\\n\" // y = leftRotate1_64(y)\n \"rol %B2\\n\"\n \"rol %C2\\n\"\n \"rol %D2\\n\"\n \"rol %A3\\n\"\n \"rol %B3\\n\"\n \"rol %C3\\n\"\n \"rol %D3\\n\"\n \"adc %A2,__zero_reg__\\n\"\n\n \"lsl %A2\\n\" // y = leftRotate1_64(y)\n \"rol %B2\\n\"\n \"rol %C2\\n\"\n \"rol %D2\\n\"\n \"rol %A3\\n\"\n \"rol %B3\\n\"\n \"rol %C3\\n\"\n \"rol %D3\\n\"\n\n \"adc %A2,__zero_reg__\\n\"\n \"lsl %A2\\n\" // y = leftRotate1_64(y)\n \"rol %B2\\n\"\n \"rol %C2\\n\"\n \"rol %D2\\n\"\n \"rol %A3\\n\"\n \"rol %B3\\n\"\n \"rol %C3\\n\"\n \"rol %D3\\n\"\n \"adc %A2,__zero_reg__\\n\"\n\n \"eor %A2,%A0\\n\" // y ^= x\n \"eor %B2,%B0\\n\"\n \"eor %C2,%C0\\n\"\n \"eor %D2,%D0\\n\"\n \"eor %A3,%A1\\n\"\n \"eor %B3,%B1\\n\"\n \"eor %C3,%C1\\n\"\n \"eor %D3,%D1\\n\"\n\n // On the last round we don't need to compute s so we\n // can exit early here if (i + 1) == rounds.\n \"mov __tmp_reg__,r23\\n\" // temp = i + 1\n \"inc __tmp_reg__\\n\"\n \"cp __tmp_reg__,%9\\n\" // if (temp == rounds) ...\n \"brne 2f\\n\"\n \"rjmp 3f\\n\"\n \"2:\\n\"\n\n // Save x and y on the stack so we can reuse registers for t and s.\n \"push %A0\\n\"\n \"push %B0\\n\"\n \"push %C0\\n\"\n \"push %D0\\n\"\n \"push %A1\\n\"\n \"push %B1\\n\"\n \"push %C1\\n\"\n \"push %D1\\n\"\n \"push %A2\\n\"\n \"push %B2\\n\"\n \"push %C2\\n\"\n \"push %D2\\n\"\n \"push %A3\\n\"\n \"push %B3\\n\"\n \"push %C3\\n\"\n \"push %D3\\n\"\n\n // Compute the key schedule word s for the next round.\n\n // l[li_out] = (s + rightRotate8_64(l[li_in])) ^ i;\n \"ldd r24,%6\\n\" // Z = &(l[li_in])\n \"add %A8,r24\\n\"\n \"adc %B8,__zero_reg__\\n\"\n\n \"ld %D1,Z+\\n\" // t = rightRotate8_64(l[li_in])\n \"ld %A0,Z+\\n\"\n \"ld %B0,Z+\\n\"\n \"ld %C0,Z+\\n\"\n \"ld %D0,Z+\\n\"\n \"ld %A1,Z+\\n\"\n \"ld %B1,Z+\\n\"\n \"ld %C1,Z+\\n\"\n\n \"ldd %A2,%A4\\n\" // load s\n \"ldd %B2,%B4\\n\"\n \"ldd %C2,%C4\\n\"\n \"ldd %D2,%D4\\n\"\n \"ldd %A3,%A5\\n\"\n \"ldd %B3,%B5\\n\"\n \"ldd %C3,%C5\\n\"\n \"ldd %D3,%D5\\n\"\n\n \"add %A0,%A2\\n\" // t += s\n \"adc %B0,%B2\\n\"\n \"adc %C0,%C2\\n\"\n \"adc %D0,%D2\\n\"\n \"adc %A1,%A3\\n\"\n \"adc %B1,%B3\\n\"\n \"adc %C1,%C3\\n\"\n \"adc %D1,%D3\\n\"\n\n \"eor %A0,r23\\n\" // t ^= i\n\n // Z = Z - li_in + li_out\n \"ldi r25,8\\n\" // li_in = li_in + 1\n \"add r24,r25\\n\"\n \"sub %A8,r24\\n\" // return Z to its initial value\n \"sbc %B8,__zero_reg__\\n\"\n \"andi r24,0x1f\\n\" // li_in = li_in % 4\n \"std %6,r24\\n\"\n \"ldd r24,%7\\n\" // Z = &(l[li_out])\n \"add %A8,r24\\n\"\n \"adc %B8,__zero_reg__\\n\"\n\n \"st Z+,%A0\\n\" // l[li_out] = t\n \"st Z+,%B0\\n\"\n \"st Z+,%C0\\n\"\n \"st Z+,%D0\\n\"\n \"st Z+,%A1\\n\"\n \"st Z+,%B1\\n\"\n \"st Z+,%C1\\n\"\n \"st Z+,%D1\\n\"\n\n \"add r24,r25\\n\" // li_out = li_out + 1\n \"sub %A8,r24\\n\" // return Z to its initial value\n \"sbc %B8,__zero_reg__\\n\"\n \"andi r24,0x1f\\n\" // li_out = li_out % 4\n \"std %7,r24\\n\"\n\n // s = leftRotate3_64(s) ^ l[li_out];\n \"lsl %A2\\n\" // s = leftRotate1_64(s)\n \"rol %B2\\n\"\n \"rol %C2\\n\"\n \"rol %D2\\n\"\n \"rol %A3\\n\"\n \"rol %B3\\n\"\n \"rol %C3\\n\"\n \"rol %D3\\n\"\n \"adc %A2,__zero_reg__\\n\"\n\n \"lsl %A2\\n\" // s = leftRotate1_64(s)\n \"rol %B2\\n\"\n \"rol %C2\\n\"\n \"rol %D2\\n\"\n \"rol %A3\\n\"\n \"rol %B3\\n\"\n \"rol %C3\\n\"\n \"rol %D3\\n\"\n \"adc %A2,__zero_reg__\\n\"\n\n \"lsl %A2\\n\" // s = leftRotate1_64(s)\n \"rol %B2\\n\"\n \"rol %C2\\n\"\n \"rol %D2\\n\"\n \"rol %A3\\n\"\n \"rol %B3\\n\"\n \"rol %C3\\n\"\n \"rol %D3\\n\"\n \"adc %A2,__zero_reg__\\n\"\n\n \"eor %A2,%A0\\n\" // s ^= l[li_out]\n \"eor %B2,%B0\\n\"\n \"eor %C2,%C0\\n\"\n \"eor %D2,%D0\\n\"\n \"eor %A3,%A1\\n\"\n \"eor %B3,%B1\\n\"\n \"eor %C3,%C1\\n\"\n \"eor %D3,%D1\\n\"\n\n \"std %A4,%A2\\n\" // store s\n \"std %B4,%B2\\n\"\n \"std %C4,%C2\\n\"\n \"std %D4,%D2\\n\"\n \"std %A5,%A3\\n\"\n \"std %B5,%B3\\n\"\n \"std %C5,%C3\\n\"\n \"std %D5,%D3\\n\"\n\n // Pop registers from the stack to recover the x and y values.\n \"pop %D3\\n\"\n \"pop %C3\\n\"\n \"pop %B3\\n\"\n \"pop %A3\\n\"\n \"pop %D2\\n\"\n \"pop %C2\\n\"\n \"pop %B2\\n\"\n \"pop %A2\\n\"\n \"pop %D1\\n\"\n \"pop %C1\\n\"\n \"pop %B1\\n\"\n \"pop %A1\\n\"\n \"pop %D0\\n\"\n \"pop %C0\\n\"\n \"pop %B0\\n\"\n \"pop %A0\\n\"\n\n // Bottom of the loop.\n \"inc r23\\n\"\n \"rjmp 1b\\n\"\n \"3:\\n\"\n\n : \"+r\"(xlow), \"+r\"(xhigh), \"+r\"(ylow), \"+r\"(yhigh),\n \"+Q\"(slow), \"+Q\"(shigh), \"+Q\"(li_in), \"+Q\"(li_out)\n : \"z\"(l), \"r\"(rounds)\n : \"r23\", \"r24\", \"r25\"\n );\n\n // Pack the results into the output and convert back to big-endian.\n __asm__ __volatile__ (\n \"st Z,%D1\\n\"\n \"std Z+1,%C1\\n\"\n \"std Z+2,%B1\\n\"\n \"std Z+3,%A1\\n\"\n \"std Z+4,%D0\\n\"\n \"std Z+5,%C0\\n\"\n \"std Z+6,%B0\\n\"\n \"std Z+7,%A0\\n\"\n \"std Z+8,%D3\\n\"\n \"std Z+9,%C3\\n\"\n \"std Z+10,%B3\\n\"\n \"std Z+11,%A3\\n\"\n \"std Z+12,%D2\\n\"\n \"std Z+13,%C2\\n\"\n \"std Z+14,%B2\\n\"\n \"std Z+15,%A2\\n\"\n : : \"r\"(xlow), \"r\"(xhigh), \"r\"(ylow), \"r\"(yhigh), \"z\"(output)\n );\n#else\n uint64_t l[4];\n uint64_t x, y, s;\n uint8_t round;\n uint8_t li_in = 0;\n uint8_t li_out = rounds - 31;\n uint8_t i = 0;\n\n // Copy the input block into the work registers.\n unpack64(x, input);\n unpack64(y, input + 8);\n\n // Prepare the key schedule.\n memcpy(l, k + 1, li_out * sizeof(uint64_t));\n s = k[0];\n\n // Perform all encryption rounds except the last.\n for (round = rounds - 1; round > 0; --round, ++i) {\n // Perform the round with the current key schedule word.\n x = (rightRotate8_64(x) + y) ^ s;\n y = leftRotate3_64(y) ^ x;\n\n // Calculate the next key schedule word.\n l[li_out] = (s + rightRotate8_64(l[li_in])) ^ i;\n s = leftRotate3_64(s) ^ l[li_out];\n li_in = (li_in + 1) & 0x03;\n li_out = (li_out + 1) & 0x03;\n }\n\n // Perform the final round and copy to the output.\n x = (rightRotate8_64(x) + y) ^ s;\n y = leftRotate3_64(y) ^ x;\n pack64(output, x);\n pack64(output + 8, y);\n#endif\n}\n\n/**\n * \\brief Decrypts a single block using this cipher.\n *\n * \\param output The output buffer to put the plaintext into.\n * Must be at least blockSize() bytes in length.\n * \\param input The input buffer to read the ciphertext from which is\n * allowed to overlap with \\a output. Must be at least blockSize()\n * bytes in length.\n *\n * \\note This function is not supported for SpeckLowMemory, which means\n * that CBC mode cannot be used but that the CTR, CFB, OFB, and GCM modes\n * can be used.\n */\nvoid SpeckLowMemory::decryptBlock(uint8_t *output, const uint8_t *input)\n{\n // Decryption is not supported.\n}\n\nvoid SpeckLowMemory::clear()\n{\n clean(k);\n}\n" }, { "alpha_fraction": 0.5855284333229065, "alphanum_fraction": 0.6154471635818481, "avg_line_length": 29.147058486938477, "blob_id": "bc7e9f6291222def7560a6b07335119ee2593ec9", "content_id": "f8fd6797484375e560f2abcf08b6b93274df1ced", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6150, "license_type": "permissive", "max_line_length": 111, "num_lines": 204, "path": "/Crypto/GHASH.cpp", "repo_name": "dchen496/remote-power-button", "src_encoding": "UTF-8", "text": "/*\n * Copyright (C) 2015 Southern Storm Software, Pty Ltd.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n#include \"GHASH.h\"\n#include \"Crypto.h\"\n#include \"utility/EndianUtil.h\"\n#include <string.h>\n\n/**\n * \\class GHASH GHASH.h <GHASH.h>\n * \\brief Implementation of the GHASH message authenticator.\n *\n * GHASH is the message authentication part of Galois Counter Mode (GCM).\n *\n * \\note GHASH is not the same as GMAC. GHASH implements the low level\n * hashing primitive that is used by both GCM and GMAC. GMAC can be\n * simulated using GCM and an empty plaintext/ciphertext.\n *\n * References: <a href=\"http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf\">NIST SP 800-38D</a>,\n * http://en.wikipedia.org/wiki/Galois/Counter_Mode\n *\n * \\sa GCM\n */\n\n/**\n * \\brief Constructs a new GHASH message authenticator.\n */\nGHASH::GHASH()\n{\n state.posn = 0;\n}\n\n/**\n * \\brief Destroys this GHASH message authenticator.\n */\nGHASH::~GHASH()\n{\n clean(state);\n}\n\n/**\n * \\brief Resets the GHASH message authenticator for a new session.\n *\n * \\param key Points to the 16 byte authentication key.\n *\n * \\sa update(), finalize()\n */\nvoid GHASH::reset(const void *key)\n{\n // Copy the key into H and convert from big endian to host order.\n memcpy(state.H, key, 16);\n#if defined(CRYPTO_LITTLE_ENDIAN)\n state.H[0] = be32toh(state.H[0]);\n state.H[1] = be32toh(state.H[1]);\n state.H[2] = be32toh(state.H[2]);\n state.H[3] = be32toh(state.H[3]);\n#endif\n\n // Reset the hash.\n memset(state.Y, 0, sizeof(state.Y));\n state.posn = 0;\n}\n\n/**\n * \\brief Updates the message authenticator with more data.\n *\n * \\param data Data to be hashed.\n * \\param len Number of bytes of data to be hashed.\n *\n * If finalize() has already been called, then the behavior of update() will\n * be undefined. Call reset() first to start a new authentication process.\n *\n * \\sa pad(), reset(), finalize()\n */\nvoid GHASH::update(const void *data, size_t len)\n{\n // XOR the input with state.Y in 128-bit chunks and process them.\n const uint8_t *d = (const uint8_t *)data;\n while (len > 0) {\n uint8_t size = 16 - state.posn;\n if (size > len)\n size = len;\n uint8_t *y = ((uint8_t *)state.Y) + state.posn;\n for (uint8_t i = 0; i < size; ++i)\n y[i] ^= d[i];\n state.posn += size;\n len -= size;\n d += size;\n if (state.posn == 16) {\n processChunk();\n state.posn = 0;\n }\n }\n}\n\n/**\n * \\brief Finalizes the authentication process and returns the token.\n *\n * \\param token The buffer to return the token value in.\n * \\param len The length of the \\a token buffer between 0 and 16.\n *\n * If \\a len is less than 16, then the token value will be truncated to\n * the first \\a len bytes. If \\a len is greater than 16, then the remaining\n * bytes will left unchanged.\n *\n * If finalize() is called again, then the returned \\a token value is\n * undefined. Call reset() first to start a new authentication process.\n *\n * \\sa reset(), update()\n */\nvoid GHASH::finalize(void *token, size_t len)\n{\n // Pad with zeroes to a multiple of 16 bytes.\n pad();\n\n // The token is the current value of Y.\n if (len > 16)\n len = 16;\n memcpy(token, state.Y, len);\n}\n\n/**\n * \\brief Pads the input stream with zero bytes to a multiple of 16.\n *\n * \\sa update()\n */\nvoid GHASH::pad()\n{\n if (state.posn != 0) {\n // Padding involves XOR'ing the rest of state.Y with zeroes,\n // which does nothing. Immediately process the next chunk.\n processChunk();\n state.posn = 0;\n }\n}\n\n/**\n * \\brief Clears the authenticator's state, removing all sensitive data.\n */\nvoid GHASH::clear()\n{\n clean(state);\n}\n\nvoid GHASH::processChunk()\n{\n uint32_t Z0 = 0; // Z = 0\n uint32_t Z1 = 0;\n uint32_t Z2 = 0;\n uint32_t Z3 = 0;\n uint32_t V0 = state.H[0]; // V = H\n uint32_t V1 = state.H[1];\n uint32_t V2 = state.H[2];\n uint32_t V3 = state.H[3];\n\n // Multiply Z by V for the set bits in Y, starting at the top.\n // This is a very simple bit by bit version that may not be very\n // fast but it should be resistant to cache timing attacks.\n for (uint8_t posn = 0; posn < 16; ++posn) {\n uint8_t value = ((const uint8_t *)state.Y)[posn];\n for (uint8_t bit = 0; bit < 8; ++bit, value <<= 1) {\n // Extract the high bit of \"value\" and turn it into a mask.\n uint32_t mask = (~((uint32_t)(value >> 7))) + 1;\n\n // XOR V with Z if the bit is 1.\n Z0 ^= (V0 & mask);\n Z1 ^= (V1 & mask);\n Z2 ^= (V2 & mask);\n Z3 ^= (V3 & mask);\n\n // Rotate V right by 1 bit.\n mask = ((~(V3 & 0x01)) + 1) & 0xE1000000;\n V3 = (V3 >> 1) | (V2 << 31);\n V2 = (V2 >> 1) | (V1 << 31);\n V1 = (V1 >> 1) | (V0 << 31);\n V0 = (V0 >> 1) ^ mask;\n }\n }\n\n // We have finished the block so copy Z into Y and byte-swap.\n state.Y[0] = htobe32(Z0);\n state.Y[1] = htobe32(Z1);\n state.Y[2] = htobe32(Z2);\n state.Y[3] = htobe32(Z3);\n}\n" }, { "alpha_fraction": 0.3938499689102173, "alphanum_fraction": 0.4470282793045044, "avg_line_length": 26.594463348388672, "blob_id": "c4677b1f2f1cabd40449041b163d138e89958c7b", "content_id": "5834f70d015dca54894cb01d06aab1e5353cb307", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 16943, "license_type": "permissive", "max_line_length": 78, "num_lines": 614, "path": "/Crypto/Speck.cpp", "repo_name": "dchen496/remote-power-button", "src_encoding": "UTF-8", "text": "/*\n * Copyright (C) 2015 Southern Storm Software, Pty Ltd.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n#include \"Speck.h\"\n#include \"Crypto.h\"\n#include \"utility/RotateUtil.h\"\n#include \"utility/EndianUtil.h\"\n#include <string.h>\n\n/**\n * \\class Speck Speck.h <Speck.h>\n * \\brief Speck block cipher with a 128-bit block size.\n *\n * Speck is a family of lightweight block ciphers designed by the\n * National Security Agency (NSA). The ciphers are highly optimized\n * for software implementation on microcontrollers.\n *\n * This class implements the Speck family that uses 128-bit block sizes\n * with 128-bit, 192-bit, or 256-bit key sizes. Other Speck families support\n * smaller block sizes of 32, 48, 64, or 96 bits but such block sizes are\n * too small for use in modern cryptosystems.\n *\n * \\note Current crytoanalysis (up until 2015) has not revealed any obvious\n * weaknesses in the full-round version of Speck. But if you are wary of\n * ciphers designed by the NSA, then use ChaCha or AES instead.\n *\n * The SpeckLowMemory class provides an alternative implementation that\n * has reduced RAM and flash size requirements at the cost of some encryption\n * performance.\n *\n * References: https://en.wikipedia.org/wiki/Speck_%28cipher%29,\n * http://eprint.iacr.org/2013/404\n *\n * \\sa SpeckLowMemory\n */\n\n// The \"avr-gcc\" compiler doesn't do a very good job of compiling\n// code involving 64-bit values. So we have to use inline assembly.\n// It also helps to break the state up into 32-bit quantities\n// because \"asm\" supports register names like %A0, %B0, %C0, %D0\n// for the bytes in a 32-bit quantity, but it does not support\n// %E0, %F0, %G0, %H0 for the high bytes of a 64-bit quantity.\n#if defined(__AVR__)\n#define USE_AVR_INLINE_ASM 1\n#endif\n\n/**\n * \\brief Constructs a Speck block cipher with no initial key.\n *\n * This constructor must be followed by a call to setKey() before the\n * block cipher can be used for encryption or decryption.\n */\nSpeck::Speck()\n : rounds(32)\n{\n}\n\nSpeck::~Speck()\n{\n clean(k);\n}\n\nsize_t Speck::blockSize() const\n{\n return 16;\n}\n\nsize_t Speck::keySize() const\n{\n // Also supports 128-bit and 192-bit, but we only report 256-bit.\n return 32;\n}\n\n// Pack/unpack byte-aligned big-endian 64-bit quantities.\n#define pack64(data, value) \\\n do { \\\n uint64_t v = htobe64((value)); \\\n memcpy((data), &v, sizeof(uint64_t)); \\\n } while (0)\n#define unpack64(value, data) \\\n do { \\\n memcpy(&(value), (data), sizeof(uint64_t)); \\\n (value) = be64toh((value)); \\\n } while (0)\n\nbool Speck::setKey(const uint8_t *key, size_t len)\n{\n#if USE_AVR_INLINE_ASM\n uint64_t l[4];\n uint8_t m, mb;\n if (len == 32) {\n m = 4;\n mb = 3 * 8;\n } else if (len == 24) {\n m = 3;\n mb = 2 * 8;\n } else if (len == 16) {\n m = 2;\n mb = 8;\n } else {\n return false;\n }\n rounds = 30 + m;\n\n // Copy the first (m - 1) * 8 bytes of the key into the \"l\" array\n // in reverse order to convert big endian into little-endian.\n __asm__ __volatile__ (\n \"1:\\n\"\n \"ld __tmp_reg__,-Z\\n\"\n \"st X+,__tmp_reg__\\n\"\n \"dec %2\\n\"\n \"brne 1b\\n\"\n : : \"x\"(l), \"z\"(key + len - 8), \"r\"(mb)\n );\n\n // Copy the final 8 bytes of the key into k[0] in reverse order.\n __asm__ __volatile__ (\n \"1:\\n\"\n \"ld __tmp_reg__,-Z\\n\"\n \"st X+,__tmp_reg__\\n\"\n \"dec %2\\n\"\n \"brne 1b\\n\"\n : : \"x\"(k), \"z\"(key + len), \"r\"(8)\n );\n\n // Expand the key to the full key schedule.\n __asm__ __volatile__ (\n \"1:\\n\"\n // l[li_out] = (k[i] + rightRotate8_64(l[li_in])) ^ i;\n \"add %A1,%2\\n\" // X = &(l[li_in])\n \"adc %B1,__zero_reg__\\n\"\n \"ld r15,X+\\n\" // x = rightRotate8_64(l[li_in])\n \"ld r8,X+\\n\"\n \"ld r9,X+\\n\"\n \"ld r10,X+\\n\"\n \"ld r11,X+\\n\"\n \"ld r12,X+\\n\"\n \"ld r13,X+\\n\"\n \"ld r14,X+\\n\"\n\n \"ld r16,Z+\\n\" // y = k[i]\n \"ld r17,Z+\\n\" \n \"ld r18,Z+\\n\" \n \"ld r19,Z+\\n\" \n \"ld r20,Z+\\n\" \n \"ld r21,Z+\\n\" \n \"ld r22,Z+\\n\" \n \"ld r23,Z+\\n\" \n\n \"add r8,r16\\n\" // x += y\n \"adc r9,r17\\n\"\n \"adc r10,r18\\n\"\n \"adc r11,r19\\n\"\n \"adc r12,r20\\n\"\n \"adc r13,r21\\n\"\n \"adc r14,r22\\n\"\n \"adc r15,r23\\n\"\n\n \"eor r8,%4\\n\" // x ^= i\n\n // X = X - li_in + li_out\n \"ldi r24,8\\n\" // li_in = li_in + 1\n \"add %2,r24\\n\"\n \"sub %A1,%2\\n\" // return X to its initial value\n \"sbc %B1,__zero_reg__\\n\"\n \"ldi r25,0x1f\\n\"\n \"and %2,r25\\n\" // li_in = li_in % 4\n \"add %A1,%3\\n\" // X = &(l[li_out])\n \"adc %B1,__zero_reg__\\n\"\n\n \"st X+,r8\\n\" // l[li_out] = x\n \"st X+,r9\\n\"\n \"st X+,r10\\n\"\n \"st X+,r11\\n\"\n \"st X+,r12\\n\"\n \"st X+,r13\\n\"\n \"st X+,r14\\n\"\n \"st X+,r15\\n\"\n\n \"add %3,r24\\n\" // li_out = li_out + 1\n \"sub %A1,%3\\n\" // return X to its initial value\n \"sbc %B1,__zero_reg__\\n\"\n \"and %3,r25\\n\" // li_out = li_out % 4\n\n // k[i + 1] = leftRotate3_64(k[i]) ^ l[li_out];\n \"lsl r16\\n\" // y = leftRotate1_64(y)\n \"rol r17\\n\"\n \"rol r18\\n\"\n \"rol r19\\n\"\n \"rol r20\\n\"\n \"rol r21\\n\"\n \"rol r22\\n\"\n \"rol r23\\n\"\n \"adc r16,__zero_reg__\\n\"\n\n \"lsl r16\\n\" // y = leftRotate1_64(y)\n \"rol r17\\n\"\n \"rol r18\\n\"\n \"rol r19\\n\"\n \"rol r20\\n\"\n \"rol r21\\n\"\n \"rol r22\\n\"\n \"rol r23\\n\"\n \"adc r16,__zero_reg__\\n\"\n\n \"lsl r16\\n\" // y = leftRotate1_64(y)\n \"rol r17\\n\"\n \"rol r18\\n\"\n \"rol r19\\n\"\n \"rol r20\\n\"\n \"rol r21\\n\"\n \"rol r22\\n\"\n \"rol r23\\n\"\n \"adc r16,__zero_reg__\\n\"\n\n \"eor r16,r8\\n\" // y ^= x\n \"eor r17,r9\\n\"\n \"eor r18,r10\\n\"\n \"eor r19,r11\\n\"\n \"eor r20,r12\\n\"\n \"eor r21,r13\\n\"\n \"eor r22,r14\\n\"\n \"eor r23,r15\\n\"\n\n \"st Z,r16\\n\" // k[i + 1] = y\n \"std Z+1,r17\\n\"\n \"std Z+2,r18\\n\"\n \"std Z+3,r19\\n\"\n \"std Z+4,r20\\n\"\n \"std Z+5,r21\\n\"\n \"std Z+6,r22\\n\"\n \"std Z+7,r23\\n\"\n\n // Loop\n \"inc %4\\n\" // ++i\n \"dec %5\\n\" // --rounds\n \"breq 2f\\n\"\n \"rjmp 1b\\n\"\n \"2:\\n\"\n\n : : \"z\"(k), \"x\"(l),\n \"r\"((uint8_t)0), // initial value of li_in\n \"r\"((uint8_t)((m - 1) * 8)), // initial value of li_out\n \"r\"(0), // initial value of i\n \"r\"(rounds - 1)\n : \"r8\", \"r9\", \"r10\", \"r11\", \"r12\", \"r13\", \"r14\", \"r15\",\n \"r16\", \"r17\", \"r18\", \"r19\", \"r20\", \"r21\", \"r22\", \"r23\",\n \"r24\", \"r25\"\n );\n#else\n uint64_t l[4];\n uint8_t m;\n if (len == 32) {\n m = 4;\n unpack64(l[2], key);\n unpack64(l[1], key + 8);\n unpack64(l[0], key + 16);\n unpack64(k[0], key + 24);\n } else if (len == 24) {\n m = 3;\n unpack64(l[1], key);\n unpack64(l[0], key + 8);\n unpack64(k[0], key + 16);\n } else if (len == 16) {\n m = 2;\n unpack64(l[0], key);\n unpack64(k[0], key + 8);\n } else {\n return false;\n }\n rounds = 30 + m;\n uint8_t li_in = 0;\n uint8_t li_out = m - 1;\n for (uint8_t i = 0; i < (rounds - 1); ++i) {\n l[li_out] = (k[i] + rightRotate8_64(l[li_in])) ^ i;\n k[i + 1] = leftRotate3_64(k[i]) ^ l[li_out];\n if ((++li_in) >= m)\n li_in = 0;\n if ((++li_out) >= m)\n li_out = 0;\n }\n#endif\n clean(l);\n return true;\n}\n\nvoid Speck::encryptBlock(uint8_t *output, const uint8_t *input)\n{\n#if USE_AVR_INLINE_ASM\n uint32_t xlow, xhigh, ylow, yhigh;\n\n // Unpack the input into the x and y variables, converting\n // from big-endian into little-endian in the process.\n __asm__ __volatile__ (\n \"ld %D1,Z\\n\"\n \"ldd %C1,Z+1\\n\"\n \"ldd %B1,Z+2\\n\"\n \"ldd %A1,Z+3\\n\"\n \"ldd %D0,Z+4\\n\"\n \"ldd %C0,Z+5\\n\"\n \"ldd %B0,Z+6\\n\"\n \"ldd %A0,Z+7\\n\"\n \"ldd %D3,Z+8\\n\"\n \"ldd %C3,Z+9\\n\"\n \"ldd %B3,Z+10\\n\"\n \"ldd %A3,Z+11\\n\"\n \"ldd %D2,Z+12\\n\"\n \"ldd %C2,Z+13\\n\"\n \"ldd %B2,Z+14\\n\"\n \"ldd %A2,Z+15\\n\"\n : \"=r\"(xlow), \"=r\"(xhigh), \"=r\"(ylow), \"=r\"(yhigh)\n : \"z\"(input)\n );\n\n // Perform all encryption rounds. Z points to the key schedule.\n __asm__ __volatile__ (\n \"1:\\n\"\n // x = (rightRotate8_64(x) + y) ^ *s++;\n \"mov __tmp_reg__,%A0\\n\" // x = rightRotate8_64(x)\n \"mov %A0,%B0\\n\"\n \"mov %B0,%C0\\n\"\n \"mov %C0,%D0\\n\"\n \"mov %D0,%A1\\n\"\n \"mov %A1,%B1\\n\"\n \"mov %B1,%C1\\n\"\n \"mov %C1,%D1\\n\"\n \"mov %D1,__tmp_reg__\\n\"\n\n \"add %A0,%A2\\n\" // x += y\n \"adc %B0,%B2\\n\"\n \"adc %C0,%C2\\n\"\n \"adc %D0,%D2\\n\"\n \"adc %A1,%A3\\n\"\n \"adc %B1,%B3\\n\"\n \"adc %C1,%C3\\n\"\n \"adc %D1,%D3\\n\"\n\n \"ld __tmp_reg__,Z+\\n\" // x ^= *s++\n \"eor %A0,__tmp_reg__\\n\"\n \"ld __tmp_reg__,Z+\\n\"\n \"eor %B0,__tmp_reg__\\n\"\n \"ld __tmp_reg__,Z+\\n\"\n \"eor %C0,__tmp_reg__\\n\"\n \"ld __tmp_reg__,Z+\\n\"\n \"eor %D0,__tmp_reg__\\n\"\n \"ld __tmp_reg__,Z+\\n\"\n \"eor %A1,__tmp_reg__\\n\"\n \"ld __tmp_reg__,Z+\\n\"\n \"eor %B1,__tmp_reg__\\n\"\n \"ld __tmp_reg__,Z+\\n\"\n \"eor %C1,__tmp_reg__\\n\"\n \"ld __tmp_reg__,Z+\\n\"\n \"eor %D1,__tmp_reg__\\n\"\n\n // y = leftRotate3_64(y) ^ x;\n \"lsl %A2\\n\" // y = leftRotate1_64(y)\n \"rol %B2\\n\"\n \"rol %C2\\n\"\n \"rol %D2\\n\"\n \"rol %A3\\n\"\n \"rol %B3\\n\"\n \"rol %C3\\n\"\n \"rol %D3\\n\"\n \"adc %A2,__zero_reg__\\n\"\n\n \"lsl %A2\\n\" // y = leftRotate1_64(y)\n \"rol %B2\\n\"\n \"rol %C2\\n\"\n \"rol %D2\\n\"\n \"rol %A3\\n\"\n \"rol %B3\\n\"\n \"rol %C3\\n\"\n \"rol %D3\\n\"\n\n \"adc %A2,__zero_reg__\\n\"\n \"lsl %A2\\n\" // y = leftRotate1_64(y)\n \"rol %B2\\n\"\n \"rol %C2\\n\"\n \"rol %D2\\n\"\n \"rol %A3\\n\"\n \"rol %B3\\n\"\n \"rol %C3\\n\"\n \"rol %D3\\n\"\n \"adc %A2,__zero_reg__\\n\"\n\n \"eor %A2,%A0\\n\" // y ^= x\n \"eor %B2,%B0\\n\"\n \"eor %C2,%C0\\n\"\n \"eor %D2,%D0\\n\"\n \"eor %A3,%A1\\n\"\n \"eor %B3,%B1\\n\"\n \"eor %C3,%C1\\n\"\n \"eor %D3,%D1\\n\"\n\n // Loop\n \"dec %5\\n\" // --round\n \"breq 2f\\n\"\n \"rjmp 1b\\n\"\n \"2:\\n\"\n : \"+r\"(xlow), \"+r\"(xhigh), \"+r\"(ylow), \"+r\"(yhigh)\n : \"z\"(k), \"r\"(rounds)\n );\n\n // Pack the results into the output and convert back to big-endian.\n __asm__ __volatile__ (\n \"st Z,%D1\\n\"\n \"std Z+1,%C1\\n\"\n \"std Z+2,%B1\\n\"\n \"std Z+3,%A1\\n\"\n \"std Z+4,%D0\\n\"\n \"std Z+5,%C0\\n\"\n \"std Z+6,%B0\\n\"\n \"std Z+7,%A0\\n\"\n \"std Z+8,%D3\\n\"\n \"std Z+9,%C3\\n\"\n \"std Z+10,%B3\\n\"\n \"std Z+11,%A3\\n\"\n \"std Z+12,%D2\\n\"\n \"std Z+13,%C2\\n\"\n \"std Z+14,%B2\\n\"\n \"std Z+15,%A2\\n\"\n : : \"r\"(xlow), \"r\"(xhigh), \"r\"(ylow), \"r\"(yhigh), \"z\"(output)\n );\n#else\n uint64_t x, y;\n const uint64_t *s = k;\n unpack64(x, input);\n unpack64(y, input + 8);\n for (uint8_t round = rounds; round > 0; --round, ++s) {\n x = (rightRotate8_64(x) + y) ^ s[0];\n y = leftRotate3_64(y) ^ x;\n }\n pack64(output, x);\n pack64(output + 8, y);\n#endif\n}\n\nvoid Speck::decryptBlock(uint8_t *output, const uint8_t *input)\n{\n#if USE_AVR_INLINE_ASM\n uint32_t xlow, xhigh, ylow, yhigh;\n\n // Unpack the input into the x and y variables, converting\n // from big-endian into little-endian in the process.\n __asm__ __volatile__ (\n \"ld %D1,Z\\n\"\n \"ldd %C1,Z+1\\n\"\n \"ldd %B1,Z+2\\n\"\n \"ldd %A1,Z+3\\n\"\n \"ldd %D0,Z+4\\n\"\n \"ldd %C0,Z+5\\n\"\n \"ldd %B0,Z+6\\n\"\n \"ldd %A0,Z+7\\n\"\n \"ldd %D3,Z+8\\n\"\n \"ldd %C3,Z+9\\n\"\n \"ldd %B3,Z+10\\n\"\n \"ldd %A3,Z+11\\n\"\n \"ldd %D2,Z+12\\n\"\n \"ldd %C2,Z+13\\n\"\n \"ldd %B2,Z+14\\n\"\n \"ldd %A2,Z+15\\n\"\n : \"=r\"(xlow), \"=r\"(xhigh), \"=r\"(ylow), \"=r\"(yhigh)\n : \"z\"(input)\n );\n\n // Perform all decryption rounds. Z points to the end of key schedule.\n __asm__ __volatile__ (\n \"1:\\n\"\n // y = rightRotate3_64(x ^ y);\n \"eor %A2,%A0\\n\" // y ^= x\n \"eor %B2,%B0\\n\"\n \"eor %C2,%C0\\n\"\n \"eor %D2,%D0\\n\"\n \"eor %A3,%A1\\n\"\n \"eor %B3,%B1\\n\"\n \"eor %C3,%C1\\n\"\n \"eor %D3,%D1\\n\"\n\n \"bst %A2,0\\n\" // y = rightRotate1_64(y)\n \"ror %D3\\n\"\n \"ror %C3\\n\"\n \"ror %B3\\n\"\n \"ror %A3\\n\"\n \"ror %D2\\n\"\n \"ror %C2\\n\"\n \"ror %B2\\n\"\n \"ror %A2\\n\"\n \"bld %D3,7\\n\"\n\n \"bst %A2,0\\n\" // y = rightRotate1_64(y)\n \"ror %D3\\n\"\n \"ror %C3\\n\"\n \"ror %B3\\n\"\n \"ror %A3\\n\"\n \"ror %D2\\n\"\n \"ror %C2\\n\"\n \"ror %B2\\n\"\n \"ror %A2\\n\"\n \"bld %D3,7\\n\"\n\n \"bst %A2,0\\n\" // y = rightRotate1_64(y)\n \"ror %D3\\n\"\n \"ror %C3\\n\"\n \"ror %B3\\n\"\n \"ror %A3\\n\"\n \"ror %D2\\n\"\n \"ror %C2\\n\"\n \"ror %B2\\n\"\n \"ror %A2\\n\"\n \"bld %D3,7\\n\"\n\n // x = leftRotate8_64((x ^ *s--) - y);\n \"ld __tmp_reg__,-Z\\n\" // x ^= *s--\n \"eor %D1,__tmp_reg__\\n\"\n \"ld __tmp_reg__,-Z\\n\"\n \"eor %C1,__tmp_reg__\\n\"\n \"ld __tmp_reg__,-Z\\n\"\n \"eor %B1,__tmp_reg__\\n\"\n \"ld __tmp_reg__,-Z\\n\"\n \"eor %A1,__tmp_reg__\\n\"\n \"ld __tmp_reg__,-Z\\n\"\n \"eor %D0,__tmp_reg__\\n\"\n \"ld __tmp_reg__,-Z\\n\"\n \"eor %C0,__tmp_reg__\\n\"\n \"ld __tmp_reg__,-Z\\n\"\n \"eor %B0,__tmp_reg__\\n\"\n \"ld __tmp_reg__,-Z\\n\"\n \"eor %A0,__tmp_reg__\\n\"\n\n \"sub %A0,%A2\\n\" // x -= y\n \"sbc %B0,%B2\\n\"\n \"sbc %C0,%C2\\n\"\n \"sbc %D0,%D2\\n\"\n \"sbc %A1,%A3\\n\"\n \"sbc %B1,%B3\\n\"\n \"sbc %C1,%C3\\n\"\n \"sbc %D1,%D3\\n\"\n\n \"mov __tmp_reg__,%D1\\n\" // x = lefRotate8_64(x)\n \"mov %D1,%C1\\n\"\n \"mov %C1,%B1\\n\"\n \"mov %B1,%A1\\n\"\n \"mov %A1,%D0\\n\"\n \"mov %D0,%C0\\n\"\n \"mov %C0,%B0\\n\"\n \"mov %B0,%A0\\n\"\n \"mov %A0,__tmp_reg__\\n\"\n\n // Loop\n \"dec %5\\n\" // --round\n \"breq 2f\\n\"\n \"rjmp 1b\\n\"\n \"2:\\n\"\n : \"+r\"(xlow), \"+r\"(xhigh), \"+r\"(ylow), \"+r\"(yhigh)\n : \"z\"(k + rounds), \"r\"(rounds)\n );\n\n // Pack the results into the output and convert back to big-endian.\n __asm__ __volatile__ (\n \"st Z,%D1\\n\"\n \"std Z+1,%C1\\n\"\n \"std Z+2,%B1\\n\"\n \"std Z+3,%A1\\n\"\n \"std Z+4,%D0\\n\"\n \"std Z+5,%C0\\n\"\n \"std Z+6,%B0\\n\"\n \"std Z+7,%A0\\n\"\n \"std Z+8,%D3\\n\"\n \"std Z+9,%C3\\n\"\n \"std Z+10,%B3\\n\"\n \"std Z+11,%A3\\n\"\n \"std Z+12,%D2\\n\"\n \"std Z+13,%C2\\n\"\n \"std Z+14,%B2\\n\"\n \"std Z+15,%A2\\n\"\n : : \"r\"(xlow), \"r\"(xhigh), \"r\"(ylow), \"r\"(yhigh), \"z\"(output)\n );\n#else\n uint64_t x, y;\n const uint64_t *s = k + rounds - 1;\n unpack64(x, input);\n unpack64(y, input + 8);\n for (uint8_t round = rounds; round > 0; --round, --s) {\n y = rightRotate3_64(x ^ y);\n x = leftRotate8_64((x ^ s[0]) - y);\n }\n pack64(output, x);\n pack64(output + 8, y);\n#endif\n}\n\nvoid Speck::clear()\n{\n clean(k);\n}\n" } ]
5
jiaeyan/Data-Analysis-Library-Tutorial
https://github.com/jiaeyan/Data-Analysis-Library-Tutorial
e90da7b6fc5e047a599be3b89c48ffb975841870
138d45f7067f5da8c78b5f324eb87c2dc2425e88
7c75bd1c18cfd002b579fa14638934f33f8cd068
refs/heads/master
2021-05-12T04:28:50.044710
2018-01-15T16:25:20
2018-01-15T16:25:20
117,164,739
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.620525062084198, "alphanum_fraction": 0.648127019405365, "avg_line_length": 42.39639663696289, "blob_id": "a5d0d1bac07b77ae50fe57a5195c0e407594c20d", "content_id": "d9576a9588072ac81211321710049a2e099140f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9639, "license_type": "no_license", "max_line_length": 205, "num_lines": 222, "path": "/pandas_guide.py", "repo_name": "jiaeyan/Data-Analysis-Library-Tutorial", "src_encoding": "UTF-8", "text": "import pandas as pd, numpy as np\nfrom pandas import Series, DataFrame\n\n'''-----------------------------01. Series----------------------------'''\n'''A dict (with a name), with values corresponding to labels/indexes.'''\n\n'''[Construction]'''\nobj = pd.Series([4, 7, -5, 3]) # or use keyword args to indicate 'name', 'index' and 'values'\nprint(obj)\nprint(obj.values)\nprint(obj.index) # default range index, seen as labels of dict, index object in pandas is immutable\nobj.name = 'ID' # assign \"name\" to series and its index\nobj.index.name = 'names'\nobj.index = ['Bob', 'Steve', 'Jeff', 'Ryan'] # alter indices/labels in place, but not work for values\n\nsdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000} # map from index/label to value\nobj3 = pd.Series(sdata) # pass a dict to series, key->index, forced to be sorted\nstates = ['California', 'Ohio', 'Oregon', 'Texas']\nobj4 = pd.Series(sdata, index=states) #DIY the order of keys\nprint()\n\n'''[Modification]'''\nobj2 = pd.Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])\nprint(obj2['a']) # check value by label\nprint()\nobj2['d'] = 6 # change value by label, in place\nprint(obj2[['c', 'a', 'd']])\nprint()\n\n'''[Operation]'''\nprint(obj2[obj2 > 0])\nprint()\nprint(obj2 * 2) # this operation returns a new list, not in place\nprint()\nprint('b' in obj2) # only check if LABEL is in, not value\nprint(obj3 + obj4) # automatically aligns by index label in arithmetic operations\nprint()\n\n'''[Reindex]'''\n'''Pass a list of index, return a new object.'''\nobj = pd.Series([4.5, 7.2, -5.3, 3.6], index=['d', 'b', 'a', 'c'])\nobj2 = obj.reindex(['a', 'b', 'c', 'd', 'e'], fill_value=0) # values will be fixed with existed index\nobj3 = pd.Series(['blue', 'purple', 'yellow'], index=[0, 2, 4])\nobj3.reindex(range(6), method='ffill')\n\n'''[Drop]'''\n'''Dropping one or more entries from an axis.'''\nobj = pd.Series(np.arange(5.), index=['a', 'b', 'c', 'd', 'e'])\nnew_obj = obj.drop('c') # drop one item\nobj.drop(['d', 'c']) # drop several items\nobj.drop('c', inplace=True) # operate in place\n\n'''[Indexing, Selection, and Filtering]'''\n'''Retrieve a value'''\nobj = pd.Series(np.arange(4.), index=['a', 'b', 'c', 'd'])\nprint(obj['b'] == obj[1]) # check value either by index or integer index\nobj[obj < 2]\nobj[1:3] # the end point is exclusive if slicing with integer index\nobj['b':'c'] # the end point is inclusive if slicing with labels\nobj['b':'c'] = 5 # if interval length = 1, set one cell; if >1, set all cells as the give value\n\n'''[Data Alignment]'''\n'''Lengths can be different.'''\ns1 = pd.Series([7.3, -2.5, 3.4, 1.5], index=['a', 'c', 'd', 'e'])\ns2 = pd.Series([-2.1, 3.6, -1.5, 4, 3.1], index=['a', 'c', 'e', 'f', 'g'])\ns1 + s2 # only operate on common indexed values, pad any uncommon ones with NaN (single side)\n\n'''[Sorting and Ranking]'''\nobj = pd.Series(range(4), index=['d', 'a', 'b', 'c'])\nobj.sort_index() # sort lexicographically by index\nobj.sort_values() # sort by values\n\n'''[Unique Values, Value Counts, and Membership]'''\nobj = pd.Series(['c', 'a', 'd', 'a', 'a', 'b', 'b', 'c', 'c'])\nuniques = obj.unique()\n\n'''Compute value frequency.'''\nobj.value_counts()\npd.value_counts(obj.values, sort=False) # return a series of frequencies indexed by values,\n\n'''data filtering'''\nmask = obj.isin(['b', 'c']) # return a boolean series indicating if the value occurs\nobj[mask] # return a series with values in mask, indexed by index in obj (not continuous)\n\n'''compute a histogram on multiple related columns'''\ndata = pd.DataFrame({'Qu1': [1, 3, 4, 3, 4], 'Qu2': [2, 3, 1, 2, 3], 'Qu3': [1, 5, 2, 4, 4]})\nresult = data.apply(pd.value_counts).fillna(0) # the row labels in the result are the distinct values occurring in all of the col‐ umns. The values are the respective counts of these values in each column.\n\n\n\n\n\n\n\n'''------------------------------02. DataFrame-------------------------------------'''\n'''A collection of series as columns, each series can be different data type.'''\n\n'''[Construction]'''\ndata = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada', 'Nevada'],\n 'year': [2000, 2001, 2002, 2001, 2002, 2003],\n 'pop': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]}\nframe = pd.DataFrame(data) # keys become column names and sorted, list items become values, index is assigned automatically and \nframe2 = pd.DataFrame(data, columns=['year', 'state', 'pop'], index=['one', 'two', 'three', 'four','five', 'six']) # force column name order\n\npop = {'Nevada': {2001: 2.4, 2002: 2.9}, # outer dict keys as the column names and the inner keys as the row indices\n 'Ohio': {2000: 1.5, 2001: 1.7, 2002: 3.6}}\nframe3 = pd.DataFrame(pop)\nframe3.values #check values in ndarray\nframe3.index.name = 'year' # index has a name\nframe3.columns.name = 'state' # column names also has a general name\nprint(frame3.columns)\nprint(frame3.shape)\n\n'''[Modification]'''\nprint(frame2['state']) # retrieve a series/column by column name/key\nprint(frame2.state)\nframe2['debt'] = 16.5 #create a new column if not included, value can be a scalar, array or a series (aligned, NAN if not matched)\nprint(frame2.loc['three']) # retrieve a row by index\ndel frame2['debt']\n\n'''[Operation]'''\nframe3.T # transpose the DataFrame (swap rows and columns)\nprint(frame3.index.unique())\n\n'''[Reindex]'''\n'''Work for both index and columns.'''\nframe = pd.DataFrame(np.arange(9).reshape((3, 3)), index=['a', 'c', 'd'], columns=['Ohio', 'Texas', 'California'])\nframe2 = frame.reindex(['a', 'b', 'c', 'd'])\nstates = ['Texas', 'Utah', 'California']\nframe.reindex(columns=states)\n \n# frame.loc[['a', 'b', 'c', 'd'], states] # reindex index and columns in one line by 'loc'\n \n'''[Drop]'''\n'''Return new object'''\ndata = pd.DataFrame(np.arange(16).reshape((4, 4)), index=['Ohio', 'Colorado', 'Utah', 'New York'], columns=['one', 'two', 'three', 'four'])\ndata.drop(['Colorado', 'Ohio']) # drop values from the row labels/index (axis 0)\ndata.drop('two', axis=1) # drop values from the columns by passing axis=1 or axis='columns'\ndata.drop(['two', 'four'], axis='columns')\n\n'''[Indexing, Selection, and Filtering]'''\n'''Retrieve a value'''\nprint(data['two']['Colorado']) # fix a column then fix a row, return the VALUE, rather than a pandas object\n\nprint(data.loc['Colorado', 'two']) # fix a row then fix a column, return the VALUE, rather than a pandas object\nprint(data.loc['Colorado', ['two']]) # return a pandas object of single one value\nprint(data.iloc[1, 1])\n\nprint(data.at['Colorado', 'two']) # select a value by ROW label then COLUMN label\nprint(data.iat[1, 1]) # select a value by ROW integer index then COLUMN integer index\n\n\n'''Retrieve a column.'''\n'''Values indexed by index'''\ndata = pd.DataFrame(np.arange(16).reshape((4, 4)), index=['Ohio', 'Colorado', 'Utah', 'New York'], columns=['one', 'two', 'three', 'four'])\ndata['two'] # check a series/column by its name/key, integer index retrieval like data[1] doesn't work\ndata.two\ndata[:2] # get first 2 columns; integer index only works for slicing\ndata < 5 # return an object with boolean values for the condition\ndata[data < 5] = 0 # set all qualified values to 0\n\n'''Retrieve a row.'''\n'''Values indexed by column keys'''\n# print(data.loc['Colorado', ['two', 'three']]) # select a row of 'Colorado', and retrieve some values in the row according to their column name/key\ndata.loc[:'Utah', 'two'] # select rows until 'Utah', and only column 'two'\ndata.iloc[[1, 2], [3, 0, 1]] # select several rows\ndata.iloc[2, [3, 0, 1]] # select by integer index with the same mechanism\ndata.iloc[:, :3][data.three > 5]\n\n'''[Data Alignment]'''\n'''Sizes can be different'''\ndf1 = pd.DataFrame(np.arange(9.).reshape((3, 3)), columns=list('bcd'), index=['Ohio', 'Texas', 'Colorado'])\ndf2 = pd.DataFrame(np.arange(12.).reshape((4, 3)), columns=list('bde'), index=['Utah', 'Ohio', 'Texas', 'Oregon'])\ndf1 + df2 # only operate on values that have the same index and column in both tables, otherwise show 'NaN'; may create new column/index\ndf1.add(df2, fill_value=0) # fill all nan values with 0.\n\n'''DataFrame + Series'''\ns1 = df1.iloc[0] # indexed with column keys\ndf1 + s1 # row broadcasting according to column keys\n\ns2 = df1['b'] # indexed with index\ndf1.add(s2, axis='index') # column broadcasting along index\n\n'''[Function Application and Mapping]'''\nframe = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['Utah', 'Ohio', 'Texas', 'Oregon'])\n\n'''column/row wise function'''\nf = lambda x: x.max() - x.min() # DIY a function\nframe.apply(f) # apply on columns, and return a series indexed by column keys\nframe.apply(f, axis='columns') # apply on rows, and return a series indexed by index\n\nframe.sum() # sum values along columns, indexed by column keys, exclude nan\nframe.sum(axis = 1) # sum values along rows, indexed by index, exclude nan\n\n\n'''element wise function'''\nnp.abs(frame) # all numpy functions work for the dataframe object\n\nformat = lambda x: '%.2f' % x\nframe.applymap(format) # applymap for dataframe to do element wise function\nframe['e'].map(format) # map() for series to do element wise function\n\n'''[Sorting and Ranking]'''\nframe = pd.DataFrame(np.arange(8).reshape((2, 4)), index=['three', 'one'], columns=['d', 'a', 'b', 'c'])\nframe.sort_index() # sort by index\nframe.sort_index(axis=1, ascending=False) # sort by column keys\n\nframe.sort_values(by='b') # sort by values of certain columns\nframe.sort_values(by=['a', 'b'])\n\n\n\n\n'''------------------------------03. Data Cleaning and Preparation-------------------------------------'''\n'''[Missing Data]''' \n\n'''[Removing Duplicates]'''\n\n'''[Transforming Data Using a Function or Mapping]'''\n'''Replacing Values'''\n'''Renaming Axis Indexes'''\n'''Vectorized String Functions'''\n\n\n\n" }, { "alpha_fraction": 0.691058874130249, "alphanum_fraction": 0.70199054479599, "avg_line_length": 39.458744049072266, "blob_id": "b61b9cdbba04837234839910327a912a144ee74e", "content_id": "cce51a750b35a865a27213d76e299b5a35f1fbae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12260, "license_type": "no_license", "max_line_length": 137, "num_lines": 303, "path": "/sklearn_guide.py", "repo_name": "jiaeyan/Data-Analysis-Library-Tutorial", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport sklearn\n\n\n'''\nAssume the data set is a PANDAS DataFrame.\n\n01. Frame the problem\nCheck the objective and existing performance, and then decide:\n a. Supervised? Unsupervised?\n b. Classification? Regression? Sequence tagging?\n c. Batch learning? Online learning?\n\n02. Select a performance measure\n\n03. Check the assumptions\n\n04. Prepare the data\n a. separate the data into train and test sets properly\n b. explore and analyze the train data by visualization and correlations\n c. *combine features\n d. deal with missing values in some features\n e. deal with non-numerical type values in some features\n f. feature scaling\n\n05. Select a model and train\n a. cross validation training\n\n06. Fine Tune the Parameters of the Model\n a. grid search with different combinations of parameters\n b. check the importance of each feature, drop the useless ones\n\n07. Test\n\n08. Save the model\n'''\n\n'''------------------------------Separate data-------------------------'''\nhousing = pd.DataFrame({'a':[0,1,2,3,4], 'b':[5,6,7,8,9]})\n\n'''randomly distribute the test set only if the test set is fixed'''\ndef split_train_test(data, test_ratio):\n # set the random number generator'seed, so every time generates the same result, ensure the fairness of result comparisons\n np.random.seed(42)\n # return a list that randomly permutes the indices of data set\n shuffled_indices = np.random.permutation(len(data))\n # return an integer indicating the train/test set boundary\n test_set_size = int(len(data) * test_ratio)\n # return a list of indices of test instances\n test_indices = shuffled_indices[:test_set_size]\n # return a list of indices of train instances\n train_indices = shuffled_indices[test_set_size:]\n # test set is the rows of indices in test_indices\n return data.iloc[train_indices], data.iloc[test_indices]\n\n'''above function can be replaced by sklearn's function:'''\nfrom sklearn.model_selection import train_test_split\ntrain_set, test_set = train_test_split(housing, test_size=0.2, random_state=42) # where 'data' is arrays object from any 3rd party source\n\n'''stratified sampling: ensure the test set is representative in the most important ONE feature'''\n# convert values in column 'median_income' into certain categories\nhousing[\"income_cat\"] = np.ceil(housing[\"a\"] / 1.5)\n# convert values in column that are < 5 to 5.\nhousing[\"income_cat\"].where(housing[\"income_cat\"] < 5, 5.0, inplace=True)\n\nfrom sklearn.model_selection import StratifiedShuffleSplit\n# create an instance of the imported class\n# n_splits: number of re-shuffling & splitting iterations, the result of each iteration is: (train_index_list, test_index_list)\n# if multiple iterations, the results will be concatenated: [(train1, test1), (train2, test2), (train3, test3), ...]\nsplit = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)\n# split the given data according the given label array\nfor train_index_list, test_index_list in split.split(housing, housing[\"income_cat\"]):\n # the indices for train and test\n strat_train_set = housing.loc[train_index_list]\n strat_test_set = housing.loc[test_index_list]\n\n# if the test set will be updated later, write a hash function to convert\n# each instance's unique identifier to decide if the instance should be in test set\n\n\n'''-------------------------------Visualization------------------------------------------------'''\n# chose the graph type, then select the columns/features you'd like to show relations\nhousing.plot(kind=\"scatter\", x=\"median_income\", y=\"median_house_value\", alpha=0.1)\n\n\n\n\n\n'''-------------------------------Find correlations between features----------------------------'''\n'''Numerical check'''\ncorr_matrix = housing.corr()\n# select a column, and function below displays pairwise correlation of columns to selected column, excluding NA/null values\n# default is Pearson's relation, a measure of the linear correlation between two variables X and Y.\n# 1 means strong positive correlation while -1 means strong negative correlation and 0 means no linear correlation\ncorr_matrix[\"median_house_value\"].sort_values(ascending=False)\n\n'''Graph check'''\nfrom pandas.plotting import scatter_matrix\n# the list of features you'd like to check relations\nattributes = [\"median_house_value\", \"median_income\", \"total_rooms\", \"housing_median_age\"]\n# return a figure, each row represents current feature's relations with others\nscatter_matrix(housing[attributes], figsize=(12, 8))\n\n\n\n\n'''------------------------------Combine relative features---------------------------------------'''\n'''\nSome features alone don't offer much useful information, and also may have low correlations with\ntarget feature; but if combined with other features by some computation, the correlation may improve.\n\nhousing[\"rooms_per_household\"] = housing[\"total_rooms\"]/housing[\"households\"]\nhousing[\"bedrooms_per_room\"] = housing[\"total_bedrooms\"]/housing[\"total_rooms\"]\nhousing[\"population_per_household\"]=housing[\"population\"]/housing[\"households\"]\n'''\n\n\n\n\n'''------------------------------Missing values in features-------------------------------------------------'''\n# Get rid of the corresponding instances.\nhousing.dropna(subset=[\"total_bedrooms\"])\n# Get rid of the feature/column.\nhousing.drop(\"total_bedrooms\", axis=1)\n# Set the missing values to some value.\nmedian = housing[\"total_bedrooms\"].median()\nhousing[\"total_bedrooms\"].fillna(median)\n\n'''sklearn way to fill in missing values'''\nfrom sklearn.preprocessing import Imputer\n# define a strategy to deal with missing values when creating an instance\nimputer = Imputer(strategy=\"median\")\n# get rid of string type features/columns\nhousing_num = housing.drop(\"ocean_proximity\", axis=1)\n# fit the instance with the data, generates a statics in \"imputer.statistics_\"\nimputer.fit(housing_num)\n# check the result median column\nprint(imputer.statistics_)\n# fill in and transform the original train data\nX = imputer.transform(housing_num)\n# convert X back to pandas' DataFrame object\nhousing_tr = pd.DataFrame(X, columns=housing_num.columns)\n\n'''---------------------------------Non-numerical values in features--------------------------------'''\n'''Encode each label/non-numerical value into a unique number, from 0 to len(column)'''\n'''Issue: will assume that two nearby values are more similar than two distant values.'''\nfrom sklearn.preprocessing import LabelEncoder\n# create an instance of this helper class\nencoder = LabelEncoder()\n# select the feature/column that has non-numerical values\nhousing_cat = housing[\"ocean_proximity\"]\n# perform encoding procedure; fit_transform() = fit() + transform()\nhousing_cat_encoded = encoder.fit_transform(housing_cat)\n# check the mapping\nprint(encoder.classes_)\n\n'''Encode each label/non-numerical value into a one-hot-vector'''\nfrom sklearn.preprocessing import OneHotEncoder\nencoder = OneHotEncoder()\n# returns a SciPy sparse matrix\nhousing_cat_1hot = encoder.fit_transform(housing_cat_encoded.reshape(-1,1))\n# convert to numpy ndarray\nhousing_cat_1hot.toarray()\n\n\n'''Encode from text categories to integer categories, then from integer categories to one-hot vectors in one shot'''\nfrom sklearn.preprocessing import LabelBinarizer\nencoder = LabelBinarizer()\n# returns a dense NumPy array\nhousing_cat_1hot = encoder.fit_transform(housing_cat, sparse_output=False)\n\n'''----------------------------------Feature scaling--------------------------------'''\n'''ML algorithms don't perform well when the input numerical attributes have very different scales.'''\n'''\nMinMaxScaler(), affected by mistaken max values, range in 0-1 or diy else\nStandardScaler(), not affected by wrong max values, but not in range\n'''\n\n'''Custom transformers and pipeline them, both with numerical and non-numerical values.'''\n\n'''----------------------------------Train and Evaluate-------------------------------'''\nfrom sklearn.linear_model import LinearRegression\nlin_reg = LinearRegression()\n# train a model with prepared and cleaned data and relative labels\nlin_reg.fit(housing, ['put label list here'])\n\n# take a little training set to play with\nsome_data = housing.iloc[:5]\nsome_labels = housing_labels.iloc[:5]\n# clean and prepare the small train set\nsome_data_prepared = full_pipeline.transform(some_data)\n\nprint(\"Predictions:\\t\", lin_reg.predict(some_data_prepared))\n#Predictions: [ 303104. 44800. 308928. 294208. 368704.]\nprint(\"Labels:\\t\\t\", list(some_labels))\n\n# measure this regression model’s RMSE on the whole training set\nfrom sklearn.metrics import mean_squared_error\nhousing_predictions = lin_reg.predict(housing_prepared)\nlin_mse = mean_squared_error(housing_labels, housing_predictions) \nlin_rmse = np.sqrt(lin_mse)\n\n'''Evaluate with Cross-Validation'''\nfrom sklearn.model_selection import cross_val_score\n# cv: how many subsets you'd like to apply\nscores = cross_val_score(lin_reg, housing_prepared, housing_labels, scoring=\"neg_mean_squared_error\", cv=10)\n# return an array of rmse result from each cross validation training\nrmse_scores = np.sqrt(-scores)\n\n# there are 10 results in 'scores', thus calculate their mean and std\ndef display_scores(scores):\n print(\"Scores:\", scores)\n print(\"Mean:\", scores.mean())\n print(\"Standard deviation:\", scores.std())\n\ndisplay_scores(rmse_scores)\n\n\n'''--------------------------------Fine tune the model-----------------------------'''\n'''Grid Search'''\n# evaluate all the possible combinations of hyperparameter values, using cross-validation.\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import RandomForestRegressor\n\n# a list of dicts of combinations of parameters you'd like to test\n# one dict is one combination, here is two, and there are 3*4 + 2*3 = 18 combinations\n# the key in each dict should match the parameter names of given model\nparam_grid = [\n {'n_estimators': [3, 10, 30], 'max_features': [2, 4, 6, 8]},\n {'bootstrap': [False], 'n_estimators': [3, 10], 'max_features': [2, 3, 4]},\n]\n\n# define a model\nforest_reg = RandomForestRegressor()\n\n# define an instance of the estimator, feed in the parameters\ngrid_search = GridSearchCV(forest_reg, param_grid, cv=5,\n scoring='neg_mean_squared_error')\n\n# train the model\ngrid_search.fit(housing_prepared, housing_labels)\n\n# check the best parameters\ngrid_search.best_params_\n\n# get the best estimator directly\ngrid_search.best_estimator_\n\n# get the evaluation scores on the hold-out set of cross validation\ncvres = grid_search.cv_results_\nfor mean_score, params in zip(cvres[\"mean_test_score\"], cvres[\"params\"]):\n print(np.sqrt(-mean_score), params)\n\n'''Check the importance of each feature'''\n# only return a list of figures, no correspoding feature names\nfeature_importances = grid_search.best_estimator_.feature_importances_\nextra_attribs = [\"rooms_per_hhold\", \"pop_per_hhold\", \"bedrooms_per_room\"]\ncat_one_hot_attribs = list(encoder.classes_)\nattributes = num_attribs + extra_attribs + cat_one_hot_attribs\nsorted(zip(feature_importances, attributes), reverse=True)\n\n\n\n'''--------------------------------------Test------------------------------------------'''\n# get the best model with best parameters\nfinal_model = grid_search.best_estimator_\n\n# get the test data, separating the label column\n# test data\nX_test = strat_test_set.drop(\"median_house_value\", axis=1)\n# test data's labels\ny_test = strat_test_set[\"median_house_value\"].copy()\n\n# clean the test data\nX_test_prepared = full_pipeline.transform(X_test)\n\n# make predictions on test data and returns a list of results\nfinal_predictions = final_model.predict(X_test_prepared)\n\n# get the results\nfinal_mse = mean_squared_error(y_test, final_predictions)\nfinal_rmse = np.sqrt(final_mse) # => evaluates to 48,209.6\n\n\n'''---------------------------------Save the model----------------------------------'''\n# a model example\nfrom sklearn import svm\nfrom sklearn import datasets\nclf = svm.SVC()\niris = datasets.load_iris()\nX, y = iris.data, iris.target\nclf.fit(X, y)\n\n'''Store with Python's pickle.'''\nimport pickle\ns = pickle.dumps(clf)\nclf2 = pickle.loads(s)\n\n'''Store with Sklearn's joblib.'''\nfrom sklearn.externals import joblib\njoblib.dump(clf, 'filename.pkl') \nclf = joblib.load('filename.pkl')" }, { "alpha_fraction": 0.84375, "alphanum_fraction": 0.84375, "avg_line_length": 32, "blob_id": "0c20127a560fb144ee31a6478c9f86bbc25f0d61", "content_id": "075221772c46dcaca1032a2f64c9ef73bcd089b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 32, "license_type": "no_license", "max_line_length": 32, "num_lines": 1, "path": "/README.md", "repo_name": "jiaeyan/Data-Analysis-Library-Tutorial", "src_encoding": "UTF-8", "text": "# Data-Analysis-Library-Tutorial" } ]
3
jsgomezc/Maps
https://github.com/jsgomezc/Maps
0ee8f186a58342e8fbfd39bf1350b572be9e5bf5
bc7748b907f3649af9b4029bba2020b5409cf343
85aedc44664a77ce963edffd088b61ea85ec1b5e
refs/heads/master
2022-12-17T13:04:07.941251
2020-09-05T17:48:33
2020-09-05T17:48:33
286,526,372
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 31.5, "blob_id": "5fcd1a238ef5980d475171ba9edca8547838cf7a", "content_id": "cec30379a4d4c1ea7b1e2ffab986b2cfc27ed1e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 65, "license_type": "no_license", "max_line_length": 57, "num_lines": 2, "path": "/README.md", "repo_name": "jsgomezc/Maps", "src_encoding": "UTF-8", "text": "# Maps\nJust a few codes to create maps using Python and Basemap.\n" }, { "alpha_fraction": 0.5965103507041931, "alphanum_fraction": 0.6750272512435913, "avg_line_length": 22.512821197509766, "blob_id": "6554f17c9eb036333624b11cf24a22c77109d187", "content_id": "e7b874d85e03b5453200d3b1ffc15e53fcaee3d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 917, "license_type": "no_license", "max_line_length": 57, "num_lines": 39, "path": "/world_location.py", "repo_name": "jsgomezc/Maps", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 31 11:55:35 2020\n\n@author: juancho\n\"\"\"\n\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nfig = plt.figure(figsize=(10,10))\n\n#ax = fig.add_subplot(111)\nax0 = fig.add_subplot(111)\n# make sure the value of resolution is a lowercase L,\n# for 'low', not a numeral 1\nmap = Basemap(projection='ortho', lat_0=4, lon_0=-72,\n resolution='i', area_thresh=500.0)\n \nmap.drawcoastlines()\nmap.drawcountries()\nmap.fillcontinents(color='#9c9c9c', lake_color='#ADD8E6')\nmap.drawmapboundary(fill_color='#ADD8E6')\nmap.drawmeridians(np.arange(0, 360, 30))\nmap.drawparallels(np.arange(-90, 90, 30))\n\n# Drawing the box\nlons = [-81, -65, -65, -81, -81]\nlats = [-6, -6, 14, 14, -6]\n\nx, y = map(lons, lats)\n\nmap.plot(x, y, marker=None, color='r', linewidth=3)\n\n\nplt.savefig('world_location.png', transparent=True)\n" }, { "alpha_fraction": 0.5353068113327026, "alphanum_fraction": 0.6151711344718933, "avg_line_length": 29.60377311706543, "blob_id": "20483ff0786e2b1e40b0dd9641837565463e34cd", "content_id": "d2f185f13735ea164e3eadad492213bc565f6952", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3243, "license_type": "no_license", "max_line_length": 133, "num_lines": 106, "path": "/specific_location.py", "repo_name": "jsgomezc/Maps", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 31 14:14:16 2020\n\n@author: juancho\n\"\"\"\n\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\nimport numpy as np\n\n\nfig = plt.figure(figsize=(10,15))\n\n#ax = fig.add_subplot(111)\nax0 = fig.add_subplot(111)\n\nmap = Basemap(llcrnrlon=-75.3, llcrnrlat=2.1, urcrnrlon=-71.8, urcrnrlat=6.5, epsg=3116, resolution='i')\n#http://server.arcgisonline.com/arcgis/rest/services\n\nmap.arcgisimage(service='World_Imagery', xpixels = 1500, verbose= True)\n\n#map.drawstates(linewidth = 0.1, color='white')\n#map.drawrivers(color='blue')\nmap.drawparallels(range(-4, 15, 1), labels=[True,False,False,True],dashes=[2,2], fontsize=30)\nmap.drawmeridians(range(-87, -61, 1), labels=[True,False,False,True], dashes=[2,2], fontsize=30)\n\nmap.readshapefile('/home/juancho/Documentos/GeneralGeo/FallasColombia/FallasColombia', 'faults', color='white', linewidth=0.3)\n\n# USME\nlon = -74.126777\nlat = 4.480951\n\nx, y = map(lon, lat)\n\nmap.scatter(x, y, marker='v', color='r', s=250)\n#map.scatter(x, y, marker='o', color='r', s=135000, alpha=0.2, linewidth=3, edgecolor='r')\nplt.text(x, y, 'USME',fontsize=25, fontweight='bold', color='white')\n\n\n# TUNJ\nlon = -73.357760\nlat = 5.533368\n\nx, y = map(lon, lat)\n\nmap.scatter(x, y, marker='v', color='r', s=250)\nplt.text(x, y, 'TUNJ',fontsize=25, fontweight='bold', color='white')\n\n\n\n# Plotear los sismos\n\nlons = [-74.184, -74.154, -74.168, -74.161]\nlats = [3.462, 3.465, 3.425, 3.426]\ndepth = [13, 12, 10, 19]\nmag = [6, 5.8, 4.7, 4.7]\n\n# Increasing difference in Magnitude\ns = [(1/4000)*n**9 for n in mag]\n\nx, y = map(lons, lats)\n\nscatter = map.scatter(x, y, marker='o', c=depth, s=s, edgecolor='white')\n\n#kw = dict(prop=\"sizes\", num=4, color='black', func=lambda s: (8000*s**(1/9)))\n#legend2 = ax0.legend(*scatter.legend_elements(**kw), loc=2, title=\"Mag.\")\n\n#divider = make_axes_locatable(ax0)\n#cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n\ncb = fig.colorbar(scatter, fraction=0.03, pad=-0.18)\ncb.set_label(label='$Earthquake$ $depth$ $(km)$', size=23, color='white')\ncb.ax.tick_params(labelsize=23, labelcolor='white')\n\n# Legend Elements\nlegend_elements = [Line2D([0], [0], marker='o', markeredgewidth=1, markeredgecolor='white', color='#2b7cde', lw=0,label='$M_w=6$',\n markersize=31)\n ,Line2D([0], [0], marker='o', markeredgewidth=1, markeredgecolor='white', color='#fdff64', lw=0,label='$M_w=4.7$',\n markersize=17)\n ,Line2D([0], [0], lw=1, color='w', label='Faults',\n markersize=30)]\n\nlegend = ax0.legend(handles=legend_elements, loc='lower left', fontsize=23)\n# plt.setp(legend.get_texts(), color='w')\n\nx, y = map(-75, 6.2)\nx2, y2 = map(-75.05, 5.8)\n\nplt.annotate('N', xy=(x, y),\n xytext=(x2, y2),\n color='white',\n arrowprops=dict(arrowstyle=\"fancy\", color='white'),\n fontsize=25\n )\n\n\nmap.drawmapscale(-72.5, 2.45, -73.9, 3.25, 100, barstyle='fancy', fontcolor='white', fontsize=27)\n\n\n\n#plt.savefig('mapaLocalizacion.png')\nplt.show()\n#---------------------------------------------------------------------" }, { "alpha_fraction": 0.5223848819732666, "alphanum_fraction": 0.6187142133712769, "avg_line_length": 24.187166213989258, "blob_id": "9ddba8d3486fd32eb1a8781663d037d683808525", "content_id": "81deeeac876d526925b18602dc953d1cebccb4cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4713, "license_type": "no_license", "max_line_length": 98, "num_lines": 187, "path": "/mapaBasemap.py", "repo_name": "jsgomezc/Maps", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 29 22:25:37 2020\n\n@author: juancho\n\"\"\"\n\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\n#from obspy.geodetics import kilometers2degrees\nfrom matplotlib.lines import Line2D\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\n\n\nfig = plt.figure(figsize=(10,15))\n\n#ax = fig.add_subplot(111)\nax0 = fig.add_subplot(111)\n\nmap = Basemap(llcrnrlon=-80, llcrnrlat=-5, urcrnrlon=-66, urcrnrlat=13, epsg=3116, resolution='h')\n#http://server.arcgisonline.com/arcgis/rest/services\n\nmap.arcgisimage(service='World_Imagery', xpixels = 1500, verbose= True)\n\nmap.drawcountries(linewidth = 0.6, color='white')\nmap.drawcoastlines(linewidth = 0.6, color='white')\nmap.drawstates(linewidth = 0.3, color='white')\n#map.drawrivers(color='blue')\nmap.drawparallels(range(-4, 15, 4), labels=[True,False,False,True],dashes=[2,2], fontsize=20)\nmap.drawmeridians(range(-87, -61, 4), labels=[True,False,False,True], dashes=[2,2], fontsize=20)\n\n# USME\nlon = -74.126777\nlat = 4.480951\n\nx, y = map(lon, lat)\n\nmap.scatter(x, y, marker='v', color='r', s=100)\n#map.scatter(x, y, marker='o', color='r', s=135000, alpha=0.2, linewidth=3, edgecolor='r')\nplt.text(x, y, 'USME',fontsize=15, fontweight='bold', color='white')\n'''\ndist = kilometers2degrees(500)\n\nlons = [-74.126777, -74.126777]\nlats = [4.480951, 4.480951+dist]\n\nx, y = map(lons, lats)\n\nmap.plot(x, y, marker=None,color='r')\n\nlon = -74.6\nlat = 6.3\n\nx, y = map(lon, lat)\n\nplt.text(x, y, '$500km$',fontsize=17, fontweight='bold', color='white', rotation=90)\n'''\n\n# TUNJ\nlon = -73.357760\nlat = 5.533368\n\nx, y = map(lon, lat)\n\nmap.scatter(x, y, marker='v', color='r', s=100)\nplt.text(x, y, 'TUNJ',fontsize=15, fontweight='bold', color='white')\n\n\n'''\n# VCIO\nlon = -73.592480\nlat = 4.111264\n\nx, y = map(lon, lat)\n\nmap.scatter(x, y, marker='v', color='r', s=100)\n#plt.text(x, y, 'VCIO',fontsize=7, fontweight='bold', color='white')\n\n# ZIPA\nlon = -74.0693056\nlat = 5.07930556\n\nx, y = map(lon, lat)\n\nmap.scatter(x, y, marker='v', color='y', s=100)\n#plt.text(x, y, 'ZIPA',fontsize=7, fontweight='bold', color='white')\n\n# CUSI\nlon = -72.6811086\nlat = 5.01782219\n\nx, y = map(lon, lat)\n\nmap.scatter(x, y, marker='v', color='y', s=100)\n#plt.text(x, y, 'CUSI',fontsize=7, fontweight='bold', color='white')\n\n# SJRS\nlon = -74.5832194\nlat = 4.86000107\n\nx, y = map(lon, lat)\n\nmap.scatter(x, y, marker='v', color='y', s=100)\n#plt.text(x, y, 'CUSI',fontsize=7, fontweight='bold', color='white')\n\n# BUPI\nlon = -72.969383 \t\nlat = 4.568678\n\nx, y = map(lon, lat)\n\nmap.scatter(x, y, marker='v', color='y', s=100)\n#plt.text(x, y, 'BUPI',fontsize=7, fontweight='bold', color='white')\n\n# CHRL\nlon = -74.973338 \t \t\nlat = 4.22324604\n\nx, y = map(lon, lat)\n\nmap.scatter(x, y, marker='v', color='y', s=100)\n#plt.text(x, y, 'CHRL' ,fontsize=7, fontweight='bold', color='white')\n\n# ICZO\nlon = -74.600273\t \t\nlat = 4.174588\n\nx, y = map(lon, lat)\n\nmap.scatter(x, y, marker='v', color='y', s=100)\n#plt.text(x, y, 'ICZO' ,fontsize=7, fontweight='bold', color='white')\n'''\n# Plotear los sismos\n\nlons = [-74.184, -74.154, -74.168, -74.161]\nlats = [3.462, 3.465, 3.425, 3.426]\ndepth = [13, 12, 10, 19]\nmag = [6, 5.8, 4.7, 4.7]\n\n# Increasing difference in Magnitude\ns = [(1/8000)*n**9 for n in mag]\n\nx, y = map(lons, lats)\n\nevents = map.scatter(x, y, marker='o', c=depth, s=s, edgecolor='white')\n\n#divider = make_axes_locatable(ax0)\n#cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n\n#cb = fig.colorbar(events, fraction=0.03, pad=-0.15)\n#cb.set_label(label='$Earthquake$ $depth$ $(km)$', size=20, color='white')\n#cb.ax.tick_params(labelsize=15, labelcolor='white')\n\n# Legend Elements\nlegend_elements = [Line2D([0], [0], marker='v', color='r', lw=0,label='Multiparametric\\nstations',\n markersize=15)\n ,Line2D([0], [0], marker='o', color='#572364', lw=0,label='Seismic events',\n markersize=15)]\n\nlegend = ax0.legend(handles=legend_elements, loc='lower left', fontsize=20)\n# plt.setp(legend.get_texts(), color='w')\n\nx, y = map(-78.2, 12.2)\nx2, y2 = map(-78.35, 10.7)\n\nplt.annotate('N', xy=(x, y),\n xytext=(x2, y2),\n color='white',\n arrowprops=dict( arrowstyle=\"fancy\", color='white'),\n fontsize=20\n )\n\nmap.drawmapscale(-69, -3.7, -74.5, 4.5, 400, barstyle='fancy', fontcolor='white', fontsize=17)\n\n# Drawing the box\nlons = [-75.3, -71.8, -71.8, -75.3, -75.3]\nlats = [2, 2, 6.5, 6.5, 2]\n\nx, y = map(lons, lats)\n\nmap.plot(x, y, marker=None, color='r', linewidth=1)\n\n#plt.savefig('mapaLocalizacion.png')\nplt.show()\n#---------------------------------------------------------------------\n\n\n\n" } ]
4
Schattenkind/OGameBot
https://github.com/Schattenkind/OGameBot
a6d5b9e443d6cf0e98702235eeb48594b7be2951
dc65f1266a1315e8fd28942655a6cb94bf78cfbe
ff9bd7b5b7e57b306fe5be283d1f23d83b93ce31
refs/heads/master
2020-04-06T03:38:46.635498
2018-04-22T19:31:01
2018-04-22T19:31:01
60,421,326
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5700680017471313, "alphanum_fraction": 0.5721088647842407, "avg_line_length": 28.399999618530273, "blob_id": "986f640685bf12482d4f6255ef71bd8d23d8d604", "content_id": "3c4c786d1f80643daf813ff422cf7fc142aa6bc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1470, "license_type": "no_license", "max_line_length": 138, "num_lines": 50, "path": "/info/page_info.py", "repo_name": "Schattenkind/OGameBot", "src_encoding": "UTF-8", "text": "import logging\nimport time\nimport os\nimport errno\n\n\nlogger = logging.getLogger('ogame_bot.info.page_info')\n\n\nclass Page(object):\n def __init__(self, session, url, data=None):\n self.logger = logger\n self._url = url\n\n if data is None:\n self._data = {}\n else:\n self._data = data\n\n self._session = session\n self._content = ''\n self.last_refresh_time = 0\n self.refresh_content()\n\n def refresh_content(self, force_refresh=False):\n current_time = time.time()\n time_delta = current_time - self.last_refresh_time\n if force_refresh or time_delta > 5:\n self.logger.debug(\"Refreshing site info for site: \" + self._url)\n self.content = str(self._session.get(self._url, data=self._data).content)\n self.last_refresh_time = current_time\n else:\n self.logger.debug(\"Last refresh of site \" + self._url + \" was only \" + str(time_delta) + \" seconds before. Skipping refresh!\")\n\n @property\n def content(self):\n return self._content\n\n @content.setter\n def content(self, content):\n try:\n os.makedirs(\"page_contents\")\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n file_name = self._url.split(\"=\")[-1] + \".txt\"\n with open(os.path.join(\"page_contents\", file_name), 'w') as file:\n file.write(content)\n self._content = content\n" }, { "alpha_fraction": 0.5821033120155334, "alphanum_fraction": 0.5917896628379822, "avg_line_length": 30.420289993286133, "blob_id": "9830f59697814a271795f0cfb41a18a40ae1a5b1", "content_id": "c38c5a2ac74f9e90886985b4210c2e54c29ee185", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2168, "license_type": "no_license", "max_line_length": 106, "num_lines": 69, "path": "/info/resources.py", "repo_name": "Schattenkind/OGameBot", "src_encoding": "UTF-8", "text": "import re\nimport logging\n\nfrom constants import FIND_RESOURCE_ACT_CAP_PROD, FIND_ENERGY\n\n\n__all__ = ['Resource', 'Energy', 'METAL', 'CRYSTAL', 'DEUTERIUM', 'ENERGY']\n\nlogger = logging.getLogger('ogame_bot.info.resources')\n\n\nMETAL = 0\nCRYSTAL = 1\nDEUTERIUM = 2\nENERGY = 3\n\n\nclass Resource(object):\n def __init__(self, name, info_page):\n self.logger = logger\n self.name = name\n self.actual = 0\n self.production = 0\n self.capacity = 0\n self._info_page = info_page\n self.refresh_info()\n\n def __str__(self):\n return \"Resource {name}(actual: {actual}; production: {production}; capacity: {capacity})\".format(\n name=self.name, actual=self.actual, production=self.production, capacity=self.capacity)\n\n def extract_resource_info(self):\n extract_resource_numbers = re.findall(FIND_RESOURCE_ACT_CAP_PROD.format(name=self.name.lower()),\n self._info_page.content)\n numbers = []\n for number in extract_resource_numbers:\n numbers.append(re.findall('[0-9\\.]+', number))\n if not numbers:\n return 0, 0, 0\n return numbers[0]\n\n def refresh_info(self, refresh_page=True):\n if refresh_page:\n self._info_page.refresh_content()\n numbers = self.extract_resource_info()\n self.actual = int(numbers[1])\n self.capacity = int(numbers[2])\n self.production = float(numbers[3])\n\n\nclass Energy(Resource):\n def extract_resource_info(self):\n extract_resource_numbers = re.findall(FIND_ENERGY, self._info_page.content)\n numbers = []\n for number in extract_resource_numbers:\n n = re.findall('.[0-9\\.]+', number)[1]\n try:\n numbers.append(int(n))\n except ValueError:\n numbers.append(int(n[1:]))\n return numbers[0]\n\n def refresh_info(self, refresh_page=True):\n if refresh_page:\n self._info_page.refresh_content()\n number = self.extract_resource_info()\n self.actual = int(number)\n self.capacity = int(number)\n self.production = int(number)\n" }, { "alpha_fraction": 0.6033430695533752, "alphanum_fraction": 0.6078535318374634, "avg_line_length": 30.672269821166992, "blob_id": "9886600640648a2bbe7ca11a5386170bd2315d5a", "content_id": "63f7eb445baf7dbdd37337577272f2678d356d5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3769, "license_type": "no_license", "max_line_length": 116, "num_lines": 119, "path": "/game.py", "repo_name": "Schattenkind/OGameBot", "src_encoding": "UTF-8", "text": "import re\nimport requests\nimport logging\nimport os\nimport time\n\nfrom info.page_info import Page\nfrom constants import *\n\n\nlogger = logging.getLogger('ogame_bot')\n\n\ndef initialize_logger():\n # create logger\n logger.setLevel(logging.DEBUG)\n\n # create file handler which logs even debug messages\n number_of_sessions = 0\n file_name = \"session_0.log\"\n while os.path.isfile(file_name):\n file_name = \"session_\" + str(number_of_sessions) + \".log\"\n number_of_sessions += 1\n fh = logging.FileHandler(file_name)\n fh.setLevel(logging.DEBUG)\n\n # create console handler with a higher log level\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n\n # create formatter and add it to the handlers\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n\n # add the handlers to the logger\n logger.addHandler(fh)\n logger.addHandler(ch)\n\n\nclass Game(object):\n UNIVERSE_SPEED = 1\n UNIVERSE_SPEED_FLEET = 1\n\n def __init__(self, server, user, password):\n self.logger = logger\n\n self.server = server\n self.user = user\n self.password = password\n self.session = requests.Session()\n\n self.planets = {}\n self.login()\n\n Game.UNIVERSE_SPEED = self.get_basic_parameter_value(FIND_UNIVERSE_SPEED)\n if Game.UNIVERSE_SPEED == 0:\n self.logger.warning(\"Could not set universe speed! Setting it to 1\")\n Game.UNIVERSE_SPEED = 1\n else:\n self.logger.info(\"Universe speed has been set to: \" + str(Game.UNIVERSE_SPEED))\n\n Game.UNIVERSE_SPEED_FLEET = self.get_basic_parameter_value(FIND_UNIVERSE_SPEED_FLEET)\n if Game.UNIVERSE_SPEED_FLEET == 0:\n self.logger.warning(\"Could not set universe fleet speed! Setting it to 1\")\n Game.UNIVERSE_SPEED_FLEET = 1\n else:\n self.logger.info(\"Universe fleet speed has been set to: \" + str(Game.UNIVERSE_SPEED_FLEET))\n self.get_planets()\n\n self.current_planet = self.planets['main']\n\n def login(self):\n url = LOGIN_PAGE\n user = self.user\n password = self.password\n uni = self.server\n\n self.logger.info(\"Trying to login as user \" + self.user)\n self.session.get(url)\n self.logger.debug(\"Get with URL: \" + url)\n login_data = {'kid': '',\n 'uni': uni,\n 'login': user,\n 'pass': password}\n\n self.session.post(url, data=login_data, headers=HEADERS_DICT)\n self.logger.debug(\"Post with URL: \" + url + \"; data: \" + str(login_data) + \"; headers: \"+ str(HEADERS_DICT))\n\n def get_planets(self):\n from planet import Planet\n self.planets = {'main': Planet(self.session)}\n\n def exit_game(self):\n self.logger.info(\"Exiting the game and closing the session.\")\n self.session.close()\n\n def get_basic_parameter_value(self, value):\n extract_resource_numbers = re.findall(value, Page(self.session, RESOURCE_PAGE).content)\n numbers = []\n for number in extract_resource_numbers:\n numbers.append(re.findall('[0-9.]+', number))\n try:\n number = int(numbers[0][0])\n self.logger.debug(\"Found number \" + str(number) + \" with regex: \" + value)\n except IndexError:\n self.logger.warning(\"Couldn't find any number with regex: \" + value)\n number = 0\n return number\n\n\nif __name__ == \"__main__\":\n initialize_logger()\n try:\n Game(SERVER, USER, PASSWORD)\n while True:\n time.sleep(1)\n except Exception as e:\n logger.exception(\"Uncaught Exception was raised! Exiting\")\n" }, { "alpha_fraction": 0.5473110675811768, "alphanum_fraction": 0.5518493056297302, "avg_line_length": 42.2156867980957, "blob_id": "98596e21859364384ab0270ada303b52e6d8ee4b", "content_id": "0afba978b5f8385aed81ce95545064fa094d31b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4407, "license_type": "no_license", "max_line_length": 111, "num_lines": 102, "path": "/planet.py", "repo_name": "Schattenkind/OGameBot", "src_encoding": "UTF-8", "text": "import logging\nfrom constants import *\nfrom info.page_info import Page\nfrom info.resources import *\nfrom buildings.building import *\nfrom buildings.queue import BuildQueue\n\n\nlogger = logging.getLogger('ogame_bot.planet')\n\n\nclass Planet(object):\n \"\"\" Simulates a planet in ogame. Contains pages for the planet buildings and resources.\n \"\"\"\n\n def __init__(self, session, id='0'):\n \"\"\"\n :param session: Current ogame session\n \"\"\"\n self.session = session\n self.logger = logger\n self.buildings_queue = BuildQueue(self)\n\n # load pages\n self.pages = {'resource': Page(self.session, RESOURCE_PAGE),\n 'overview': Page(self.session, OVERVIEW_PAGE),\n 'station': Page(self.session, STATION_PAGE)}\n\n self.resources = {METAL: Resource('Metal', self.pages['resource']),\n CRYSTAL: Resource('Crystal', self.pages['resource']),\n DEUTERIUM: Resource('Deuterium', self.pages['resource']),\n ENERGY: Energy('Energy', self.pages['resource'])}\n\n self.buildings = {METAL_MINE: Building('Metal Mine', Page(self.session, METAL_MINE_URL), 'supply1'),\n CRYSTAL_MINE: Building('Crystal Mine', Page(self.session, CRYSTAL_MINE_URL),\n 'supply2'),\n DEUTERIUM_MINE: Building('Deuterium Mine', Page(self.session, DEUTERIUM_MINE_URL),\n 'supply3'),\n SOLAR: Building('Solar', Page(self.session, SOLAR_URL), 'supply4',\n energy_producer=True),\n FUSION: Building('Fusion', Page(self.session, FUSION_URL), 'supply12',\n energy_producer=True),\n METAL_STORAGE: Building('Metal Storage', Page(self.session, METAL_STORAGE_URL),\n 'supply22'),\n CRYSTAL_STORAGE: Building('Crystal Storage', Page(self.session, CRYSTAL_STORAGE_URL),\n 'supply23'),\n DEUTERIUM_STORAGE: Building('Deuterium Storage',\n Page(self.session, DEUTERIUM_STORAGE_URL),\n 'supply24')\n }\n\n self.id = id\n self.fill_queue()\n self.logger.info('Starting queue for planet ' + self.id)\n self.buildings_queue.start()\n\n def refresh_info(self):\n self.logger.debug(\"Start refresh of planet info. (Planet ID \" + self.id + \")\")\n for page in self.pages:\n self.pages[page].refresh_content()\n for resource in self.resources:\n # not necessary to refresh the page since it was just refreshed\n self.resources[resource].refresh_info(refresh_page=False)\n for building in self.buildings:\n self.buildings[building].refresh_info()\n\n def fill_queue(self):\n self.refresh_info()\n metal_mine_level = self.buildings[METAL_MINE].level\n crystal_mine_level = self.buildings[CRYSTAL_MINE].level\n deuterium_mine_level = self.buildings[DEUTERIUM_MINE].level\n solar_level = self.buildings[SOLAR].level\n\n current_energy = self.resources[ENERGY].actual\n\n message = \"Figuring out what to do next... Current planet (ID: \" + self.id + \") state:\\n\"\n for b in self.buildings:\n message += str(self.buildings[b]) + \"\\n\"\n\n for r in self.resources:\n message += str(self.resources[r]) + \"\\n\"\n\n self.logger.info(message)\n\n if current_energy < 0 and solar_level < 15:\n self.upgrade_building(self.buildings[SOLAR])\n\n elif metal_mine_level - 3 > crystal_mine_level:\n self.upgrade_building(self.buildings[CRYSTAL_MINE])\n\n elif crystal_mine_level - 4 > deuterium_mine_level and crystal_mine_level > 10:\n self.upgrade_building(self.buildings[DEUTERIUM_MINE])\n\n else:\n self.upgrade_building(self.buildings[METAL_MINE])\n\n\n def upgrade_building(self, building):\n \"\"\"\n :param building: building to be upgraded\n \"\"\"\n return self.buildings_queue.add_to_queue(building)" }, { "alpha_fraction": 0.7299270033836365, "alphanum_fraction": 0.7518247961997986, "avg_line_length": 26.399999618530273, "blob_id": "8a476d40a498fe413ee00c7665ea74539309ce61", "content_id": "940d04a47060984bb0f3984a5d39cbecc2de6aaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 137, "license_type": "no_license", "max_line_length": 53, "num_lines": 5, "path": "/config.ini", "repo_name": "Schattenkind/OGameBot", "src_encoding": "UTF-8", "text": "[Login]\nLOGIN_PAGE = http://de.ogame.gameforge.com/main/login\nSERVER = s152-de.ogame.gameforge.com\nUSER = USERNAME\nPASSWORD = PASSWORD\n" }, { "alpha_fraction": 0.6277397274971008, "alphanum_fraction": 0.6691780686378479, "avg_line_length": 38.4594612121582, "blob_id": "c7e43e07fc81aa49c0a7c93a3d2cf11c03cf53d0", "content_id": "d306ee954ae4f61c4ab5cd40efe1158d8d1570d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2920, "license_type": "no_license", "max_line_length": 133, "num_lines": 74, "path": "/constants.py", "repo_name": "Schattenkind/OGameBot", "src_encoding": "UTF-8", "text": "from configparser import ConfigParser\n\nconfig = ConfigParser()\n\n# parse existing file\nconfig.read('config.ini')\n\nSERVER = config.get('Login', 'SERVER')\nUSER = config.get('Login', 'USER')\nPASSWORD = config.get('Login', 'PASSWORD')\n__HTTP = 'http://'\n\n# urls\nLOGIN_PAGE = config.get('Login', 'LOGIN_PAGE')\nMAIN_PAGE = __HTTP + SERVER + '/game/index.php'\nOVERVIEW_PAGE = MAIN_PAGE + '?page=overview'\nRESOURCE_PAGE = MAIN_PAGE + '?page=resources'\nSTATION_PAGE = MAIN_PAGE + '?page=station'\nRESEARCH_PAGE = MAIN_PAGE + '?page=research'\nSHIPYARD_PAGE = MAIN_PAGE + '?page=shipyard'\nDEFENSE_PAGE = MAIN_PAGE + '?page=defense'\nFLEET_PAGE = MAIN_PAGE + '?page=fleet1'\nGALAXY_PAGE = MAIN_PAGE + '?page=galaxy'\n\n# building pages\nMETAL_MINE_URL = MAIN_PAGE + '?page=resources&ajax=1&type=1'\nCRYSTAL_MINE_URL = MAIN_PAGE + '?page=resources&ajax=1&type=2'\nDEUTERIUM_MINE_URL = MAIN_PAGE + '?page=resources&ajax=1&type=3'\nSOLAR_URL = MAIN_PAGE + '?page=resources&ajax=1&type=4'\nFUSION_URL = MAIN_PAGE + '?page=resources&ajax=1&type=12'\nMETAL_STORAGE_URL = MAIN_PAGE + '?page=resources&ajax=1&type=22'\nCRYSTAL_STORAGE_URL = MAIN_PAGE + '?page=resources&ajax=1&type=23'\nDEUTERIUM_STORAGE_URL = MAIN_PAGE + '?page=resources&ajax=1&type=24'\nHIDDEN_METAL_STORAGE_URL = MAIN_PAGE + '?page=resources&ajax=1&type=25'\nHIDDEN_CRYSTAL_STORAGE_URL = MAIN_PAGE + '?page=resources&ajax=1&type=26'\nHIDDEN_DEUTERIUM_STORAGE_URL = MAIN_PAGE + '?page=resources&ajax=1&type=27'\n\nROBOTICS = MAIN_PAGE + 'page=station&ajax=1&type=14'\nSHIPYARD = MAIN_PAGE + 'page=station&ajax=1&type=21'\nRESEARCH_LAB = MAIN_PAGE + 'page=station&ajax=1&type=31'\n\n# regex\n# resources\nFIND_RESOURCE_ACT_CAP_PROD = '.\"{name}\":.\"resources\":.\"actualFormat\":\"[0-9\\.]+\",\"actual\":[0-9]+,\"max\":[0-9]+,\"production\":[0-9\\.]+.'\nFIND_ENERGY = '\"energy\":.\"resources\":.\"actual\":.{0,1}[0-9]+,\"actualFormat\":\".{0,1}[0-9\\.]+\"'\n\n# buildings\nFIND_COST = '\"[\\w]+ tooltip\" title=\"[0-9\\.]+'\nFIND_LEVEL = '<span class=\"level\">.{1,20}[0-9]+.{1,20}<span class=\"'\nFIND_ENERGYCOST = '<span class=\"time\">.{0,30}[0-9\\.]+'\nFIND_DURATION = '<span class=\"time\" id=\"buildDuration\">.{1,20}[0-9\\.]*.{1,5}[0-9\\.]*.{1,5}[0-9\\.]*'\nFIND_BUILDING_LINK = 'sendBuildRequest.{0,300}, null, 1'\nFIND_ACTUAL_BUILDING_TIME = \"new bauCountdown.getElementByIdWithCache..'b_supply.{1,3}.'.,[0-9]*,[0-9]*\"\n\n# planets\nFIND_PLANET_IMAGE = '<div id=\"planet\" style=\"background.image.url.{0,300}\\)\">'\n\n# universe\nFIND_UNIVERSE_SPEED = '\"ogame-universe-speed\" content=\".\"'\nFIND_UNIVERSE_SPEED_FLEET = '\"ogame-universe-speed-fleet\" content=\".\"'\n\n# header dict\nHEADERS_DICT = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}\n\n# helper methodes\ndef return_int_if_exists(value, index):\n try:\n x = int(value[index])\n except IndexError:\n x = 0\n except TypeError:\n print('Could not convert value to int!')\n x = None\n return x\n" }, { "alpha_fraction": 0.5842645168304443, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 37.46491241455078, "blob_id": "dfad8d10715a0503cce047ed4d09b979f69b8c0e", "content_id": "5dbb8ef23dda6603eb64f7e7427d32a26f62da47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4385, "license_type": "no_license", "max_line_length": 178, "num_lines": 114, "path": "/buildings/building.py", "repo_name": "Schattenkind/OGameBot", "src_encoding": "UTF-8", "text": "import re\nimport logging\n\nfrom constants import FIND_COST, FIND_LEVEL, FIND_ENERGYCOST, FIND_DURATION, FIND_BUILDING_LINK, return_int_if_exists\n\n__all__ = ['Building', 'METAL_MINE', 'CRYSTAL_MINE', 'DEUTERIUM_MINE', 'SOLAR', 'FUSION', 'METAL_STORAGE',\n 'CRYSTAL_STORAGE', 'DEUTERIUM_STORAGE', 'HIDDEN_METAL_STORAGE', 'HIDDEN_CRYSTAL_STORAGE',\n 'HIDDEN_DEUTERIUM_STORAGE']\n\n# building name constants\nMETAL_MINE = 0\nCRYSTAL_MINE = 1\nDEUTERIUM_MINE = 2\nSOLAR = 3\nFUSION = 4\nMETAL_STORAGE = 5\nCRYSTAL_STORAGE = 6\nDEUTERIUM_STORAGE = 7\nHIDDEN_METAL_STORAGE = 8\nHIDDEN_CRYSTAL_STORAGE = 9\nHIDDEN_DEUTERIUM_STORAGE = 10\n\nlogger = logging.getLogger('ogame_bot.buildings.building')\n\n\nclass Building(object):\n def __init__(self, name, info_page, supply, energy_producer=False):\n self.__info_page = info_page\n self.logger = logger\n self.supply = supply\n # self.category = category # not used yet...\n self.name = name\n self.metal_cost = 0\n self.crystal_cost = 0\n self.deuterium_cost = 0\n self.level = 0\n self.__energy = 0\n self.building_time = 0\n self.upgrade_link = ''\n self.energy_producer = energy_producer\n self.refresh_info()\n\n def __str__(self):\n return \"Building {name}(metal_cost: {metal_cost}; crystal_cost: {crystal_cost}; deuterium_cost: {deuterium_cost}; level: {level}; building_time: {building_time})\".format(\n name=self.name, metal_cost=self.metal_cost, crystal_cost=self.crystal_cost,\n deuterium_cost=self.deuterium_cost, level=self.level, building_time=self.building_time)\n\n @property\n def energy(self):\n if self.energy_producer:\n return self.__energy\n else:\n return self.__energy * -1\n\n @energy.setter\n def energy(self, energy):\n self.__energy = energy\n\n def extract_cost_info(self):\n extract_resource_numbers = re.findall(FIND_COST, self.__info_page.content)\n numbers = []\n for number in extract_resource_numbers:\n numbers.append(re.findall('[0-9\\.]+', number)[0].replace('.', ''))\n return numbers\n\n def extract_level_info(self):\n extract_level = re.findall(FIND_LEVEL, self.__info_page.content)\n numbers = []\n for number in extract_level:\n numbers.append(re.findall('[0-9\\.]+', number)[0].replace('.', ''))\n return return_int_if_exists(numbers, 0)\n\n def extract_energy_info(self):\n extract_energy = re.findall(FIND_ENERGYCOST, self.__info_page.content)\n numbers = []\n for number in extract_energy:\n numbers.append(re.findall('[0-9\\.]+', number)[0].replace('.', ''))\n return return_int_if_exists(numbers, 0)\n\n def extract_building_time_info(self):\n extract_building_time = re.findall(FIND_DURATION, self.__info_page.content)\n build_time = 0\n for info in extract_building_time:\n i = re.findall('[0-9\\.]+.{1,3}[0-9\\.]*.{0,3}[0-9\\.]*.{0,3}', info)\n for a in i[0].split():\n if a.endswith('s'):\n build_time += int(a[:-1])\n elif a.endswith('m'):\n build_time += int(a[:-1]) * 60\n elif a.endswith('h'):\n build_time += int(a[:-1]) * 3600\n return build_time\n\n def get_current_upgrade_link(self, resource_page_content):\n pattern = self.supply + '.{0,1300}' + FIND_BUILDING_LINK\n self.logger.debug(\"Trying to find upgrade link with pattern \" + pattern)\n link = re.findall(pattern, resource_page_content)\n try:\n final_link = re.findall('https://.{1,150}', link[0])[0][:-11]\n except IndexError:\n final_link = None\n return final_link\n\n def refresh_info(self, refresh_page=True):\n if refresh_page:\n self.__info_page.refresh_content()\n cost = self.extract_cost_info()\n self.logger.debug(\"Found the following building costs for building \" + self.name + \": \" + str(cost))\n self.metal_cost = return_int_if_exists(cost, 0)\n self.crystal_cost = return_int_if_exists(cost, 1)\n self.deuterium_cost = return_int_if_exists(cost, 2)\n self.level = self.extract_level_info()\n self.energy = self.extract_energy_info()\n self.building_time = self.extract_building_time_info()\n" }, { "alpha_fraction": 0.5889621376991272, "alphanum_fraction": 0.59452223777771, "avg_line_length": 41.2260856628418, "blob_id": "b8c5349796ebd3855f4e68d0af27596b1843a49f", "content_id": "9972a373b38917e141108b3fc83b486ec71215b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4856, "license_type": "no_license", "max_line_length": 118, "num_lines": 115, "path": "/buildings/queue.py", "repo_name": "Schattenkind/OGameBot", "src_encoding": "UTF-8", "text": "from constants import *\nfrom info.resources import METAL, CRYSTAL, DEUTERIUM, ENERGY\n\nimport re\nimport time\nimport datetime\nimport threading\nimport logging\n\nlogger = logging.getLogger('ogame_bot.buildings.queue')\n\n\nclass BuildQueue(threading.Thread):\n def __init__(self, planet):\n threading.Thread.__init__(self, daemon=True)\n self.logger = logger\n self.planet = planet\n self.buildings_queue = []\n self.current_remaining_time = 0\n self.stop = False\n\n def add_to_queue(self, building):\n self.logger.info(\"Adding \" + building.name + \" to the building queue. (Planet ID \" + self.planet.id + \")\")\n self.buildings_queue.append(building)\n return True\n\n def upgrade_building(self, building):\n \"\"\"\n :param building : queue item to upgrade\n :return: 0 - building is successfully upgrading\n 1 - not enough materials\n 2 - other reason why it could not be upgraded (e.g. other building still being build)\n \"\"\"\n self.planet.refresh_info()\n if self.planet.resources[METAL].actual < building.metal_cost:\n self.logger.info(\"Not enough metal to upgrade! Waiting.. (Planet ID \" + self.planet.id + \")\")\n return 1\n if self.planet.resources[CRYSTAL].actual < building.crystal_cost:\n self.logger.info(\"Not enough crystal to upgrade! Waiting.. (Planet ID \" + self.planet.id + \")\")\n return 1\n if self.planet.resources[DEUTERIUM].actual < building.deuterium_cost:\n self.logger.info(\"Not enough deuterium to upgrade! Waiting.. (Planet ID \" + self.planet.id + \")\")\n return 1\n link = building.get_current_upgrade_link(self.planet.pages['resource'].content)\n if link:\n self.planet.resources[METAL].actual -= building.metal_cost\n self.planet.resources[CRYSTAL].actual -= building.crystal_cost\n self.planet.resources[DEUTERIUM].actual -= building.deuterium_cost\n self.logger.info(\n \"Starting upgrade of \" + building.name + \" with link \" + link + \" (Planet ID \" + self.planet.id + \")\")\n self.planet.session.get(link)\n self.logger.info(\"Required time: \" + str(datetime.timedelta(seconds=building.building_time)))\n return 0\n return 2\n\n def run(self):\n while not self.stop:\n self.find_current_constructing_building_info()\n if len(self.buildings_queue) > 0:\n building = self.buildings_queue[0]\n else:\n self.logger.debug(\"Queue is empty trying to fill it... (Planet \" + self.planet.id + \")\")\n self.planet.fill_queue()\n continue\n\n state = self.upgrade_building(building)\n if state == 0:\n self.current_remaining_time = building.building_time\n self.building()\n self.buildings_queue.pop(0)\n elif state == 1:\n self.logger.info(\"Waiting for enough materials! (Planet \" + self.planet.id + \")\")\n time.sleep(self.calc_time_till_upgrade_is_possible(building) + 3)\n else:\n self.logger.warning(\n \"Could not acquire upgrade link, waiting and retrying...(Planet \" + self.planet.id + \")\")\n time.sleep(3)\n\n def building(self):\n time.sleep(self.current_remaining_time + 1)\n\n def calc_time_till_upgrade_is_possible(self, building):\n return 5\n\n def find_current_constructing_building_info(self):\n \"\"\"\n # TODO this is used to find buildings which are already building but is buggy\n Refreshes the resource page, updates the building list if necessary.\n \"\"\"\n return\n\n def add_at_start_of_queue(numbers):\n supply = 'supply' + str(numbers[0])\n building = None\n for b in self.planet.buildings.keys():\n if self.planet.buildings[b].supply == supply:\n building = self.planet.buildings[b]\n self.buildings_queue.insert(0, self.add_to_queue(building))\n self.current_remaining_time = numbers[1]\n self.building()\n self.buildings_queue.pop(0)\n\n self.planet.pages['resource'].refresh_content()\n extract_resource_numbers = re.findall(FIND_ACTUAL_BUILDING_TIME, self.planet.pages['resource'].content)\n\n numbers = []\n for number in extract_resource_numbers:\n [numbers.append(int(num)) for num in re.findall('[0-9\\.]+', number)]\n\n if numbers:\n supply = 'supply' + str(numbers[0])\n if len(self.buildings_queue) == 0:\n add_at_start_of_queue(numbers)\n elif self.buildings_queue[0].building.supply != supply:\n add_at_start_of_queue(numbers)\n" } ]
8
tyeen/sublime-text2-settings
https://github.com/tyeen/sublime-text2-settings
d718540fe894cdc04676477a8026a36be10a657e
206076645f842df00abeeeec0d3ac4e7687e1aa7
0c8bfbb1631f62c9f73e1492f51c3b71de9c4561
refs/heads/master
2015-08-07T08:57:35.697916
2013-03-10T13:16:45
2013-03-10T13:16:45
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5624251961708069, "alphanum_fraction": 0.5673447847366333, "avg_line_length": 38.17708206176758, "blob_id": "90e829becb7083d727989499642ceae5ea5ac3c2", "content_id": "4f9c732b17fac60dc57de2f4efb593e59bf79bfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7521, "license_type": "no_license", "max_line_length": 107, "num_lines": 192, "path": "/Change List (Last Edit)/Change-List.py", "repo_name": "tyeen/sublime-text2-settings", "src_encoding": "UTF-8", "text": "import sublime, sublime_plugin\nimport os\n\n# G_REGISTER is placed in global so that\n# it will not be destoyed when reloading perferences\n\nif not 'G_REGISTER' in globals(): G_REGISTER = {}\n\nclass PosStorage():\n def __init__(self, view, saved_pos=[]):\n self.vid = view.id()\n self.saved_pos = saved_pos\n self.curr_idx = 0\n self.last_row = view.rowcol(view.sel()[0].end())[1]\n self.file_size = view.size()\n self.old_pos = map(lambda s: s.end(), view.sel())\n\nclass CommandManager():\n def GoToChange(self, view, i):\n vid = view.id()\n if i<0 or i>len(G_REGISTER[vid].saved_pos)-1: return\n G_REGISTER[vid].curr_idx = i\n pos = G_REGISTER[vid].saved_pos[i]\n view.sel().clear()\n view.show(pos)\n view.sel().add(pos)\n\n # to reactivate sublime_plugin.WindowCommand.on_selection_modified()\n # useful for plugin - SublimeBlockCursor\n if view.settings().get('command_mode'):\n view.run_command(\"enter_insert_mode\")\n view.run_command(\"exit_insert_mode\")\n else:\n view.run_command(\"move\", {\"by\": \"characters\", \"forward\" : False})\n view.run_command(\"move\", {\"by\": \"characters\", \"forward\" : True})\n\n sublime.status_message(\"@Change List [%s]\" % G_REGISTER[vid].curr_idx )\n\n\nclass JumpToChangeCommand(sublime_plugin.TextCommand, CommandManager):\n def run(self, _, **kwargs):\n view = self.view\n vid = view.id()\n if not G_REGISTER.has_key(vid): return\n if not G_REGISTER[vid].saved_pos: return\n # if the cursor has moved away from the recent edited location, set move = 0\n curr_pos = view.sel()[0].end()\n if not kwargs.has_key('index'):\n move = kwargs['move']\n if G_REGISTER[vid].curr_idx==0 and move==1:\n if abs(curr_pos - G_REGISTER[vid].saved_pos[0])>1: move = 0\n self.GoToChange(view, G_REGISTER[vid].curr_idx + move)\n else:\n self.GoToChange(view, kwargs['index'])\n\nclass ShowChangeList(sublime_plugin.WindowCommand, CommandManager):\n def run(self):\n view = self.window.active_view()\n vid = view.id()\n if not G_REGISTER.has_key(vid): return\n if not G_REGISTER[vid].saved_pos: return\n change_list = [ \"[%2d] Line %3d: %s\" % (i, view.rowcol(pos)[0]+1,\n view.substr(view.line(pos))) for i,pos in enumerate(G_REGISTER[vid].saved_pos)]\n self.window.show_quick_panel(change_list, self.on_done)\n\n def on_done(self, action):\n view = self.window.active_view()\n if action==-1: return\n self.GoToChange(view, action)\n\nclass ClearChangeList(sublime_plugin.WindowCommand, CommandManager):\n def run(self):\n self.view = self.window.active_view()\n try:\n fname = os.path.basename(self.view.file_name())\n except:\n fname = \"untitled\"\n self.window.show_quick_panel([fname, \"All files\"], self.on_done)\n\n def on_done(self, action):\n global G_REGISTER\n if action==0:\n vid = self.view.id()\n if G_REGISTER.has_key(vid): G_REGISTER.pop(vid)\n vname = self.view.file_name()\n settings = sublime.load_settings('%s.sublime-settings' % __name__)\n if vname and settings.has(vname): settings.erase(vname)\n sublime.save_settings('%s.sublime-settings' % __name__)\n sublime.status_message(\"Clear Change List (this file) successfully.\")\n elif action==1:\n G_REGISTER = {}\n path = os.path.join(sublime.packages_path(), \"User\" , '%s.sublime-settings' % __name__)\n if os.path.exists(path): os.remove(path)\n sublime.status_message(\"Clear Change List (all file) successfully.\")\n\n\nclass ChangeListener(sublime_plugin.EventListener):\n\n def insert_curr_pos(self, view, ):\n vid = view.id()\n G = G_REGISTER[vid]\n curr_pos = map(lambda s: s.end(), view.sel())\n curr_row = view.rowcol(curr_pos[0])[0]\n if G.saved_pos:\n if abs(curr_row - G.last_row)>1:\n G.saved_pos.insert(0,curr_pos[0])\n else:\n G.saved_pos[0] = curr_pos[0]\n if len(G.saved_pos)>50: G.saved_pos.pop()\n else:\n G.saved_pos = [curr_pos[0]]\n # update last_row\n G.last_row = curr_row\n\n def update_pos(self, view):\n vid = view.id()\n G = G_REGISTER[vid]\n if not G.saved_pos: return\n curr_pos = map(lambda s: s.end(), view.sel())\n old_pos = G.old_pos\n file_size = view.size()\n # probelms can be created if number of selections changes\n if len(curr_pos)==len(G.old_pos):\n deltas = map(lambda x,y: x-y, curr_pos, G.old_pos)\n deltas = [long(x - deltas[i-1]) for i,x in enumerate(deltas) if i>0]\n deltas = [long(file_size-G.file_size-sum(deltas))] + deltas\n\n for i in reversed(range(len(curr_pos))):\n # delete positions in previous selection\n delta = deltas[i]\n if delta<0:\n G.saved_pos = [pos for pos in G.saved_pos if pos<curr_pos[i] or pos>=curr_pos[i]-delta]\n\n # update positions\n if delta!=0 :\n G.saved_pos = [pos+delta if pos >= old_pos[i] else pos for pos in G.saved_pos]\n else:\n # if not, do the best to update position\n print \"Warnings from Change List: number of selections change\"\n delta = long(file_size-G.file_size)\n if delta!=0 :\n G.saved_pos = [pos+delta if pos >= curr_pos[0] else pos for pos in G.saved_pos]\n\n # update file size\n G.file_size = file_size\n # drop invalid positions\n G.saved_pos = [pos for pos in G.saved_pos if pos>=0 and pos<=file_size]\n\n def on_load(self, view):\n vid = view.id()\n vname = view.file_name()\n settings = sublime.load_settings('%s.sublime-settings' % __name__)\n if vname and settings.has(vname):\n try:\n saved_pos = [long(item) for item in settings.get(vname).split(\",\")]\n except:\n saved_pos = []\n else:\n saved_pos = []\n if not G_REGISTER.has_key(vid): G_REGISTER[vid] = PosStorage(view, saved_pos)\n\n def on_selection_modified(self, view):\n vid = view.id()\n if not G_REGISTER.has_key(vid): G_REGISTER[vid] = PosStorage(view)\n # get the current multi cursor locations\n G_REGISTER[vid].old_pos = map(lambda s: s.end(), view.sel())\n\n def on_modified(self, view):\n if view.is_scratch() or view.settings().get('is_widget'): return\n vid = view.id()\n if not G_REGISTER.has_key(vid): G_REGISTER[vid] = PosStorage(view)\n G = G_REGISTER[vid]\n # reset current index\n G.curr_idx = 0\n # update saved postions\n self.update_pos(view)\n # insert current position\n self.insert_curr_pos(view)\n # print G.saved_pos\n\n\n def on_post_save(self, view):\n vid = view.id()\n vname = view.file_name()\n if G_REGISTER.has_key(vid):\n settings = sublime.load_settings('%s.sublime-settings' % __name__)\n settings.set(vname, \",\".join(map(str, G_REGISTER[vid].saved_pos)))\n sublime.save_settings('%s.sublime-settings' % __name__)\n\n def on_close(self, view):\n vid = view.id()\n if G_REGISTER.has_key(vid): G_REGISTER.pop(vid)" }, { "alpha_fraction": 0.6126760840415955, "alphanum_fraction": 0.6267605423927307, "avg_line_length": 23.482759475708008, "blob_id": "0489ad5669a0ddbd5b30c956eb1e4a16b727fbc7", "content_id": "8a19d652af93270c679c32ce2118b8aa66d95c62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 710, "license_type": "no_license", "max_line_length": 131, "num_lines": 29, "path": "/README.md", "repo_name": "tyeen/sublime-text2-settings", "src_encoding": "UTF-8", "text": "# Sublime Text2 settings\n\n### <2013/01/20>\n\n* BracketHighlighter:<br>\n highlight the brackets, () [] {} \"\"...\n\n* Change List(Last Edit):<br>\n save the change list(position moved) of current file.<br>\n **I have changed the default key-mapping<br/>**\n **from:**\n \n \t\tprevious=\"super+;\"\n \t\tnext=\"super+,\"\n \tlast=\"super+.\"\n \n **to:**\n \t\n \tprevious=\"super+;\"\n next=\"super+'\" // changed!\n last=\"super+.\"\n \n Also avoids the default behaviors of the combination \"super+,\"(to open the preferences).\n\n* Theme-Nil:<br>\n Cool theme\n\n* User:<br>\n All my adjustments, including settings of BracketHighlighter, settings of Key-mapping, settings of environment of Sublime Text 2.\n" }, { "alpha_fraction": 0.7082639932632446, "alphanum_fraction": 0.7154741883277893, "avg_line_length": 41.92856979370117, "blob_id": "fb43a4e86e21625dc63386d328ca3ff7a8ef323a", "content_id": "1ae3b16d68bc9f27bafa69867f353bfab1ea32c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1803, "license_type": "no_license", "max_line_length": 96, "num_lines": 42, "path": "/Change List (Last Edit)/README.md", "repo_name": "tyeen/sublime-text2-settings", "src_encoding": "UTF-8", "text": "Change List (Last Edit) for Sublime Text 2\n====================\nIt remembers where changes were made.\n<img src=\"https://github.com/randy3k/Change-List/raw/master/changelist.png\">\n\nInstallation\n------------\nVia [Package Control](http://wbond.net/sublime_packages/package_control)\n\nIntroduction\n------------\n\nThis plugin aims at recovering the full functionality of change list of VIM.\n* Type ``Change List: Show`` in Command Palette to show Change List.\n* Type ``Change List: Clear`` in Command Palette to clear Change List.\n* Type ``super+;`` or ``g;`` (vintage command mode) to go to previous edited location\n* Type ``super+,`` or ``g,`` (vintage command mode) to go to next edited location\n* Type ``super+.`` or ``g.`` (vintage command mode) to go to the last edited location\n\nThere are already a few other \"Last Edit\" plugins . For examples:\n* https://github.com/SamPeng87/sublime-last-edit\n* https://github.com/khrizt/GotoLastEdit\n* https://github.com/abrookins/GotoLastEdit\n* https://github.com/Stuk/sublime-edit-history\n* https://github.com/optilude/SublimeTextMisc/blob/master/navigationHistory.py\n* https://gist.github.com/1993147\n\nHowever, they do not keep history after the file is saved and closed (as far as I can tell).<BR>\nThis plugin saves history to ``Packages/User/Change-List.sublime-settings``.<BR>\nFor the moment, the last 50 history for each file will be saved.<BR>\n\nNote: The cursor always stays in the same file.\n\nKeymap\n----------------------\nIt overwrites the default keymap ``super+,`` for consistency.<br>\n\nKnown issues\n-----------------------\n* Undo will update the change list. I have no idea on how to fix it at this moment.\n* Multi cursor support is now limited, only the location of the first cursor will be saved.\n However, most multi cursor editing preserves history.\n" } ]
3
GargAnshul008/Music-Recommendation-System
https://github.com/GargAnshul008/Music-Recommendation-System
b204b8c31a6cc197612e31abf0f1129461af03a2
530189d487326a37d530181a7d61bd1df27b238a
577362fee836ae19143e399aaa913a1728caf476
refs/heads/master
2021-05-23T15:50:32.264687
2020-04-06T01:34:23
2020-04-06T01:34:23
253,368,454
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5645677447319031, "alphanum_fraction": 0.5779082179069519, "avg_line_length": 35.03845977783203, "blob_id": "f9db8edb106f8b5077886b9c19c4f4eb74fa22c6", "content_id": "08a7f00da110ad3a9dcbe8dd58431de1b44b0658", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1874, "license_type": "no_license", "max_line_length": 180, "num_lines": 52, "path": "/trainer.py", "repo_name": "GargAnshul008/Music-Recommendation-System", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\n\nfrom pyspark.sql import SparkSession\nfrom pyspark.ml.recommendation import ALS\nfrom pyspark.ml.evaluation import RegressionEvaluator\n\ndef main(spark): \n\n train_data = spark.read.parquet('anshul_project/train_index.parquet')\n val_data = spark.read.parquet('anshul_project/val_index.parquet')\n train_data = train_data.cache()\n val_data = val_data.cache() \n \n train_data = train_data.sample(withReplacement=False, fraction=0.1, seed=1)\n\n ranks = [4, 8, 16]\n regs = [0, 0.1, 1, 10]\n alphas = [0.1, 0.5, 1.0]\n # ranks = [4]\n # regs = [1]\n # alphas = [0.5]\n\n best_rmse = sys.maxsize\n best_model = None\n for rank in ranks:\n for reg in regs:\n for alpha in alphas:\n als = ALS(maxIter=3, rank=rank, regParam=reg, alpha=alpha, userCol=\"user_num\", itemCol=\"track_num\", ratingCol=\"count\", implicitPrefs=True, coldStartStrategy=\"drop\")\n als_model = als.fit(train_data)\n \n predictions = als_model.transform(val_data)\n reg_evaluator = RegressionEvaluator(metricName=\"rmse\", labelCol=\"count\", predictionCol=\"prediction\")\n rmse = reg_evaluator.evaluate(predictions)\n \n if rmse < best_rmse:\n best_model = als_model\n best_rmse = rmse\n print('New best model')\n print('Rank: {}, Reg: {}, Alpha: {}'.format(rank, reg, alpha))\n stats = [rank, reg, alpha, rmse]\n \n best_model.save('anshul_project/als_sampling')\n print('Best model: Rank: {}, Reg: {}, Alpha: {}, RMSE: {}'.format(*stats))\n\n\n# Only enter this block if we're in main\nif __name__ == \"__main__\":\n spark = SparkSession.builder.appName('als_train').getOrCreate()\n main(spark)\n" }, { "alpha_fraction": 0.7117726802825928, "alphanum_fraction": 0.7131258249282837, "avg_line_length": 27.423076629638672, "blob_id": "3e27e22057f56c5147c9e49c447477128b9a96e3", "content_id": "56ef75e37ef82f992a66ee7575779c3053c039cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 739, "license_type": "no_license", "max_line_length": 104, "num_lines": 26, "path": "/tester.py", "repo_name": "GargAnshul008/Music-Recommendation-System", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\n\nfrom pyspark.ml.evaluation import RegressionEvaluator\nfrom pyspark.ml.recommendation import ALSModel\nfrom pyspark.sql import SparkSession\n\n\ndef main():\n spark = SparkSession.builder.appName('test').getOrCreate()\n als_model = ALSModel.load('anshul_project/als_sampling')\n \n test_data = spark.read.parquet('anshul_project/test_index.parquet')\n\n als_predictions = als_model.transform(test_data)\n\n reg_evaluator = RegressionEvaluator(metricName=\"rmse\", labelCol=\"count\", predictionCol=\"prediction\")\n rmse = reg_evaluator.evaluate(als_predictions)\n\n print(\"Test rmse \" + str(rmse))\n\n\n# Only enter this block if we're in main\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6964803338050842, "alphanum_fraction": 0.702277421951294, "avg_line_length": 41.3684196472168, "blob_id": "064fe7c7dfdfe7b37067e9f8a43054f0f9e8476b", "content_id": "1ac063b04dd4d73f583401a516b8027947c48ace", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2415, "license_type": "no_license", "max_line_length": 97, "num_lines": 57, "path": "/sampler.py", "repo_name": "GargAnshul008/Music-Recommendation-System", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\n\nfrom pyspark.sql import SparkSession\nfrom pyspark.ml.feature import StringIndexer\n\ndef main(spark):\n\n partitions = 1000\n\n train_data = spark.read.parquet('hdfs:/user/bm106/pub/project/cf_train.parquet')\n validation_data = spark.read.parquet('hdfs:/user/bm106/pub/project/cf_validation.parquet')\n test_data = spark.read.parquet('hdfs:/user/bm106/pub/project/cf_test.parquet')\n \n val_test_data = test_data.union(validation_data)\n train_optional_user = train_data.join(val_test_data, \"user_id\", \"left_anti\")\n train_data = train_data.join(train_optional_user, \"user_id\", \"left_anti\")\n \n uid_indexer = StringIndexer(inputCol=\"user_id\", outputCol=\"user_num\", handleInvalid=\"skip\")\n tid_indexer = StringIndexer(inputCol=\"track_id\", outputCol=\"track_num\", handleInvalid=\"skip\")\n model_uid = uid_indexer.fit(train_data)\n model_tid = tid_indexer.fit(train_data)\n\n uid_train_index = model_uid.transform(train_data)\n combo_train_index = model_tid.transform(uid_train_index)\n \n uid_val_index = model_uid.transform(validation_data)\n combo_val_index = model_tid.transform(uid_val_index)\n \n uid_test_index = model_uid.transform(test_data)\n combo_test_index = model_tid.transform(uid_test_index)\n \n model_uid.save('anshul_project/model_uid')\n model_tid.save('anshul_project/model_tid')\n\n combo_train_index = combo_train_index.repartition(partitions, \"user_id\")\n combo_val_index = combo_val_index.repartition(partitions, \"user_id\")\n combo_test_index = combo_test_index.repartition(partitions, \"user_id\")\n\n combo_train_index = combo_train_index.select([\"user_num\",\"count\",\"track_num\"])\n combo_train_index.write.parquet(path='anshul_project/train_index.parquet', mode='overwrite')\n combo_train_index.unpersist()\n\n combo_val_index = combo_val_index.select([\"user_num\",\"count\",\"track_num\"])\n combo_val_index.write.parquet(path='anshul_project/val_index.parquet', mode='overwrite')\n combo_val_index.unpersist()\n \n combo_test_index = combo_test_index.select([\"user_num\",\"count\",\"track_num\"])\n combo_test_index.write.parquet(path='anshul_project/test_index.parquet', mode='overwrite')\n combo_test_index.unpersist()\n\n\n# Only enter this block if we're in main\nif __name__ == \"__main__\":\n spark = SparkSession.builder.appName('sampler').getOrCreate()\n main(spark)\n" }, { "alpha_fraction": 0.7799280881881714, "alphanum_fraction": 0.7848946452140808, "avg_line_length": 66.06896209716797, "blob_id": "f751c560fe26d823ff4c73beb19dac2da8c5ced2", "content_id": "5c49091722a52646b6e0ead8acc9f1a36efcd061", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5839, "license_type": "no_license", "max_line_length": 456, "num_lines": 87, "path": "/README.md", "repo_name": "GargAnshul008/Music-Recommendation-System", "src_encoding": "UTF-8", "text": "\n\n# MUSIC RECOMMENDATION SYSTEM\n\n## Technologies Used\n* Sqlite3 \n* Python \n* MapReduce\n* Spark\n* PySpark\n* MLlib\n* Data Pipelining\n* Scala\n* Version Control\n\n## Overview\n\nIn the final project, you will apply the tools you have learned in this class to build and evaluate a recommender system. While the content of the final project involves recommender systems, it is intended more as an opportunity to integrate multiple techniques to solve a realistic, large-scale applied problem.\n\nFor this project, you are encouraged to work in groups of no more than 3 students.\n\nGroups of 1--2 will need to implement one extension (described below) over the baseline project for full credit.\n\nGroups of 3 will need to implement two extensions for full credit.\n\n## The data set\n\nOn Dumbo's HDFS, you will find the following files in `hdfs:/user/bm106/pub/project`:\n\n - `cf_train.parquet`\n - `cf_validation.parquet`\n - `cf_test.parquet`\n \n - `metadata.parquet`\n - `features.parquet`\n - `tags.parquet`\n - `lyrics.parquet`\n \n \nThe first three files contain training, validation, and testing data for the collaborative filter. Specifically, each file contains a table of triples `(user_id, count, track_id)` which measure implicit feedback derived from listening behavior. The first file `cf_train` contains full histories for approximately 1M users, and partial histories for 110,000 users, located at the end of the table.\n\n`cf_validation` contains the remainder of histories for 10K users, and should be used as validation data to tune your model.\n\n`cf_test` contains the remaining history for 100K users, which should be used for your final evaluation.\n\nThe four additional files consist of supplementary data for each track (item) in the dataset. You are not required to use any of these, but they may be helpful when implementing extensions to the baseline model.\n\n## Basic recommender system [80% of grade]\n\nYour recommendation model should use Spark's alternating least squares (ALS) method to learn latent factor representations for users and items. This model has some hyper-parameters that you should tune to optimize performance on the validation set, notably: \n\n - the *rank* (dimension) of the latent factors,\n - the *regularization* parameter, and\n - *alpha*, the scaling parameter for handling implicit feedback (count) data.\n\nThe choice of evaluation criteria for hyper-parameter tuning is entirely up to you, as is the range of hyper-parameters you consider, but be sure to document your choices in the final report.\n\nOnce your model is trained, evaluate it on the test set using the ranking metrics provided by spark. Evaluations should be based on predictions of the top 500 items for each user.\n\n\n### Hints\n\nYou may need to transform the user and item identifiers (strings) into numerical index representations for it to work properly with Spark's ALS model. You might save some time by doing this once and saving the results to new files in HDFS.\n\nStart small, and get the entire system working start-to-finish before investing time in hyper-parameter tuning!\n\nYou may consider downsampling the data to more rapidly prototype your model. If you do this, be careful that your downsampled data includes enough users from the validation set to test your model.\n\n\n\n## Extensions [20% of grade]\n\nFor full credit, implement an extension on top of the baseline collaborative filter model. (Again, if you're working in a group of 3 students, you must implement two extensions for full credit here.)\n\nThe choice of extension is up to you, but here are some ideas:\n\n - *Alternative model formualtions*: the `AlternatingLeastSquares` model in Spark implements a particular form of implicit-feedback modeling, but you could change its behavior by modifying the count data. Conduct a thorough evaluation of different modification strategies (e.g., log compression, or dropping low count values) and their impact on overall accuracy.\n - *Fast search*: use a spatial data structure (e.g., LSH or partition trees) to implement accelerated search at query time. For this, it is best to use an existing library such as `annoy` or `nmslib`, and you will need to export the model parameters from Spark to work in your chosen environment. For full credit, you should provide a thorough evaluation of the efficiency gains provided by your spatial data structure over a brute-force search method.\n - *Cold-start*: using the supplementary data, build a model that can map observable feature data to the learned latent factor representation for items. To evaluate its accuracy, simulate a cold-start scenario by holding out a subset of items during training (of the recommender model), and compare its performance to a full collaborative filter model.\n - *Error analysis*: after training the model, analyze the errors that it makes. Are certain types of item over- or under-represented? Make use of the supplementary metadata and tag information to inform your analysis.\n - *Exploration*: use the learned representation to develop a visualization of the items and users, e.g., using T-SNE or UMAP. The visualization should somehow integrate additional information (features, metadata, or tags) to illustrate how items are distributed in the learned space\n\n# What to turn in\n\nIn addition to all of your code, produce a final report (not to exceed 4 pages), describing your implementation, evaluation results, and extensions. Your report should clearly identify the contributions of each member of your group. If any additional software components were required in your project, your choices should be described and well motivated here. \n\nInclude a PDF copy of your report in the github repository along with your code submission.\n\nAny additional software components should be documented with installation instructions.\n\n\n" }, { "alpha_fraction": 0.6118160486221313, "alphanum_fraction": 0.623711347579956, "avg_line_length": 39.03174591064453, "blob_id": "680d53bbf0e11d45bc92f3110d0d8fd767ca7ab4", "content_id": "39cfe5af228068b15f9ffcd3f8b1128fe8d3819e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2522, "license_type": "no_license", "max_line_length": 199, "num_lines": 63, "path": "/log_extension.py", "repo_name": "GargAnshul008/Music-Recommendation-System", "src_encoding": "UTF-8", "text": "import sys\n\nfrom pyspark.sql import SparkSession\nfrom pyspark.ml.recommendation import ALS\nfrom pyspark.ml.feature import StringIndexer\nfrom pyspark.ml.evaluation import RegressionEvaluator\nfrom pyspark.ml import Pipeline\nfrom pyspark.sql.functions import log\n\n\n\ndef main(spark):\n train_data = spark.read.parquet('hdfs:/user/bm106/pub/project/cf_train.parquet')\n val_data = spark.read.parquet('hdfs:/user/bm106/pub/project/cf_validation.parquet')\n\n train_data.createOrReplaceTempView('train_data')\n\n train_data_log = train_data.withColumn(\"logcount\", log(train_data[\"count\"]))\n val_data_log = val_data.withColumn(\"logcount\", log(val_data[\"count\"]))\n uid_indexer = StringIndexer(inputCol=\"user_id\", outputCol=\"user_num\", handleInvalid =\"skip\")\n tid_indexer = StringIndexer(inputCol=\"track_id\", outputCol=\"track_num\", handleInvalid =\"skip\")\n\n ranks =[4]\n regs = [1]\n alphas = [0.5]\n \n best_rmse = None\n best_rank = None\n best_alpha = None\n best_reg = None\n\n for rank in ranks :\n for alpha in alphas :\n for reg in regs :\n\n als = ALS(maxIter = 3 , regParam= reg, userCol= \"user_num\" , itemCol= \"track_num\" , ratingCol =\"logcount\" , implicitPrefs=True , coldStartStrategy=\"drop\" , alpha= alpha , rank = rank)\n print('model created')\n pipeline = Pipeline(stages=[uid_indexer, tid_indexer, als])\n print('pipeline created')\n als_model = pipeline.fit(train_data_log)\n print('model fit')\n predictions = als_model.transform(val_data_log)\n print('predictions created')\n evaluator = RegressionEvaluator(metricName=\"rmse\", labelCol=\"count\", predictionCol=\"prediction\")\n print('evaluator created')\n rmse = evaluator.evaluate(predictions)\n print('evaluation ',rmse)\n if best_rmse is None or best_rmse > rmse :\n best_rmse = rmse\n best_rank = rank\n best_alpha = alpha\n best_reg = reg\n\n print('The best hyper parameters: Rank: {}, Reg: {}, Alpha: {}, RMSE: {}'.format(best_rank,best_reg,best_alpha,best_rmse))\n #The best hyper parameters: Rank: 4, Reg: 0.5, Alpha: 1, RMSE: 7.71668081677277 \n\n als_model.save('anshul_project/log_model')\n\nif __name__ == \"__main__\":\n\n # Create the spark session object\n spark = SparkSession.builder.appName('log_extension').getOrCreate()\n main(spark)\n" } ]
5
blackout314/myrecon.py
https://github.com/blackout314/myrecon.py
36b2bddedaf58640b78e46f220be8ed6a8cb9110
08971c8da250632187684716c67575e0dc3fd1a1
25230ac0ee232b72255efea0b75fd15bb6781490
refs/heads/master
2020-07-28T18:24:34.793096
2019-09-19T08:21:31
2019-09-19T08:21:31
209,492,577
0
1
null
2019-09-19T07:41:47
2019-09-19T07:40:20
2019-09-18T22:27:25
null
[ { "alpha_fraction": 0.5197640061378479, "alphanum_fraction": 0.533923327922821, "avg_line_length": 27.72881317138672, "blob_id": "27f54218ac9c648fbbeb230e10d211348a6cf272", "content_id": "fbe2c24f9d54ee66966b1f3e9481d8cacabd159d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1695, "license_type": "no_license", "max_line_length": 105, "num_lines": 59, "path": "/modules/resolve.py", "repo_name": "blackout314/myrecon.py", "src_encoding": "UTF-8", "text": "# I don't believe in license.\n# You can do whatever you want with this program.\n\nimport re\nimport sys\nimport subprocess\nfrom colored import fg, bg, attr\nfrom functools import partial\nfrom multiprocessing.dummy import Pool\n\n\nclass Resolve( object ):\n ips = []\n n_ips = 0\n dead_host = []\n n_dead = 0\n full_output = ''\n\n\n def run( self, t_hosts ):\n sys.stdout.write( '[+] running mod: resolve...\\n' )\n\n t_multiproc = {\n 'n_current': 0,\n 'n_total': len(t_hosts)\n }\n\n pool = Pool( 10 )\n pool.map( partial(self.resolve,t_multiproc), t_hosts )\n pool.close()\n pool.join()\n\n self.n_ips = len(self.ips)\n self.n_dead = len(self.dead_host)\n\n\n def resolve( self, t_multiproc, host ):\n sys.stdout.write( 'progress: %d/%d\\r' % (t_multiproc['n_current'],t_multiproc['n_total']) )\n t_multiproc['n_current'] = t_multiproc['n_current'] + 1\n\n try:\n cmd = 'host ' + host\n output = subprocess.check_output( cmd, stderr=subprocess.STDOUT, shell=True ).decode('utf-8')\n # print(output)\n # ip = socket.gethostbyname( host )\n except Exception as e:\n # sys.stdout.write( \"%s[-] error occurred: %s%s\\n\" % (fg('red'),e,attr(0)) )\n return\n\n self.full_output = self.full_output + output + \"\\n\"\n\n matches = re.findall( '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}', output )\n if matches:\n for ip in matches:\n if not ip in self.ips:\n self.ips.append( ip )\n else:\n if host not in sef.dead_host:\n self.dead_host.append( host )\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7285714149475098, "avg_line_length": 19, "blob_id": "01f39c10148dd3285aedfa169ba3f9d7e8750c7e", "content_id": "75873723f0604e9de95fd772805534aec6e74731", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 140, "license_type": "no_license", "max_line_length": 50, "num_lines": 7, "path": "/README.md", "repo_name": "blackout314/myrecon.py", "src_encoding": "UTF-8", "text": "# myrecon.py #\nMy recon script\n\n\n## requirements ##\n- `pip3 install -r requirements.txt`\n- findomain https://github.com/Edu4rdSHL/findomain\n" }, { "alpha_fraction": 0.6497005820274353, "alphanum_fraction": 0.651197612285614, "avg_line_length": 12.359999656677246, "blob_id": "84b44f70590c7f9bbd9702863f783cafb3e44f3a", "content_id": "5e11174d531bfbcd0a7af19e6d6aac1e445be40c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1336, "license_type": "no_license", "max_line_length": 81, "num_lines": 100, "path": "/myrecon.py", "repo_name": "blackout314/myrecon.py", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3.5\n\n# I don't believe in license.\n# You can do whatever you want with this program.\n\nt_available_mods = ['resolve', 'screenshot', 'quickhits', 'crlf', 'openredirect']\n\n\n#\n# init app\n#\nfrom modules import functions as func\nfrom modules.app import App\n\napp = App()\nfunc.parseargs( app, t_available_mods )\n#\n# ###\n#\n\n\n#\n# MOD: subdomains\n#\nfrom modules.subdomains import Subdomains\n\nmod = Subdomains()\nmod.run( app.domains )\n\nif not mod.n_hosts:\n exit()\n\napp.setHosts( mod.hosts )\n#\n# ###\n#\n\n\n#\n# MOD: resolve\n#\nif 'resolve' in app.mods:\n from modules.resolve import Resolve\n\n mod = Resolve()\n mod.run( app.hosts )\n\n app.setIps( mod.ips, mod.full_output )\n\n if mod.n_dead:\n app.setDeadHosts( mod.dead_host )\n#\n# ###\n#\n\n\n#\n# create urls used by other tools\n#\napp.createUrls()\n#\n# ###\n#\n\n\n#\n# optional modules\n#\nif 'screenshot' in app.mods:\n from modules import screenshot\n screenshot.run( app )\n\nif 'quickhits' in app.mods:\n from modules import quickhits\n quickhits.run( app )\n\nif 'crlf' in app.mods:\n from modules import crlf\n crlf.run( app )\n\nif 'openredirect' in app.mods:\n from modules import openredirect\n openredirect.run( app )\n#\n# ###\n#\n\n\n# app.wait()\n\n\n# next\n# cors\n# google dorks\n# new subdomains\n# endpoints\n# gf mykeys\n# gf noisy\n# gf takeovers\n# final report\n" }, { "alpha_fraction": 0.5154597163200378, "alphanum_fraction": 0.5162733793258667, "avg_line_length": 32.671234130859375, "blob_id": "7f892e01cc535495d04336d1df8894be8e84a153", "content_id": "2597615b2b6c5938ec38f146fe2c9a44b0545c0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2458, "license_type": "no_license", "max_line_length": 159, "num_lines": 73, "path": "/modules/functions.py", "repo_name": "blackout314/myrecon.py", "src_encoding": "UTF-8", "text": "# I don't believe in license.\n# You can do whatever you want with this program.\n\nimport os\nimport sys\nimport argparse\nimport tldextract\n\ndef parseargs( app, t_available_mods ):\n parser = argparse.ArgumentParser()\n parser.add_argument( \"-d\",\"--domain\",help=\"domain, single, multiples or files\", action=\"append\" )\n parser.add_argument( \"-o\",\"--output\",help=\"output dir\" )\n parser.add_argument( \"-m\",\"--mod\",help=\"mods to run, can be: resolve, screenshots, quickhits, crlf, openredirect. Default: resolve,screenshots,quickhits\" )\n parser.parse_args()\n args = parser.parse_args()\n\n if args.output:\n if os.path.isdir(args.output):\n output_dir = args.output\n else:\n try:\n os.makedirs( args.output )\n except Exception as e:\n sys.stdout.write( \"%s[-] error occurred: %s%s\\n\" % (fg('red'),e,attr(0)) )\n exit()\n app.setOutputDirectory( args.output )\n else:\n app.setOutputDirectory( os.getcwd() )\n\n if args.domain:\n t_domains = []\n for d in args.domain:\n if os.path.isfile(d):\n sys.stdout.write( '[+] loading file: %s\\n' % d )\n for l in open(d,'r'):\n l = l.strip()\n if isDomain(l) and l not in t_domains:\n t_domains.append( l )\n else:\n if isDomain( d ) and d not in t_domains:\n t_domains.append( d )\n if not len(t_domains):\n parser.error( 'domain missing' )\n else:\n parser.error( 'domain missing' )\n\n if args.mod:\n t_mods = []\n for m in args.mod.split(','):\n if not m in t_available_mods and m != 'all':\n parser.error( (\"mod '%s' doesn't exist\" % m) )\n # sys.stdout.write( \"%s[-] mod %s doesn't exist.%s\\n\" % (fg('red'),m,attr(0)) )\n else:\n if m == 'all':\n t_mods = t_available_mods\n break\n else:\n t_mods.append( m )\n if not len(t_mods):\n parser.error( 'mod missing' )\n else:\n t_mods = t_available_mods\n\n app.setDomains( t_domains )\n app.setMods( t_mods )\n\n\ndef isDomain( str ):\n t_parse = tldextract.extract( str )\n if t_parse.subdomain == '' and t_parse.domain != '' and t_parse.suffix != '':\n return True\n else:\n return False\n" }, { "alpha_fraction": 0.531410276889801, "alphanum_fraction": 0.5397436022758484, "avg_line_length": 29.58823585510254, "blob_id": "bcbe840ab992ce30b18e542c627fbce4c928f3ae", "content_id": "cbcaad6094e3d8c02a7bc725478f293191177df3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1560, "license_type": "no_license", "max_line_length": 105, "num_lines": 51, "path": "/modules/subdomains.py", "repo_name": "blackout314/myrecon.py", "src_encoding": "UTF-8", "text": "# I don't believe in license.\n# You can do whatever you want with this program.\n\nimport re\nimport sys\nimport subprocess\nfrom colored import fg, bg, attr\nfrom functools import partial\nfrom multiprocessing.dummy import Pool\n\n\nclass Subdomains( object ):\n hosts = []\n n_hosts = 0\n\n def run( self, t_domains ):\n sys.stdout.write( '[+] looking for subdomains...\\n' )\n\n t_multiproc = {\n 'n_current': 0,\n 'n_total': len(t_domains)\n }\n\n pool = Pool( 3 )\n pool.map( partial(self.find,t_multiproc), t_domains )\n pool.close()\n pool.join()\n\n self.n_hosts = len(self.hosts)\n\n\n def find( self, t_multiproc, domain ):\n sys.stdout.write( 'progress: %d/%d\\r' % (t_multiproc['n_current'],t_multiproc['n_total']) )\n t_multiproc['n_current'] = t_multiproc['n_current'] + 1\n\n try:\n # cmd = 'sublist3r -d ' + domain\n cmd = 'findomain -t ' + domain\n output = subprocess.check_output( cmd, stderr=subprocess.STDOUT, shell=True ).decode('utf-8')\n # print(output)\n except Exception as e:\n sys.stdout.write( \"%s[-] error occurred: %s%s\\n\" % (fg('red'),e,attr(0)) )\n return\n\n # matches = re.findall( '92m([a-zA-Z0-9\\._-]+\\.'+domain+')', output)\n matches = re.findall( '([a-zA-Z0-9\\._-]+\\.'+domain+')', output)\n if matches:\n for sub in matches:\n sub = sub.strip('._- ')\n if sub not in self.hosts:\n self.hosts.append( sub )\n" }, { "alpha_fraction": 0.4772019386291504, "alphanum_fraction": 0.4822996258735657, "avg_line_length": 25.75, "blob_id": "0ad49db9942f4c58ddea6b44e6313f1e9256ff27", "content_id": "083e6c4876879e25364839cda519aca618ac7071", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3531, "license_type": "no_license", "max_line_length": 97, "num_lines": 132, "path": "/modules/app.py", "repo_name": "blackout314/myrecon.py", "src_encoding": "UTF-8", "text": "# I don't believe in license.\n# You can do whatever you want with this program.\n\nimport os\nimport sys\nimport time\nfrom colored import fg, bg, attr\n\n\nclass App( object ):\n mods = []\n \n d_output = ''\n f_domains = ''\n f_hosts = ''\n f_tmphosts = ''\n f_dead = ''\n f_ips = ''\n f_urls = ''\n \n domains = []\n n_domains = 0\n \n hosts = []\n n_hosts = 0\n \n ips = []\n n_ips = 0\n \n dead = []\n n_dead = 0\n \n urls = []\n n_urls = 0\n\n\n def wait( self ):\n i = 0\n t_chars = ['|','/','-','\\\\','|','/','-']\n l = len(t_chars)\n\n sys.stdout.write( \"\\n\\n\" )\n\n for n in range(100000):\n time.sleep( 0.5 )\n sys.stdout.write( ' %s\\r' % t_chars[n%l] )\n\n\n def setMods( self, t_mods ):\n self.mods = t_mods\n\n\n def setOutputDirectory( self, cd_output ):\n self.d_output = cd_output\n sys.stdout.write( '[+] output directory is: %s\\n' % self.d_output )\n self.initFilePath()\n\n\n def initFilePath( self ):\n self.f_domains = self.d_output + '/domains'\n self.f_hosts = self.d_output + '/hosts'\n self.f_tmphosts = self.d_output + '/tmp_hosts'\n self.f_dead = self.d_output + '/dead'\n self.f_ips = self.d_output + '/ips'\n self.f_urls = self.d_output + '/urls'\n\n\n def setDomains( self, t_domains ):\n self.domains = t_domains\n self.n_domains = len(t_domains)\n sys.stdout.write( '%s[+] %d domains found.%s\\n' % (fg('green'),self.n_domains,attr(0)) )\n\n if self.n_domains:\n fp = open( self.f_domains, 'w' )\n fp.write( \"\\n\".join(self.domains) )\n fp.close()\n sys.stdout.write( '[+] saved in %s\\n' % self.f_domains )\n\n\n def setHosts( self, t_hosts ):\n self.hosts = t_hosts\n self.n_hosts = len(t_hosts)\n sys.stdout.write( '%s[+] %d hosts found.%s\\n' % (fg('green'),self.n_hosts,attr(0)) )\n\n if self.n_hosts:\n fp = open( self.f_hosts, 'w' )\n fp.write( \"\\n\".join(self.hosts) )\n fp.close()\n sys.stdout.write( '[+] saved in %s\\n' % self.f_hosts )\n\n\n def setIps( self, t_ips, full_output ):\n self.ips = t_ips\n self.n_ips = len(t_ips)\n sys.stdout.write( '%s[+] %d ips found.%s\\n' % (fg('green'),self.n_ips,attr(0)) )\n\n if self.n_ips:\n fp = open( self.f_ips, 'w' )\n fp.write( \"\\n\".join(t_ips) )\n fp.close()\n sys.stdout.write( '[+] saved in %s\\n' % self.f_ips )\n\n fp = open( self.f_tmphosts, 'w' )\n fp.write( full_output )\n fp.close()\n\n\n def setDeadHosts( self, t_dead ):\n sys.stdout.write( '[+] %d dead hosts found, cleaning...\\n' % len(t_dead) )\n\n for host in t_dead:\n self.hosts.remove( host )\n\n\n def createUrls( self ):\n sys.stdout.write( '[+] creating urls...\\n' )\n\n for host in self.hosts:\n self.urls.append( 'http://'+host )\n self.urls.append( 'https://'+host )\n for ip in self.ips:\n self.urls.append( 'http://'+ip )\n self.urls.append( 'https://'+ip )\n\n self.n_urls = len( self.urls )\n sys.stdout.write( '%s[+] %d urls created.%s\\n' % (fg('green'),self.n_urls,attr(0)) )\n\n if self.urls:\n fp = open( self.f_urls, 'w' )\n fp.write( \"\\n\".join(self.urls) )\n fp.close()\n sys.stdout.write( '[+] saved in %s\\n' % self.f_urls )\n" }, { "alpha_fraction": 0.6009615659713745, "alphanum_fraction": 0.6057692170143127, "avg_line_length": 31.736841201782227, "blob_id": "f6b760f5b173fc20a9c311b830ee1455ea8ab101", "content_id": "29331ae3a07d6dd069a994b9f118d291fdb02b14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 624, "license_type": "no_license", "max_line_length": 99, "num_lines": 19, "path": "/modules/openredirect.py", "repo_name": "blackout314/myrecon.py", "src_encoding": "UTF-8", "text": "# I don't believe in license.\n# You can do whatever you want with this program.\n\nimport os\nimport sys\nimport subprocess\nfrom colored import fg, bg, attr\n\n\ndef run( app ):\n sys.stdout.write( '[+] running mod: openredirect\\n' )\n cmd = 'open-redirect.py -o ' + app.f_hosts + ' 2>&1 >/dev/null &'\n os.system( cmd )\n # try:\n # cmd = 'open-redirect.py -o ' + app.f_hosts\n # # print(cmd)\n # r = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )\n # except Exception as e:\n # sys.stdout.write( \"%s[-] error occurred: %s%s\\n\" % (fg('red'),e,attr(0)) )\n\n\n" }, { "alpha_fraction": 0.5918079018592834, "alphanum_fraction": 0.6285310983657837, "avg_line_length": 38.33333206176758, "blob_id": "517716884c178246f578a4687937bd8c31940fa0", "content_id": "d1a159fefe6e44722d96d2f8ee67312417371471", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 708, "license_type": "no_license", "max_line_length": 210, "num_lines": 18, "path": "/modules/screenshot.py", "repo_name": "blackout314/myrecon.py", "src_encoding": "UTF-8", "text": "# I don't believe in license.\n# You can do whatever you want with this program.\n\nimport os\nimport sys\nimport subprocess\nfrom colored import fg, bg, attr\n\n\ndef run( app ):\n sys.stdout.write( '[+] running mod: screenshots\\n' )\n cmd = 'EyeWitness --headless -f \"' + app.f_urls + '\" --user-agent \"Mozilla/5.0 (X11; Linux i586; rv:63.0) Gecko/20100101 Firefox/63.0\" --no-prompt --threads 10 -d ' + app.d_output + '/eye 2>&1 >/dev/null &'\n os.system( cmd )\n # try:\n # # print(cmd)\n # subprocess.Popen( cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL )\n # except Exception as e:\n # sys.stdout.write( \"%s[-] error occurred: %s%s\\n\" % (fg('red'),e,attr(0)) )\n" } ]
8
thewayiam/crawler_tutorial
https://github.com/thewayiam/crawler_tutorial
94cf400a2463d15dece14d8e8edd0dd65ef37d77
ad5756e67eab04fa75d6c2deab11aacdcfde466f
b6538f51157eda9cb2b321f7ad1a8371e4ac2735
refs/heads/master
2020-05-20T21:56:54.473766
2017-03-11T06:53:36
2017-03-11T06:53:36
84,532,966
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6523125767707825, "alphanum_fraction": 0.660287082195282, "avg_line_length": 35.882354736328125, "blob_id": "6a1e86cf612f09fe2fab307246b408e1e3abb4bd", "content_id": "fb28b6b9e14ab229a58fa13bfb22b6b8ad21da71", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 627, "license_type": "permissive", "max_line_length": 81, "num_lines": 17, "path": "/examples/1_3/parser.py", "repo_name": "thewayiam/crawler_tutorial", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom scrapy.selector import Selector\n\n\nresponse = Selector(text=open('example.html').read())\np_tags = response.xpath('//p[string-length(text()) > 0]')\nfor p_tag in p_tags:\n p_text = p_tag.xpath('normalize-space(string())').extract_first()\n table_tag = p_tag.xpath('following-sibling::table[1]')\n print(p_text, table_tag)\n\ntable_tags = response.xpath('//table')\nfor table_tag in table_tags:\n p_tag = table_tag.xpath('preceding-sibling::p[string-length(text()) > 0][1]')\n p_text = p_tag.xpath('normalize-space(string())').extract_first()\n print(p_text, table_tag)\n" }, { "alpha_fraction": 0.6027649641036987, "alphanum_fraction": 0.6082949042320251, "avg_line_length": 39.185184478759766, "blob_id": "23494a42eae1f2a96509cc3793aee8034c234583", "content_id": "829da7ec92f4d558173a5525eb813161ae707843", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1115, "license_type": "permissive", "max_line_length": 77, "num_lines": 27, "path": "/examples/1_4/parser.py", "repo_name": "thewayiam/crawler_tutorial", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\nimport re\nfrom scrapy.selector import Selector\n\n\nresponse = Selector(text=open('example.html').read())\ntitles = response.xpath(u'//p[re:test(., \"公\\s*職\\s*人\\s*員.*表$\")]')\nfor title in titles:\n title_text = title.xpath('normalize-space(string())').extract_first()\n first_table = title.xpath('following-sibling::table[1]')\n print(title_text, first_table)\n p_tags = title.xpath('following::p[string-length(text()) > 0]')\n for p_tag in p_tags:\n p_text = p_tag.xpath('normalize-space(string())').extract_first()\n table_tag = p_tag.xpath('following-sibling::table[1]')\n if re.search(u'公\\s*職\\s*人\\s*員.*表$', p_text):\n break\n print(p_text, table_tag)\n\n table_tags = title.xpath('following-sibling::table')\n for table_tag in table_tags:\n p_tag = table_tag.xpath('preceding::p[string-length(text()) > 0][1]')\n p_text = p_tag.xpath('normalize-space(string())').extract_first()\n if re.search(u'公\\s*職\\s*人\\s*員.*表$', p_text):\n break\n print(p_text, table_tag)\n" } ]
2
engwaqar36/wordcount
https://github.com/engwaqar36/wordcount
bbde9131a3e7acc8f9b9f44eb7e7e527d23bbf14
f7afc24759cca669c072a0c8c1f7e47077ba834a
f7c23ff903bad3f46ec18acd4c985cf0ec7c273c
refs/heads/master
2020-04-20T15:35:34.886951
2019-02-03T10:47:21
2019-02-03T10:47:21
168,935,231
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.669767439365387, "alphanum_fraction": 0.6790697574615479, "avg_line_length": 32.11538314819336, "blob_id": "9eb6f0eb948a37ead3f7559c4188d5e39ad1c05c", "content_id": "95cd2c769322390ff3296ad9634b7a9782c885ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 860, "license_type": "no_license", "max_line_length": 106, "num_lines": 26, "path": "/wordcount/views.py", "repo_name": "engwaqar36/wordcount", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse\nfrom django.shortcuts import render\nimport operator\n\ndef homepage(request):\n return render(request,'home.html',{'name':'This is waqar'})\n\ndef contact(request):\n return HttpResponse(\"<h1>Contact page</h1><br> This is our contact page\")\n\ndef homepage1(request):\n return HttpResponse(\"<h1>This is homepage</h1>\")\n\ndef count(request):\n data = request.GET['fulltextarea']\n word_list = data.split()\n list_length= len(word_list)\n worddictionary ={}\n for word in word_list:\n if word in worddictionary:\n worddictionary[word] +=1\n else:\n worddictionary[word]=1\n \n worddictionary =sorted(worddictionary.items(), key= operator.itemgetter(1), reverse=True)\n return render(request,'count.html', {'fulltext':data, \"words\":list_length, \"word_dic\":worddictionary})" } ]
1
blackdie100/Propine
https://github.com/blackdie100/Propine
e595c792a93bf11b35b3daca36f93460b65bb224
dddcbc7d3e700c6f3b13c98c4c6ab8966ed38f7b
0758241ec88941e7a5dcb5faa8da41163997c528
refs/heads/master
2020-11-24T16:16:52.745383
2019-12-15T20:03:40
2019-12-15T20:03:40
228,239,522
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6059190034866333, "alphanum_fraction": 0.6137071847915649, "avg_line_length": 27.46666717529297, "blob_id": "c72e56f9c5eab77846c7b8d318f495ca3d1a3a8c", "content_id": "07bceff38d272302702be57f77e81ccfb2f2d256", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1284, "license_type": "no_license", "max_line_length": 93, "num_lines": 45, "path": "/HomeworkImplement.py", "repo_name": "blackdie100/Propine", "src_encoding": "UTF-8", "text": "import time\nimport HomeworkClass as HomeworkImplement\n\n## Environment Setting ## \n#############################################################################################\n### Choose Platform ###\nCheckPlatform = HomeworkImplement.Platform();\nCheckPlatform.setup_method_Chrome();\n\n### Get Website URL ###\nNickTest = HomeworkImplement.TestList(CheckPlatform);\nNickTest.get_site()\n\n\n## Test Item ## \n#############################################################################################\n### Test 1 ~ 10 units with one random number ###\n# NickTest.ImputNumberRandom_FirstElement()\n# NickTest.teardown_method()\n\n### Test 1 ~ 10 units with two random number ###\nNickTest.InputNumberRandom_TwoElement()\nNickTest.teardown_method()\n\n### Input English / Chinese Character ###\n# NickTest.InputCharacter()\n# NickTest.teardown_method()\n\n### Open and Close app ###\n# i = 1\n# while i < 10: \n# \tNickTest.teardown_method()\n# \tCheckPlatform = HomeworkImplement.Platform();\n# \tCheckPlatform.setup_method_Chrome();\n# \tNickTest = HomeworkImplement.TestList(CheckPlatform);\n# \tNickTest.get_site()\n# \ti = i + 1\n\n### Test Load Performance ###\n# NickTest.Load_Performance()\n# NickTest.teardown_method()\n\n### Test Press Propine Marker Link ###\n# NickTest.PressLink()\n# NickTest.teardown_method()\n\n\n\n" }, { "alpha_fraction": 0.595295250415802, "alphanum_fraction": 0.6116178631782532, "avg_line_length": 32.5, "blob_id": "6d4dfafe17e389d58b0386abdb703a9dfdece685", "content_id": "1c191e2cb0f2da25eadd071309f19eb55da335ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4166, "license_type": "no_license", "max_line_length": 105, "num_lines": 124, "path": "/HomeworkClass.py", "repo_name": "blackdie100/Propine", "src_encoding": "UTF-8", "text": "import pytest\nimport time\nimport json\nimport random \nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\n\nclass Platform():\n def setup_method_Chrome(self):\n self.driver = webdriver.Chrome()\n self.vars = {}\n\n def setup_method_Safari(self):\n self.driver = webdriver.Safari()\n self.vars = {}\n\n def setup_method_Firefox(self):\n self.driver = webdriver.Firefox()\n self.vars = {}\n\n def setup_method_Ie(self):\n self.driver = webdriver.Ie()\n self.vars = {}\n \n\nclass TestList(Platform):\n def __init__(self, class_a):\n self.driver = class_a.driver\n\n def teardown_method(self):\n time.sleep(3)\n self.driver.quit()\n\n def get_site(self):\n self.driver.get(\"https://vast-dawn-73245.herokuapp.com/\")\n self.driver.set_window_size(1212, 777)\n \n def InputNumberRandom_FirstElement(self):\n i = 2\n while i <= 10:\n j = 1\n while j <= 10:\n self.driver.find_element(By.NAME, \"firstNumber\").click()\n self.driver.find_element(By.NAME, \"firstNumber\").send_keys(int(random.random()*10**i))\n self.driver.find_element(By.NAME, \"secondNumber\").click()\n self.driver.find_element(By.NAME, \"secondNumber\").send_keys(\"1\")\n self.driver.find_element(By.CSS_SELECTOR, \".btn\").click()\n \n result = int(self.driver.find_element_by_xpath('/html/body/div[2]/div/div[2]/div').text)\n print result\n\n time.sleep(1)\n j = j + 1\n i = i + 1\n\n\n def InputNumberRandom_TwoElement(self):\n i = 2\n while i <= 10:\n j = 1\n while j <= 10:\n self.driver.find_element(By.NAME, \"firstNumber\").click()\n self.driver.find_element(By.NAME, \"firstNumber\").send_keys(int(random.random()*10**i))\n self.driver.find_element(By.NAME, \"secondNumber\").click()\n self.driver.find_element(By.NAME, \"secondNumber\").send_keys(int(random.random()*10**i))\n self.driver.find_element(By.CSS_SELECTOR, \".btn\").click()\n \n result = int(self.driver.find_element_by_xpath('/html/body/div[2]/div/div[2]/div').text)\n print result\n\n time.sleep(1)\n j = j + 1\n i = i + 1\n\n\n def InputCharacter(self):\n i = 2 ; k = 0\n while i <= 10:\n j = 1 ; Word = [\"Hello\", \"ChineseWord\" , \"JapaneseWord\" , \"#\"]\n while j <= 10:\n self.driver.find_element(By.NAME, \"firstNumber\").click()\n self.driver.find_element(By.NAME, \"firstNumber\").send_keys(int(random.random()*10**i))\n self.driver.find_element(By.NAME, \"secondNumber\").click()\n self.driver.find_element(By.NAME, \"secondNumber\").send_keys(Word[k])\n self.driver.find_element(By.CSS_SELECTOR, \".btn\").click()\n \n result = str(self.driver.find_element_by_xpath('/html/body/div[2]/div/div[2]/div').text)\n print result\n\n time.sleep(1)\n j = j + 1\n\n if i > 2 :\n k = 1\n elif i > 4 :\n k = 2\n elif i > 6 :\n k = 3\n\n i = i + 1\n\n\n def Load_Performance(self):\n navigationStart = int(self.driver.execute_script(\"return window.performance.timing.navigationStart\"))\n responseStart = int(self.driver.execute_script(\"return window.performance.timing.responseStart\"))\n domComplete = int(self.driver.execute_script(\"return window.performance.timing.domComplete\"))\n \n backendPerformance_calc = responseStart - navigationStart\n frontendPerformance_calc = domComplete - responseStart\n \n print(\"Back End: %s ms\" % backendPerformance_calc)\n print(\"Front End: %s ms\" % frontendPerformance_calc)\n\n\n def PressLink(self):\n i = 1\n while i < 100: \n self.driver.find_element(By.XPATH, \"/html/body/div[1]/div/a/img\").click()\n i = i + 1\n\n\n\n\n\n\n\n\n\n\n\n\n" } ]
2
PaulaJorgensen/sqlalchemy-challenge
https://github.com/PaulaJorgensen/sqlalchemy-challenge
5290057b8b8fcd3097b9e9bda7b1a1dc975c12b6
b194e8e45cd8a943720d50836b7adf19ad3c20b0
5c1cea06a57373224c09f0f8ebc03cfdc16e2ef8
refs/heads/master
2020-09-11T09:39:26.922891
2019-11-24T00:10:26
2019-11-24T00:10:26
222,024,519
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6237424612045288, "alphanum_fraction": 0.6441146731376648, "avg_line_length": 30.0625, "blob_id": "5d2c5b151d7b16f230ab8f1a7a64c307f5eea728", "content_id": "3cb5814ce35272fadc57a541a2b7006463cc1e92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3976, "license_type": "no_license", "max_line_length": 120, "num_lines": 128, "path": "/climate_flask.py", "repo_name": "PaulaJorgensen/sqlalchemy-challenge", "src_encoding": "UTF-8", "text": "import datetime as dt\nimport numpy as np\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\nfrom flask import Flask, jsonify\n\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\") \nBase = automap_base()\nBase.prepare(engine, reflect=True)\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\nsession = Session(engine)\n\napp = Flask(__name__)\n\[email protected](\"/\")\ndef Welcome():\n return (\n f\"Data Range is from 8/23/2016 thru 8/23/2017.<br><br>\"\n f\"Available Routes: <br>\"\n f\"/api/v1.0/precipitation<br/>\"\n f\"Returns percipitation data for the data range.<br><br>\"\n f\"/api/v1.0/stations<br/>\"\n f\"Returns data on all the weather stations in Hawaii. <br><br>\"\n f\"/api/v1.0/tobs<br/>\"\n f\"Returns temperature data for the most active weather station (USC00519281).<br><br>\"\n f\"/api/v1.0/<date>date<br/>\"\n f\"Returns an Average, Max, and Min temperature for a given start date. <br><br>\"\n f\"/api/v1.0/<startdate>startdate/<enddate>enddate<br/>\"\n f\"Returns an Average, Max, and Min temperatures for a given date range.\"\n )\n \[email protected](\"/api/v1.0/precipitation\")\ndef precipitation():\n session = Session(engine)\n curr_year=dt.date(2017, 8, 23)\n prev_year = curr_year - dt.timedelta(days=365)\n \n prcp=session.query(Measurement.date, func.sum(Measurement.prcp)).\\\n filter(Measurement.prcp != None).filter(Measurement.date>=prev_year).\\\n group_by(Measurement.date).all()\n session.close()\n\n prcp_data = []\n for d,p in prcp:\n prcp_dict = {}\n prcp_dict[\"date\"] = d\n prcp_dict[\"prcp\"] = p\n prcp_data.append(prcp_dict)\n return jsonify(prcp_data)\n \[email protected](\"/api/v1.0/stations\")\ndef stations():\n session = Session(engine)\n \"\"\"Return a list of stations.\"\"\"\n results = session.query(Station.station, Station.name, Station.elevation, Station.latitude, Station.longitude).all()\n \n session.close()\n \n station_list = []\n for result in results:\n row = {}\n row['station'] = result[0]\n row['name'] = result[1]\n row['elevation'] = result[2]\n row['latitude'] = result[3]\n row['longitude'] = result[4]\n station_list.append(row)\n return jsonify(station_list)\n\[email protected](\"/api/v1.0/tobs\")\ndef tobs():\n session = Session(engine)\n\n curr_year=dt.date(2017, 8, 23)\n prev_year = curr_year - dt.timedelta(days=365)\n \n temps = session.query(Measurement.tobs).\\\n filter(Measurement.station == 'USC00519281').\\\n filter(Measurement.date >= prev_year).all()\n\n session.close()\n \n temp_list = list(np.ravel(temps))\n return jsonify(temp_list)\n\[email protected](\"/api/v1.0/<date>\")\ndef date(date):\n session = Session(engine)\n\n results=session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date>=date).all()\n\n session.close()\n \n date_temp=list(np.ravel(results))\n\n t_min=date_temp[0]\n t_avg=date_temp[1]\n t_max=date_temp[2]\n t_dict = {'Minimum Temperature': t_min, 'Average Temperature': t_avg, 'Maximum Temperature': t_max}\n return jsonify(t_dict)\n\[email protected](\"/api/v1.0/<startdate>/<enddate>\")\ndef start_end_date(startdate,enddate):\n session=Session(engine)\n print(startdate)\n\n results=session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date>=startdate).\\\n filter(Measurement.date<=enddate).all()\n\n session.close()\n print(jsonify(results))\n date_temp=list(np.ravel(results))\n\n t_min=date_temp[0]\n t_avg=date_temp[1]\n t_max=date_temp[2]\n t_dict = {'Minimum Temperature': t_min, 'Average Temperature': t_avg, 'Maximum Temperature': t_max}\n return jsonify(t_dict)\n\nif __name__ == '__main__':\n app.run(debug=True)\n" } ]
1
oscar2sun/CyptoCurrency-Valuation
https://github.com/oscar2sun/CyptoCurrency-Valuation
270dbd1e75ee7e5a86085537534bab55623aa165
44ec6ead90a4b10f85e9ad61326a449b5c1ff53a
a53d32d365266e92aea6855943eabcf21b3af3e2
refs/heads/master
2020-03-07T06:00:04.925358
2018-03-29T15:37:08
2018-03-29T15:37:08
127,310,730
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6235818266868591, "alphanum_fraction": 0.7034035921096802, "avg_line_length": 39.86440658569336, "blob_id": "72cb45f28b3bd70b7174d4713979fdedd17244bc", "content_id": "a859e4ea3633ca6ce4b36ea8cd7437b0863f7290", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2468, "license_type": "no_license", "max_line_length": 120, "num_lines": 59, "path": "/Donwload Data.py", "repo_name": "oscar2sun/CyptoCurrency-Valuation", "src_encoding": "UTF-8", "text": "import pandas as pd\r\nimport time\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport datetime\r\nimport numpy as np\r\nfrom random import randint\r\n\r\n\r\ndef load_price_from_coinmarketcap(coin, start, end):\r\n bitcoin_market_info = \\\r\n pd.read_html(\"https://coinmarketcap.com/currencies/\" + coin + \"/historical-data/?start=\" + start + \"&end=\" + end)[0]\r\n # convert the date string to the correct date format\r\n bitcoin_market_info = bitcoin_market_info.assign(Date=pd.to_datetime(bitcoin_market_info['Date']))\r\n # when Volume is equal to '-' convert it to 0\r\n # bitcoin_market_info.loc[bitcoin_market_info['Volume'] == \"-\", 'Volume'] = 0\r\n # convert to int\r\n bitcoin_market_info['Volume'] = bitcoin_market_info['Volume'].astype('int64')\r\n # look at the first few rows\r\n return bitcoin_market_info\r\n\r\n\r\naion = load_price_from_coinmarketcap(\"aion\", \"20171018\", \"20180324\")\r\neth = load_price_from_coinmarketcap(\"ethereum\", \"20150807\", \"20180324\")\r\neos = load_price_from_coinmarketcap(\"eos\", \"20170701\", \"20180324\")\r\n\r\nwriter = pd.ExcelWriter('AION Project.xlsx', engine='xlsxwriter')\r\naion.to_excel(writer, sheet_name=\"aion\")\r\neth.to_excel(writer, sheet_name=\"eth\")\r\neos.to_excel(writer, sheet_name=\"eos\")\r\nwriter.save()\r\n\r\n# Competing Projects\r\nbtc = load_price_from_coinmarketcap(\"bitcoin\", \"20140501\", \"20180324\")\r\nlsk = load_price_from_coinmarketcap(\"lisk\", \"20160406\", \"20180324\")\r\nwaves = load_price_from_coinmarketcap(\"waves\", \"20160602\", \"20180324\")\r\nstrat = load_price_from_coinmarketcap(\"stratis\", \"20160811\", \"20180324\")\r\nneo = load_price_from_coinmarketcap(\"neo\", \"20160908\", \"20180324\")\r\ngnt = load_price_from_coinmarketcap(\"golem-network-tokens\", \"20161118\", \"20180324\")\r\nkmd = load_price_from_coinmarketcap(\"komodo\", \"20170205\", \"20180324\")\r\nark = load_price_from_coinmarketcap(\"ark\", \"20170523\", \"20180324\")\r\nqtum = load_price_from_coinmarketcap(\"qtum\", \"20170524\", \"20180324\")\r\n\r\n\r\nwriter = pd.ExcelWriter('Competing Projects.xlsx', engine='xlsxwriter')\r\nlsk.to_excel(writer, sheet_name=\"lsk\")\r\nwaves.to_excel(writer, sheet_name=\"waves\")\r\nstrat.to_excel(writer, sheet_name=\"strat\")\r\nneo.to_excel(writer, sheet_name=\"neo\")\r\ngnt.to_excel(writer, sheet_name=\"gnt\")\r\nkmd.to_excel(writer, sheet_name=\"kmd\")\r\nark.to_excel(writer, sheet_name=\"ark\")\r\nqtum.to_excel(writer, sheet_name=\"qtum\")\r\n\r\nwriter.save()\r\n\r\nwriter = pd.ExcelWriter('BTC Price.xlsx', engine='xlsxwriter')\r\nbtc.to_excel(writer, sheet_name=\"btc\")\r\nwriter.save()" }, { "alpha_fraction": 0.5291456580162048, "alphanum_fraction": 0.6234193444252014, "avg_line_length": 33.25, "blob_id": "0d74a3e9f82eec07e9031fcacde1d3d5191849f5", "content_id": "73557b9517549a5d57a3e492e0cb202c59c45384", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9727, "license_type": "no_license", "max_line_length": 126, "num_lines": 276, "path": "/AION.py", "repo_name": "oscar2sun/CyptoCurrency-Valuation", "src_encoding": "UTF-8", "text": "import pandas as pd\r\nimport time\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport datetime\r\nimport numpy as np\r\nfrom random import randint\r\n\r\n\r\n# GBM model\r\n\r\n# Predefined Functions\r\ndef load_price_from_coinmarketcap(coin, start, end):\r\n bitcoin_market_info = \\\r\n pd.read_html(\"https://coinmarketcap.com/currencies/\" + coin + \"/historical-data/?start=\" + start + \"&end=\" + end)[0]\r\n # convert the date string to the correct date format\r\n bitcoin_market_info = bitcoin_market_info.assign(Date=pd.to_datetime(bitcoin_market_info['Date']))\r\n # when Volume is equal to '-' convert it to 0\r\n # bitcoin_market_info.loc[bitcoin_market_info['Volume'] == \"-\", 'Volume'] = 0\r\n # convert to int\r\n bitcoin_market_info['Volume'] = bitcoin_market_info['Volume'].astype('int64')\r\n # look at the first few rows\r\n return bitcoin_market_info\r\n\r\n\r\ndef daily_return(adj_close):\r\n returns = []\r\n for i in range(0, len(adj_close) - 1):\r\n today = adj_close[i ]\r\n yesterday = adj_close[i + 1]\r\n daily_return = (today - yesterday) / yesterday\r\n returns.append(daily_return)\r\n return returns\r\n\r\n\r\ndef Brownian(seed, N, T):\r\n np.random.seed(seed)\r\n dt = T / N # time step\r\n b = np.random.normal(0., T, int(N)) * np.sqrt(dt) # brownian increments\r\n W = np.cumsum(b) # brownian path\r\n return W, b\r\n\r\n\r\ndef GBM(So, mu, sigma, W, T, N):\r\n t = np.linspace(0., T, N + 1)\r\n S = []\r\n S.append(So)\r\n for i in range(1, int(N + 1)):\r\n drift = (mu - 0.5 * sigma ** 2) * t[i]\r\n diffusion = sigma * W[i - 1]\r\n S_temp = So * np.exp(drift + diffusion)\r\n S.append(S_temp)\r\n return S, t\r\n\r\n\r\ndef MJD(So, mu, sigma, T, N, labda, nu, delta) -> object:\r\n S = []\r\n S.append(So)\r\n t = T/N\r\n for i in range(1, int(N+1)):\r\n P=np.random.poisson(labda*t)\r\n U=np.exp(P*nu+np.sqrt(P)*delta*np.random.normal(0,1))\r\n S_temp=S[i-1]*np.exp((mu-labda*(np.exp(nu+0.5*delta**2)-1)-0.5*sigma**2)*t + sigma*np.sqrt(t)*np.random.normal(0,1))*U\r\n S.append(S_temp)\r\n return S\r\n\r\n\r\n# Calibrate Mu and Sigma\r\naion = load_price_from_coinmarketcap(\"aion\", \"20171018\", \"20180324\")\r\n\r\nwriter = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')\r\naion.to_excel(writer, sheet_name=\"Sheet1\")\r\nwriter.save()\r\n\r\n\r\nadj_close = aion['Close']\r\ntime = np.linspace(1, len(adj_close), len(adj_close))\r\n\r\nreturns = daily_return(adj_close)\r\n\r\nmu = np.mean(returns) * 365. # drift coefficient\r\nsig = np.std(returns) * np.sqrt(365.) # diffusion coefficient\r\nprint(mu, sig)\r\n\r\n# GBM Exact Solution\r\nM=1000\r\nseed = pd.Series(range(1,M+1))\r\n\r\n\r\nSo = 2.86 # Initial AION coin price (03/05/2018)\r\nT = 1\r\nN = 365.\r\ntimes = pd.date_range('2018-03-25',periods= T*N+1, freq='D')\r\nW = Brownian(0, N, T)[0]\r\n# result = pd.DataFrame(GBM(So, mu, sig, W, T, N)[0])\r\nresult = pd.DataFrame()\r\nfor i in range(M):\r\n W = Brownian(seed[i], N, T)[0]\r\n soln = pd.Series(GBM(So, mu, sig, W, T, N)[0]) # Exact solution\r\n result = result.append(soln,ignore_index=True)\r\nresult = result.transpose()\r\nresult.index = times\r\nprint(result)\r\nq05 = result.quantile(0.05,axis=1)\r\nq15 = result.quantile(0.15,axis=1)\r\nq25 = result.quantile(0.25,axis=1)\r\nq35 = result.quantile(0.35,axis=1)\r\nq45 = result.quantile(0.45,axis=1)\r\nq55 = result.quantile(0.55,axis=1)\r\nq65 = result.quantile(0.65,axis=1)\r\nq75 = result.quantile(0.75,axis=1)\r\nq85 = result.quantile(0.85,axis=1)\r\nq95 = result.quantile(0.95,axis=1)\r\nsmean = result.mean(axis=1)\r\nStats = pd.DataFrame([smean,q05,q15,q25,q35,q45,q55,q65,q75,q85,q95])\r\nStats = Stats.transpose()\r\nStats.columns = [\"mean\",\"q05\",\"q15\",\"q25\",\"q35\",\"q45\",\"q55\",\"q65\",\"q75\",\"q85\",\"q95\"]\r\n\r\n\r\n\r\n# Function\r\ndef GBM_simulate(coin, hist_start, hist_end, S0, Date, M):\r\n # Calibrate Mu and Sigma\r\n coin_price = load_price_from_coinmarketcap(coin, hist_start, hist_end)\r\n adj_close = coin_price['Close']\r\n time = np.linspace(1, len(adj_close), len(adj_close))\r\n plt.plot(time, adj_close)\r\n\r\n returns = daily_return(adj_close)\r\n\r\n mu = np.mean(returns) * 365. # drift coefficient\r\n sig = np.std(returns) * np.sqrt(365.) # diffusion coefficient\r\n print(mu, sig)\r\n\r\n # GBM Exact Solution\r\n seed = pd.Series(range(1, M + 1))\r\n\r\n T = 1\r\n N = 365.\r\n times = pd.date_range(Date, periods=T * N + 1, freq='D')\r\n result = pd.DataFrame()\r\n for i in range(M):\r\n W = Brownian(seed[i], N, T)[0]\r\n soln = pd.Series(GBM(S0, mu, sig, W, T, N)[0]) # Exact solution\r\n result = result.append(soln, ignore_index=True)\r\n result = result.transpose()\r\n result.index = times\r\n print(result)\r\n q05 = result.quantile(0.05, axis=1)\r\n q15 = result.quantile(0.15, axis=1)\r\n q25 = result.quantile(0.25, axis=1)\r\n q35 = result.quantile(0.35, axis=1)\r\n q45 = result.quantile(0.45, axis=1)\r\n q55 = result.quantile(0.55, axis=1)\r\n q65 = result.quantile(0.65, axis=1)\r\n q75 = result.quantile(0.75, axis=1)\r\n q85 = result.quantile(0.85, axis=1)\r\n q95 = result.quantile(0.95, axis=1)\r\n smean = result.mean(axis=1)\r\n Stats = pd.DataFrame([smean, q05, q15, q25, q35, q45, q55, q65, q75, q85, q95])\r\n Stats = Stats.transpose()\r\n Stats.columns = [\"mean\", \"q05\", \"q15\", \"q25\", \"q35\", \"q45\", \"q55\", \"q65\", \"q75\", \"q85\", \"q95\"]\r\n return Stats\r\n\r\n\r\ndef GBM_simulate2(mu,sig, S0, Date, M):\r\n # Calibrate Mu and Sigma\r\n # GBM Exact Solution\r\n seed = pd.Series(range(1, M + 1))\r\n\r\n T = 1\r\n N = 365.\r\n times = pd.date_range(Date, periods=T * N + 1, freq='D')\r\n result = pd.DataFrame()\r\n for i in range(M):\r\n W = Brownian(seed[i], N, T)[0]\r\n soln = pd.Series(GBM(S0, mu, sig, W, T, N)[0]) # Exact solution\r\n result = result.append(soln, ignore_index=True)\r\n result = result.transpose()\r\n result.index = times\r\n print(result)\r\n q05 = result.quantile(0.05, axis=1)\r\n q15 = result.quantile(0.15, axis=1)\r\n q25 = result.quantile(0.25, axis=1)\r\n q35 = result.quantile(0.35, axis=1)\r\n q45 = result.quantile(0.45, axis=1)\r\n q55 = result.quantile(0.55, axis=1)\r\n q65 = result.quantile(0.65, axis=1)\r\n q75 = result.quantile(0.75, axis=1)\r\n q85 = result.quantile(0.85, axis=1)\r\n q95 = result.quantile(0.95, axis=1)\r\n smean = result.mean(axis=1)\r\n Stats = pd.DataFrame([smean, q05, q15, q25, q35, q45, q55, q65, q75, q85, q95])\r\n Stats = Stats.transpose()\r\n Stats.columns = [\"mean\", \"q05\", \"q15\", \"q25\", \"q35\", \"q45\", \"q55\", \"q65\", \"q75\", \"q85\", \"q95\"]\r\n return Stats\r\n\r\ndef MJD_simulate(mu,sig, S0, Date, labda, nu, delta, M):\r\n # Calibrate Mu and Sigma\r\n # GBM Exact Solution\r\n\r\n T = 2\r\n N = 730.\r\n times = pd.date_range(Date, periods=N + 1, freq='D')\r\n result = pd.DataFrame()\r\n for i in range(M):\r\n soln = pd.Series(MJD(S0, mu, sig, T, N, labda, nu, delta)) # Exact solution\r\n result = result.append(soln, ignore_index=True)\r\n result = result.transpose()\r\n result.index = times\r\n print(result)\r\n q05 = result.quantile(0.05, axis=1)\r\n q15 = result.quantile(0.15, axis=1)\r\n q25 = result.quantile(0.25, axis=1)\r\n q35 = result.quantile(0.35, axis=1)\r\n q45 = result.quantile(0.45, axis=1)\r\n q55 = result.quantile(0.55, axis=1)\r\n q65 = result.quantile(0.65, axis=1)\r\n q75 = result.quantile(0.75, axis=1)\r\n q85 = result.quantile(0.85, axis=1)\r\n q95 = result.quantile(0.95, axis=1)\r\n smean = result.mean(axis=1)\r\n Stats = pd.DataFrame([smean, q05, q15, q25, q35, q45, q55, q65, q75, q85, q95])\r\n Stats = Stats.transpose()\r\n Stats.columns = [\"mean\", \"q05\", \"q15\", \"q25\", \"q35\", \"q45\", \"q55\", \"q65\", \"q75\", \"q85\", \"q95\"]\r\n return Stats\r\n\r\n\r\n\r\nStats1 = MJD_simulate(mu=0.01458,sig=2.5849,S0=0.5,Date=\"20170814\",labda=6.412509,nu=-0.12849,delta=0.032184,M=10000)\r\nStats2 = MJD_simulate(mu=0.5,sig=2.5849,S0=0.5,Date=\"20170814\",labda=6.412509,nu=-0.12849,delta=0.032184,M=10000)\r\nStats3 = MJD_simulate(mu=1,sig=2.5849,S0=0.5,Date=\"20170814\",labda=6.412509,nu=-0.12849,delta=0.032184,M=10000)\r\nStats4 = MJD_simulate(mu=2,sig=2.5849,S0=0.5,Date=\"20170814\",labda=6.412509,nu=-0.12849,delta=0.032184,M=10000)\r\nStats5 = MJD_simulate(mu=5.390198,sig=2.5849,S0=0.5,Date=\"20170814\",labda=6.412509,nu=-0.12849,delta=0.032184,M=10000)\r\nStats6 = MJD_simulate(mu=3.549762,sig=3.438839,S0=5.19,Date=\"20180101\",labda=6.412509,nu=-0.12849,delta=0.032184,M=10000)\r\n\r\nwriter = pd.ExcelWriter('AION Project Result4.xlsx', engine='xlsxwriter')\r\nStats1.to_excel(writer, sheet_name=\"scenario1\")\r\nStats2.to_excel(writer, sheet_name=\"scenario2\")\r\nStats3.to_excel(writer, sheet_name=\"scenario3\")\r\nStats4.to_excel(writer, sheet_name=\"scenario4\")\r\nStats5.to_excel(writer, sheet_name=\"scenario5\")\r\nwriter.save()\r\n\r\nwriter = pd.ExcelWriter('AION Project Result6.xlsx', engine='xlsxwriter')\r\nStats6.to_excel(writer, sheet_name=\"scenario6\")\r\nwriter.save()\r\n\r\n\r\n\r\nscenario3 = GBM_simulate2(mu=5.390198, sig=2.584968, S0=0.5, Date='2018-08-14', M=10000)\r\nscenario4 =\r\nwriter = pd.ExcelWriter('AION Project Result3.xlsx', engine='xlsxwriter')\r\nStats1.to_excel(writer, sheet_name=\"scenario1\")\r\nStats2.to_excel(writer, sheet_name=\"scenario2\")\r\nwriter.save()\r\n\r\nwriter = pd.ExcelWriter('AION Project Result3.1.xlsx', engine='xlsxwriter')\r\nStats3.to_excel(writer, sheet_name=\"scenario1\")\r\nwriter.save()\r\n\r\n\r\nresult = MJD(So=0.5, mu=5.390198, sigma=2.5849, T=2, N=730, labda=6.412509, nu=0.12849, delta=0.032184)\r\nresults = pd.DataFrame(result)\r\n\r\n\r\nwriter = pd.ExcelWriter('temp_obs.xlsx', engine='xlsxwriter')\r\nresults.to_excel(writer, sheet_name=\"scenario1\")\r\nwriter.save()\r\n\r\n\r\n\r\nTT = pd.date_range(\"20170814\", periods=731, freq='D')\r\ntime = np.linspace(1, len(result), len(result))\r\n\r\nplt.plot(time,result)" }, { "alpha_fraction": 0.8633093237876892, "alphanum_fraction": 0.8633093237876892, "avg_line_length": 45.33333206176758, "blob_id": "7b907f682d3c99022f6a189fe9254a5149911ed4", "content_id": "96983fcc87582b46f794e685b273cdf21325cc36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 139, "license_type": "no_license", "max_line_length": 59, "num_lines": 3, "path": "/README.md", "repo_name": "oscar2sun/CyptoCurrency-Valuation", "src_encoding": "UTF-8", "text": "# CyptoCurrency-Valuation\nUsing Valuation Model to predict CyptoCurrency Pirce\nUsing Jump Difussion Model to predicet CryptoCurrency Price\n" } ]
3
frake17/SSP_project
https://github.com/frake17/SSP_project
e9e373834e16e021775069b4f9fbcc35a47e2f59
f77ae45c54b580f64b46a7fe59b54d4aebfe664c
78afc8203f18eef3b0107f8b0dc674ae61e3e3b4
refs/heads/main
2023-06-10T16:27:39.544307
2021-07-01T04:04:33
2021-07-01T04:04:33
371,261,515
0
3
null
2021-05-27T05:52:01
2021-07-01T02:42:03
2021-07-01T04:04:33
Python
[ { "alpha_fraction": 0.46282723546028137, "alphanum_fraction": 0.4691099524497986, "avg_line_length": 22.899999618530273, "blob_id": "f070de3e8348def7f6084f3d2d892b117d6ffb80", "content_id": "bc495e79063a94394772647c7512f00ffba2f2bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 955, "license_type": "no_license", "max_line_length": 60, "num_lines": 40, "path": "/templates/storeLocator(customer).html", "repo_name": "frake17/SSP_project", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n{% block title %}Library Loan System - Profile{% endblock %}\n\n{% block content %}\n\n<h1 class=\"display-4\">Store Locator</h1>\n\n<div>\n {% if count == 0 %}\n <p>There are no locations.</p>\n {% elif count == 1 %}\n <p>There is 1 location.</p>\n {% else %}\n <p>There are {{ count }} locations.</p>\n {% endif %}\n</div>\n\n<div>\n <table class=\"table table-striped\">\n <thead>\n <tr>\n <th>Neighbourhood</th>\n <th>Address</th>\n <th>Area</th>\n <th>Availability</th>\n </tr>\n </thead>\n <tbody>\n {% for location in locations_list %}\n <tr>\n <td>{{ location.get_neighbourhood() }}</td>\n <td>{{ location.get_address() }}</td>\n <td>{{ location.get_area() }}</td>\n <td>{{ location.get_availability() }}</td>\n </tr>\n {% endfor %}\n </tbody>\n </table>\n</div>\n{% endblock %}" }, { "alpha_fraction": 0.5719202756881714, "alphanum_fraction": 0.5736967921257019, "avg_line_length": 34.61178970336914, "blob_id": "a6719aa3345342c926ab32e1f8ae6563778a64d3", "content_id": "29f7a3842240bcd52a29701ac41bacd269fc84e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18013, "license_type": "no_license", "max_line_length": 135, "num_lines": 492, "path": "/elly.py", "repo_name": "frake17/SSP_project", "src_encoding": "UTF-8", "text": "import shelve\r\n\r\nfrom flask import Flask, render_template, request, redirect, url_for, session, flash, Blueprint\r\n\r\nimport Location\r\nimport User\r\nfrom Forms import SignUp, Login, CreateLocation, UpdateProfile, UpdatePassword\r\nfrom Forms import SignUp, Login, CreateLocation, UpdateProfile, UpdatePassword, optional_signup, recaptcha_form\r\n# SSP CODES\r\nfrom flask_mysqldb import MySQL\r\nimport MySQLdb.cursors\r\nfrom flask_recaptcha import ReCaptcha\r\nimport requests\r\nimport json\r\nfrom flask_mail import Mail, Message\r\nfrom random import randint\r\nfrom datetime import datetime, timedelta\r\n\r\nelly = Flask(__name__)\r\nelly.secret_key = 'any_random_string'\r\nelly.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\r\nelly.config[\"SESSION_PERMANENT\"] = False\r\n\r\n\r\n# SSP CODES\r\nelly.config['MAIL_SERVER'] = 'smtp.gmail.com'\r\nelly.config['MAIL_PORT'] = 465\r\nelly.config['MAIL_USERNAME'] = '[email protected]'\r\nelly.config['MAIL_PASSWORD'] = 'SSP123456'\r\nelly.config['MAIL_USE_TLS'] = False\r\nelly.config['MAIL_USE_SSL'] = True\r\nelly.config['MYSQL_HOST'] = 'localhost'\r\nelly.config['MYSQL_USER'] = 'root'\r\nelly.config['MYSQL_PASSWORD'] = '100carbook'\r\nelly.config['MYSQL_DB'] = 'pythonlogin'\r\nrecaptcha = ReCaptcha(app=elly)\r\nmysql = MySQL(elly)\r\nmail = Mail(elly)\r\nelly = Blueprint('elly', __name__, template_folder='templates', static_folder='static')\r\n\r\[email protected]('/loginActivity(cust)')\r\ndef loginActivity():\r\n return render_template('loginActivity(cust).html')\r\n\r\n\r\[email protected]('/loginActivity(cust)')\r\ndef loginActivity():\r\n return render_template('loginActivity(cust).html')\r\n\r\n\r\[email protected]('/signup', methods=['GET', 'POST'])\r\ndef signup():\r\n signup_form = SignUp(request.form)\r\n if request.method == 'POST' and signup_form.validate():\r\n optional_form = optional_signup(request.form)\r\n recaptcha_forms = recaptcha_form(request.form)\r\n msg = ''\r\n print(signup_form.validate())\r\n if request.method == 'POST' and signup_form.validate() and optional_form.validate():\r\n\r\n users_dict = {}\r\n db = shelve.open('storage.db', 'c')\r\n\r\n users_list = []\r\n for key in users_dict:\r\n user = users_dict.get(key)\r\n if key == signup_form.email.data:\r\n flash(\"Account already exist\")\r\n return redirect(url_for('home'))\r\n\r\n try:\r\n users_dict = db['Users']\r\n except:\r\n print(\"Error in retrieving Users from storage.db.\")\r\n\r\n user = User.User(signup_form.first_name.data, signup_form.last_name.data, signup_form.email.data,\r\n signup_form.password.data)\r\n print(\"===user====\", user)\r\n users_dict[user.get_email()] = user\r\n db['Users'] = users_dict\r\n\r\n # Test codes\r\n users_dict = db['Users']\r\n\r\n user = users_dict[user.get_email()]\r\n print(user.get_first_name(), user.get_last_name(), \"was stored in storage.db successfully with user_id ==\",\r\n user.get_user_id())\r\n\r\n db.close()\r\n\r\n session['user_created'] = user.get_first_name() + ' ' + user.get_last_name()\r\n\r\n # MySQL SSP Codes\r\n r = requests.post('https://www.google.com/recaptcha/api/siteverify',\r\n data={'secret':\r\n '6Lf15hYbAAAAAMq2XaVag56w4fFCNmSo9WkgxOBh',\r\n 'response':\r\n request.form['g-recaptcha-response']})\r\n\r\n google_response = json.loads(r.text)\r\n print('JSON: ', google_response)\r\n\r\n if google_response['success']:\r\n\r\n if optional_form.Phone_number.data != '':\r\n phone_num = optional_form.Phone_number.data\r\n else:\r\n phone_num = 'NULL'\r\n\r\n if optional_form.card_number.data != '':\r\n card_num = optional_form.card_number.data\r\n else:\r\n card_num = 'NULL'\r\n\r\n if optional_form.exp_date.data != '':\r\n exp_date = optional_form.exp_date.data\r\n else:\r\n exp_date = 'NULL'\r\n\r\n if optional_form.CVV.data != '':\r\n CVV = optional_form.CVV.data\r\n else:\r\n CVV = 'NULL'\r\n\r\n current_time = datetime.now()\r\n conformation_code = randint(000000, 999999)\r\n first_name = signup_form.first_name.data\r\n last_name = signup_form.last_name.data\r\n email = signup_form.email.data\r\n password = signup_form.password.data\r\n security_qn = signup_form.security_question.data\r\n security_ans = signup_form.security_answer.data\r\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\r\n cursor.execute('INSERT INTO customers_temp VALUES (NULL, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',\r\n (first_name, last_name, email, password, phone_num, card_num, exp_date, CVV, security_qn, security_ans))\r\n mysql.connection.commit()\r\n session['fname'] = first_name\r\n session['lname'] = last_name\r\n session['EMAIL'] = email\r\n msg = Message('Hello', sender='smtp.gmail.com', recipients=[email])\r\n msg.body = \"Conformation code is: %d\" % conformation_code\r\n mail.send(msg)\r\n\r\n return redirect(url_for('elly.signup_confirmation', conformation_code=conformation_code, date = current_time))\r\n\r\n return render_template('signup(customer).html', form=signup_form, optional_form=optional_form, recap = recaptcha_forms)\r\n\r\n\r\[email protected]('/signup_confirmation/<conformation_code>', methods=['GET', 'POST']) # SSP CODE\r\ndef signup_confirmation(conformation_code, date):\r\n time_change = timedelta(minutes=15)\r\n Changed_time = date + time_change\r\n first_name = session['fname']\r\n last_name = session['lname']\r\n if request.method == 'POST':\r\n code = request.form['confirmation']\r\n if int(code) == int(conformation_code):\r\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\r\n cursor.execute('INSERT INTO customers SELECT * FROM customers_temp WHERE fname = %s and lname = %s'\r\n , (first_name, last_name))\r\n cursor.execute('DELETE FROM customers_temp WHERE fname = %s and lname = %s', (first_name, last_name))\r\n mysql.connection.commit()\r\n return redirect(url_for('elly.account_created'))\r\n elif datetime.now() < Changed_time:\r\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\r\n cursor.execute('DELETE FROM customers_temp WHERE fname = %s and lname = %s', (first_name, last_name))\r\n mysql.connection.commit()\r\n return redirect(url_for('elly.signup'))\r\n else:\r\n return redirect(url_for('elly.signup_confirmation', conformation_code=conformation_code))\r\n return render_template('Signup_confirmation.html')\r\n\r\n\r\[email protected]('/resend', methods=['POST', 'GET'])\r\ndef resend():\r\n current_time = datetime.now()\r\n email = session.get('EMAIL')\r\n conformation_code = randint(000000, 999999)\r\n msg = Message('Hello', sender='smtp.gmail.com', recipients=[email])\r\n msg.body = \"Conformation code is: %d\" % conformation_code\r\n mail.send(msg)\r\n\r\n return redirect(url_for('elly.signup_confirmation', conformation_code=conformation_code, date=current_time))\r\n\r\n\r\[email protected]('/Account_created', methods=['GET', 'POST'])\r\ndef account_created():\r\n if request.method == 'POST':\r\n return redirect(url_for('home'))\r\n return render_template('Account_created.html')\r\n\r\n\r\[email protected]('/retrieveUsers')\r\ndef retrieve_users():\r\n users_dict = {}\r\n db = shelve.open('storage.db', 'r')\r\n try:\r\n users_dict = db['Users']\r\n except:\r\n print('no users')\r\n db.close()\r\n\r\n users_list = []\r\n for key in users_dict:\r\n user = users_dict.get(key)\r\n users_list.append(user)\r\n\r\n return render_template('retrieveUsers(admin).html', count=len(users_list), users_list=users_list)\r\n\r\n\r\[email protected]('/deleteUser/<email>', methods=['POST'])\r\ndef delete_user(email):\r\n users_dict = {}\r\n db = shelve.open('storage.db', 'w')\r\n users_dict = db['Users']\r\n\r\n users_dict.pop(email)\r\n\r\n db['Users'] = users_dict\r\n db.close()\r\n\r\n return redirect(url_for('elly.retrieve_users'))\r\n\r\n\r\[email protected]('/login', methods=['GET', 'POST'])\r\ndef login():\r\n login_form = Login(request.form)\r\n if request.method == 'POST' and login_form.validate():\r\n session['current'] = login_form.email.data\r\n if login_form.email.data == \"[email protected]\":\r\n if login_form.password.data == \"Admin123\":\r\n session['admin'] = True\r\n session['customer'] = False\r\n session['deliveryman'] = False\r\n return redirect(url_for('home'))\r\n else:\r\n session['customer'] = False\r\n session['admin'] = False\r\n session['deliveryman'] = False\r\n else:\r\n users_dict = {}\r\n deliveryman_login = {}\r\n db = shelve.open('storage.db', 'r')\r\n try:\r\n users_dict = db['Users']\r\n except:\r\n return redirect(url_for('elly.signup'))\r\n try:\r\n deliveryman_login = db[\"Deliverymen_login\"]\r\n except:\r\n print('no deliveryman')\r\n db.close()\r\n\r\n users_list = []\r\n print(deliveryman_login)\r\n for key in deliveryman_login:\r\n if login_form.email.data == key:\r\n print('dsa')\r\n if login_form.password.data == 'Deliverymen123':\r\n session['customer'] = False\r\n session['admin'] = False\r\n session['deliveryman'] = True\r\n return redirect(url_for('home'))\r\n for key in users_dict:\r\n user = users_dict.get(key)\r\n if key == login_form.email.data:\r\n if login_form.password.data == user.get_password():\r\n users_list.append(user)\r\n session['customer'] = True\r\n session['admin'] = False\r\n session['deliveryman'] = False\r\n return redirect(url_for('elly.profile'))\r\n if login_form.email.data not in users_dict:\r\n return redirect(url_for('elly.signup'))\r\n\r\n return render_template('login.html', form=login_form)\r\n\r\n\r\[email protected]('/logout')\r\ndef logout():\r\n try:\r\n session.pop('current', None)\r\n session.pop('admin', None)\r\n session.pop('customer', None)\r\n session.pop('deliverman', None)\r\n except:\r\n flash('User is not logged in')\r\n return redirect(url_for('home'))\r\n\r\n\r\[email protected]('/profile')\r\ndef profile():\r\n email = session.get('current', 'c')\r\n users_dict = {}\r\n db = shelve.open('storage.db', 'r')\r\n users_dict = db['Users']\r\n db.close()\r\n\r\n users_list = []\r\n for key in users_dict:\r\n user = users_dict.get(key)\r\n if key == email:\r\n users_list.append(user)\r\n\r\n return render_template('profile(customer).html', count=len(users_list), users_list=users_list)\r\n\r\n\r\[email protected]('/deleteAcc/<email>', methods=['POST'])\r\ndef delete_acc(email):\r\n users_dict = {}\r\n db = shelve.open('storage.db', 'w')\r\n users_dict = db['Users']\r\n\r\n users_dict.pop(email)\r\n\r\n db['Users'] = users_dict\r\n db.close()\r\n\r\n try:\r\n session.pop('current', None)\r\n session.pop('customer', None)\r\n except:\r\n flash('User is not logged in')\r\n return redirect(url_for('home'))\r\n\r\n\r\[email protected]('/updateProfile/<email>/', methods=['GET', 'POST'])\r\ndef update_profile(email):\r\n update_profile_form = UpdateProfile(request.form)\r\n if request.method == 'POST' and update_profile_form.validate():\r\n users_dict = {}\r\n db = shelve.open('storage.db', 'w')\r\n users_dict = db['Users']\r\n\r\n user = users_dict.get(email)\r\n user.set_first_name(update_profile_form.first_name.data)\r\n user.set_last_name(update_profile_form.last_name.data)\r\n user.set_email(update_profile_form.email.data)\r\n db['Users'] = users_dict\r\n db.close()\r\n\r\n return redirect(url_for('elly.profile'))\r\n else:\r\n users_dict = {}\r\n db = shelve.open('storage.db', 'r')\r\n users_dict = db['Users']\r\n db.close()\r\n\r\n user = users_dict.get(email)\r\n update_profile_form.first_name.data = user.get_first_name()\r\n update_profile_form.last_name.data = user.get_last_name()\r\n update_profile_form.email.data = user.get_email()\r\n return render_template('updateProfile.html', form=update_profile_form)\r\n\r\n\r\[email protected]('/updatePassword/<email>/', methods=['GET', 'POST'])\r\ndef update_password(email):\r\n update_password_form = UpdatePassword(request.form)\r\n if request.method == 'POST' and update_password_form.validate():\r\n users_dict = {}\r\n db = shelve.open('storage.db', 'w')\r\n users_dict = db['Users']\r\n\r\n user = users_dict.get(email)\r\n user.set_password(update_password_form.password.data)\r\n db['Users'] = users_dict\r\n db.close()\r\n\r\n return redirect(url_for('elly.profile'))\r\n else:\r\n users_dict = {}\r\n db = shelve.open('storage.db', 'r')\r\n users_dict = db['Users']\r\n db.close()\r\n\r\n user = users_dict.get(email)\r\n update_password_form.password.data = user.get_password()\r\n return render_template('updatePassword(cust).html', form=update_password_form)\r\n\r\n\r\[email protected]('/createLocation', methods=['GET', 'POST'])\r\ndef create_location():\r\n location_form = CreateLocation(request.form)\r\n count = 1\r\n if request.method == 'POST' and location_form.validate():\r\n locations_dict = {}\r\n db = shelve.open('location.db', 'c')\r\n\r\n try:\r\n locations_dict = db['Locations']\r\n while count in locations_dict:\r\n count += 1\r\n except:\r\n print(\"Error in retrieving locations from location.db.\")\r\n\r\n location = Location.Location(location_form.neighbourhood.data, location_form.address.data,\r\n location_form.area.data, location_form.availability.data)\r\n print(\"===location====\", location)\r\n location.set_location_id(count)\r\n locations_dict[location.get_location_id()] = location\r\n db['Locations'] = locations_dict\r\n\r\n # Test codes\r\n locations_dict = db['Locations']\r\n location = locations_dict[location.get_location_id()]\r\n print(location.get_address(), \"was stored in location.db successfully with location_id ==\",\r\n location.get_location_id())\r\n\r\n db.close()\r\n\r\n session['location_created'] = location.get_address()\r\n\r\n return redirect(url_for('elly.retrieve_locations'))\r\n return render_template('createLocation(admin).html', form=location_form)\r\n\r\n\r\[email protected]('/retrieveLocations')\r\ndef retrieve_locations():\r\n locations_dict = {}\r\n db = shelve.open('location.db', 'r')\r\n locations_dict = db['Locations']\r\n db.close()\r\n\r\n locations_list = []\r\n for key in locations_dict:\r\n location = locations_dict.get(key)\r\n locations_list.append(location)\r\n\r\n return render_template('retrieveLocations(admin).html', count=len(locations_list), locations_list=locations_list)\r\n\r\n\r\[email protected]('/storeLocator')\r\ndef store_locator():\r\n locations_dict = {}\r\n try:\r\n db = shelve.open('location.db', 'r')\r\n locations_dict = db['Locations']\r\n db.close()\r\n except:\r\n print('location no created')\r\n\r\n locations_list = []\r\n for key in locations_dict:\r\n location = locations_dict.get(key)\r\n locations_list.append(location)\r\n\r\n return render_template('storeLocator(customer).html', count=len(locations_list), locations_list=locations_list)\r\n\r\n\r\[email protected]('/deleteLocation/<int:id>', methods=['POST'])\r\ndef delete_location(id):\r\n locations_dict = {}\r\n db = shelve.open('location.db', 'w')\r\n locations_dict = db['Locations']\r\n\r\n locations_dict.pop(id)\r\n\r\n db['Locations'] = locations_dict\r\n db.close()\r\n\r\n return redirect(url_for('elly.retrieve_locations'))\r\n\r\n\r\[email protected]('/updateLocation/<int:id>/', methods=['GET', 'POST'])\r\ndef update_location(id):\r\n update_location_form = CreateLocation(request.form)\r\n if request.method == 'POST' and update_location_form.validate():\r\n locations_dict = {}\r\n db = shelve.open('location.db', 'w')\r\n locations_dict = db['Locations']\r\n\r\n location = locations_dict.get(id)\r\n location.set_neighbourhood(update_location_form.neighbourhood.data)\r\n location.set_address(update_location_form.address.data)\r\n location.set_area(update_location_form.area.data)\r\n location.set_availability(update_location_form.availability.data)\r\n db['Locations'] = locations_dict\r\n db.close()\r\n\r\n return redirect(url_for('elly.retrieve_locations'))\r\n else:\r\n locations_dict = {}\r\n db = shelve.open('location.db', 'r')\r\n locations_dict = db['Locations']\r\n db.close()\r\n\r\n location = locations_dict.get(id)\r\n update_location_form.neighbourhood.data = location.get_neighbourhood()\r\n update_location_form.address.data = location.get_address()\r\n update_location_form.area.data = location.get_area()\r\n update_location_form.availability.data = location.get_availability()\r\n return render_template('updateLocation(admin).html', form=update_location_form)\r\n" }, { "alpha_fraction": 0.6461824774742126, "alphanum_fraction": 0.6517691016197205, "avg_line_length": 25.538461685180664, "blob_id": "0445daa99ddac7b5d26c8aacccf18cf2f992ae81", "content_id": "180efc8e929877d27f67d9049c7a938fb8f74f98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2148, "license_type": "no_license", "max_line_length": 68, "num_lines": 78, "path": "/__init__.py", "repo_name": "frake17/SSP_project", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request, redirect, url_for\r\nfrom flask_mysqldb import MySQL\r\nimport MySQLdb.cursors\r\nimport re\r\nfrom alicia import alicia\r\nfrom elly import elly\r\nfrom kin import kin\r\nfrom zhiching import qing\r\n\r\nUPLOAD_FOLDER = 'static/img/uploaded'\r\nALLOWED_EXTENSIONS = {'png'}\r\n\r\napp = Flask(__name__)\r\napp.secret_key = 'any_random_string'\r\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\r\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\r\napp.config[\"SESSION_PERMANENT\"] = False\r\napp.register_blueprint(alicia)\r\napp.register_blueprint(elly)\r\napp.register_blueprint(kin)\r\napp.register_blueprint(qing)\r\napp.config['MYSQL_HOST'] = 'localhost'\r\napp.config['MYSQL_USER'] = 'root'\r\napp.config['MYSQL_PASSWORD'] = '100carbook'\r\napp.config['MYSQL_DB'] = 'pythonlogin'\r\n\r\napp.config['RECAPTCHA_USE_SSL'] = False\r\napp.config['RECAPTCHA_PUBLIC_KEY'] = '6Lf15hYbAAAAAK_KyjqVXkqKhFe6NUt-4HpzAIek'\r\napp.config['RECAPTCHA_PRIVATE_KEY'] = '6Lf15hYbAAAAAMq2XaVag56w4fFCNmSo9WkgxOBh'\r\napp.config['RECAPTCHA_OPTIONS'] = {'theme': 'white'}\r\napp.config['RECAPTCHA_PARAMETERS '] = {'hl': 'pt'}\r\n\r\n\r\nmysql = MySQL(app)\r\n\r\n\r\ndef allowed_file(filename):\r\n return '.' in filename and \\\r\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\r\n\r\n\r\[email protected]('/')\r\ndef home():\r\n return render_template('home.html')\r\n\r\[email protected](\"/login\", methods=['GET', 'POST'])\r\ndef login():\r\n if request.method == \"POST\":\r\n if request.form['btn'] == \"login_btn\":\r\n return redirect(url_for(\"authenticate\"))\r\n\r\n return render_template('login.html')\r\n\r\[email protected](\"/authenticate\", methods=['GET', 'POST'])\r\ndef authenticate():\r\n return render_template('authenticate.html')\r\n\r\[email protected](\"/login\", methods=['GET', 'POST'])\r\ndef login():\r\n if request.method == \"POST\":\r\n if request.form['btn'] == \"login_btn\":\r\n return redirect(url_for(\"authenticate\"))\r\n\r\n return render_template('login.html')\r\n\r\n\r\[email protected](\"/authenticate\", methods=['GET', 'POST'])\r\ndef authenticate():\r\n return render_template('authenticate.html')\r\n\r\n\r\[email protected](404)\r\ndef page_not_found(e):\r\n return render_template('error404.html'), 404\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run()\r\n" }, { "alpha_fraction": 0.6033946871757507, "alphanum_fraction": 0.6138665080070496, "avg_line_length": 49.72618865966797, "blob_id": "9f3a795377004e55aba6d443ff7f8e7161b60ea9", "content_id": "f38c5781b31bc07bfae1b354562a65f8208f45e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17382, "license_type": "no_license", "max_line_length": 153, "num_lines": 336, "path": "/Forms.py", "repo_name": "frake17/SSP_project", "src_encoding": "UTF-8", "text": "from datetime import datetime, date\r\n\r\nfrom wtforms import Form, StringField, RadioField, SelectField, TextAreaField, validators, IntegerField, DateField, \\\r\n FloatField, TimeField, ValidationError, PasswordField, SubmitField\r\nfrom wtforms.fields.html5 import EmailField\r\nfrom flask_wtf import Form, RecaptchaField\r\n\r\n\r\nclass Item(Form):\r\n stock_name = StringField('Stock Name', [validators.DataRequired()])\r\n brand = StringField('Brand Name', [validators.DataRequired()])\r\n amt_of_stock = IntegerField('Current stock', [validators.DataRequired()])\r\n stock_unit = SelectField('Unit for stocks', [validators.DataRequired()],\r\n choices=[('Kg', 'Kg'), ('L', 'L'), ('boxes', 'boxes')], render_kw={'onchange': \"myFunction()\"})\r\n subcategory_boxes = IntegerField('Per box', [validators.Optional()])\r\n price = FloatField('Price', [validators.DataRequired()])\r\n origin = StringField('Origin', [validators.DataRequired()])\r\n weight = FloatField('Weight', [validators.DataRequired()])\r\n unit = SelectField('Unit', [validators.DataRequired()],\r\n choices=[('Kg', 'Kg'), ('L', 'L')])\r\n Dietary = SelectField('Dietary', [validators.Optional()], choices=[\r\n ('', 'Select'), ('Halal', 'Halal'), ('Healthier choice', 'Healthier choice'), ('Organic', 'Organic'),\r\n ('Vegetarian', 'Vegetarian'),\r\n ('Gluten-Free', 'Gluten-Free'), ('Trans-Fat-Free', 'Trans-Fat-Free'), ('Hypoallergenic', 'Hypoallergenic'),\r\n ('Lactose-Free', 'Lactose-Free')\r\n ], default='')\r\n category = SelectField('Category', [validators.required()],\r\n choices=[('Fruit and vegetables', 'Fruit and vegetables'), ('Frozen', 'Frozen'),\r\n ('Dairy', 'Dairy'), ('Meat and seafood', 'Meat and seafood'), ('Drinks', 'Drinks'),\r\n ('Packaged food and snacks', 'Packaged food and snacks')])\r\n ingredients = TextAreaField('Ingredients', [validators.Optional()])\r\n description = TextAreaField('Description', [validators.Optional()])\r\n\r\n def validate_amt_of_stock(form, amt_of_stock):\r\n if not str(amt_of_stock.data).isdigit():\r\n raise ValidationError('Only digits allowed')\r\n\r\n def validate_price(form, price):\r\n if type(price.data) != float:\r\n raise ValidationError('Only digits allowed')\r\n\r\n def validate_weight(form, weight):\r\n print(type(weight.data))\r\n if type(weight.data) != float:\r\n raise ValidationError('Only digits allowed')\r\n\r\n\r\nclass Order(Form):\r\n name = StringField('name', [validators.DataRequired()])\r\n number = IntegerField('Phone_number',\r\n [validators.DataRequired()])\r\n postal = IntegerField('Postal_code', [validators.DataRequired()])\r\n address = StringField('Address', [validators.Length(min=1, max=150), validators.DataRequired()])\r\n general_location = SelectField('General location', [validators.data_required()],\r\n choices=[('North', 'North'), ('South', 'South'),\r\n ('East', 'East'), ('West', 'West')])\r\n level = IntegerField('Level', [validators.number_range(min=1, max=50), validators.DataRequired()])\r\n door_number = StringField('Door_number', [validators.DataRequired()])\r\n card_number = IntegerField('Card_number', [\r\n validators.DataRequired()])\r\n exp_date = DateField('Exp_date(mm/yyyy)', [validators.DataRequired()], format='%m/%Y')\r\n cvv = IntegerField('Card_cvv', [validators.number_range(min=000, max=999), validators.DataRequired()])\r\n card_type = SelectField('Card_type', choices=[('CC', 'Credit Card'), ('DC', 'Debit Card')])\r\n remarks = TextAreaField('Remarks')\r\n\r\n def validate_number(form, number):\r\n length = str(number.data)\r\n if len(length) > 8 or len(length) < 8:\r\n raise ValidationError('Phone number should be 8 numbers')\r\n if not length.isdigit():\r\n raise ValidationError('Only digits are allowed')\r\n\r\n def validate_postal(form, postal):\r\n if not str(postal.data).isdigit():\r\n raise ValidationError('Only digits are allowed')\r\n if len(str(postal.data)) < 6 or len(str(postal.data)) > 6:\r\n raise ValidationError('Postal code is only 6 digits long')\r\n\r\n def validate_level(form, level):\r\n if not str(level.data).isdigit():\r\n raise ValidationError('Only digit allowed')\r\n\r\n def validate_card_number(form, card_number):\r\n if len(str(card_number.data)) > 19 or len(str(card_number.data)) < 16:\r\n raise ValidationError('Card numbers should be between 16 and 19')\r\n\r\n def validate_cvv(form, cvv):\r\n if len(str(cvv.data)) != 3:\r\n raise ValidationError('cvv should be 3 digits long')\r\n\r\n def validate_exp_date(self, exp_date):\r\n date_now = datetime.now()\r\n date = date_now.strftime('%Y-%m-%d')\r\n exp = exp_date.data.strftime('%Y-%m-%d')\r\n if exp < date:\r\n raise ValidationError('Expiry date is invalid')\r\n\r\n\r\nclass self_collect(Form):\r\n name = StringField('name', [validators.DataRequired()])\r\n card_number = IntegerField('Card number', [\r\n validators.DataRequired()])\r\n exp_date = DateField('Expiry date(mm/yyyy)', [validators.DataRequired()], format='%m/%Y')\r\n cvv = IntegerField('Card cvv', [validators.DataRequired()])\r\n card_type = SelectField('Card type', choices=[('CC', 'Credit Card'), ('DC', 'Debit Card')])\r\n number = IntegerField('Phone number',\r\n [validators.DataRequired()])\r\n\r\n def validate_card_number(form, card_number):\r\n if len(str(card_number.data)) > 19 or len(str(card_number.data)) < 16:\r\n raise ValidationError('Card numbers should be between 16 and 19')\r\n\r\n def validate_cvv(form, cvv):\r\n if len(str(cvv.data)) != 3:\r\n raise ValidationError('cvv should be 3 digits long')\r\n\r\n def validate_number(form, number):\r\n length = str(number.data)\r\n if len(length) > 8 or len(length) < 8:\r\n raise ValidationError('Phone number should be 8 numbers')\r\n if not length.isdigit():\r\n raise ValidationError('Only digits are allowed')\r\n\r\n def validate_exp_date(self, exp_date):\r\n date_now = datetime.now()\r\n date = date_now.strftime('%Y-%m-%d')\r\n exp = exp_date.data.strftime('%Y-%m-%d')\r\n if exp < date:\r\n raise ValidationError('Expiry date is invalid')\r\n\r\n\r\nclass self_collection_update(Form):\r\n name = StringField('name', [validators.data_required()])\r\n number = IntegerField('Phone_number',\r\n [validators.number_range(min=00000000, max=99999999,\r\n message='Contact number should be 8 digits'),\r\n validators.data_required()])\r\n status = SelectField('Status',\r\n choices=[('collected', 'collected'), ('Not collected', 'Not collected'), ('reschedule', 'reschedule')])\r\n\r\n def validate_number(form, number):\r\n length = str(number.data)\r\n if len(length) > 8 or len(length) < 8:\r\n raise ValidationError('Phone number should be 8 numbers')\r\n if not length.isdigit():\r\n raise ValidationError('Only digits are allowed')\r\n\r\n\r\nclass Supplier(Form):\r\n name = StringField('name', [validators.DataRequired()])\r\n number = IntegerField('Phone_number',\r\n [validators.DataRequired()])\r\n email = EmailField('email', [validators.DataRequired()])\r\n location = StringField('Location', [validators.DataRequired()])\r\n\r\n def validate_number(form, number):\r\n length = str(number.data)\r\n if len(length) > 8 or len(length) < 8:\r\n raise ValidationError('Phone number should be 8 numbers')\r\n if not length.isdigit():\r\n raise ValidationError('Only digits are allowed')\r\n\r\n\r\nclass recaptcha_form(Form):\r\n recaptcha = RecaptchaField()\r\n\r\n\r\nclass SignUp(Form):\r\n first_name = StringField('First Name', [validators.Length(min=1, max=150), validators.DataRequired()])\r\n last_name = StringField('Last Name', [validators.Length(min=1, max=150), validators.DataRequired()])\r\n email = StringField('Email', [validators.Length(min=1, max=150), validators.DataRequired(), validators.Email()])\r\n password = PasswordField('Password', [validators.DataRequired(), validators.EqualTo('confirm_password')])\r\n confirm_password = PasswordField('Confirm Password', [validators.DataRequired(), validators.EqualTo('password')])\r\n security_question = SelectField('Security question', [validators.DataRequired()], choices = [('1', 'option 1'), ('2', 'option 2'), ('3', 'option 3')]\r\n )\r\n security_answer = StringField('Security answers', [validators.DataRequired()])\r\n submit = SubmitField('Sign Up')\r\n\r\n def validate_password(form, password):\r\n password_value = password.data\r\n special_characters = False\r\n upper_case = False\r\n lower_case = False\r\n numeric_number = False\r\n if len((str(password_value ))) < 8:\r\n raise ValidationError('Password should be at least 8 letters/digits long')\r\n for i in str(password_value ):\r\n if i.isupper():\r\n upper_case = True\r\n if i.islower():\r\n lower_case = True\r\n if i.isdigit():\r\n numeric_number = True\r\n if not i.isalnum():\r\n special_characters = True\r\n if not upper_case:\r\n raise ValidationError('Password must contain at least 1 upper case letter')\r\n if not lower_case:\r\n raise ValidationError('Password must contain at least 1 lower case letter')\r\n if not numeric_number:\r\n raise ValidationError('Password must contain at least 1 digit')\r\n if not special_characters:\r\n raise ValidationError('Password must contain at least 1 special character')\r\n\r\n\r\nclass optional_signup(Form):\r\n Phone_number = IntegerField('Phone number', validators=(validators.Optional(),))\r\n card_number = IntegerField('Card number', validators=(validators.Optional(),))\r\n exp_date = DateField('Expiry date(mm/yyyy)',format='%m/%Y',validators=(validators.Optional(),))\r\n CVV = IntegerField('CVV', validators=(validators.Optional(),))\r\n\r\n\r\nclass Login(Form):\r\n email = StringField('Email', [validators.Length(min=1, max=150), validators.DataRequired()])\r\n password = PasswordField('Password', [validators.DataRequired()])\r\n submit = SubmitField('Log In')\r\n\r\n\r\nclass UpdateProfile(Form):\r\n first_name = StringField('First Name', [validators.Length(min=1, max=150), validators.DataRequired()])\r\n last_name = StringField('Last Name', [validators.Length(min=1, max=150), validators.DataRequired()])\r\n email = StringField('Email', [validators.Length(min=1, max=150), validators.DataRequired(), validators.Email()])\r\n\r\n\r\nclass UpdatePassword(Form):\r\n password = PasswordField('Password', [validators.DataRequired(), validators.EqualTo('confirm_password')])\r\n confirm_password = PasswordField('Confirm Password')\r\n\r\n\r\nclass CreateLocation(Form):\r\n neighbourhood = StringField('Neighbourhood', [validators.Length(min=1, max=150), validators.DataRequired()])\r\n address = StringField('Address', [validators.Length(min=1, max=150), validators.DataRequired()])\r\n area = RadioField('Area', choices=[('North', 'North'), ('South', 'South'), ('East', 'East'), ('West', 'West')],\r\n default='North')\r\n availability = RadioField('Availability', choices=[('Full', 'Full'), ('Available', 'Available')], default='Full')\r\n\r\n\r\nclass CreateDeliverymen(Form):\r\n first_name = StringField('First Name :', [validators.Length(min=1, max=150), validators.DataRequired()])\r\n last_name = StringField('Last Name :', [validators.Length(min=1, max=150), validators.DataRequired()])\r\n gender = SelectField('Gender :', [validators.DataRequired()],\r\n choices=[('', 'Select'), ('F', 'Female'), ('M', 'Male')], default='')\r\n email = StringField('Email :', [validators.Length(min=1, max=150), validators.DataRequired()])\r\n contact_no = IntegerField('Contact number :', [validators.DataRequired()])\r\n regions = RadioField('Regions in charge :', choices=[('N', 'North'), ('S', 'South'), ('E', 'East'), ('W', 'West')],\r\n default='F')\r\n remarks = TextAreaField('Remarks :', [validators.Optional()])\r\n\r\n def validate_contact_no(form, contact_no):\r\n length = str(contact_no.data)\r\n if len(length) > 8 or len(length) < 8:\r\n raise ValidationError('Phone number should be 8 numbers')\r\n if not length.isdigit():\r\n raise ValidationError('Only digits are allowed')\r\n\r\n\r\nclass deliverymen_profile_update(Form):\r\n first_name = StringField('First Name :', [validators.Length(min=1, max=150), validators.DataRequired()])\r\n last_name = StringField('Last Name :', [validators.Length(min=1, max=150), validators.DataRequired()])\r\n gender = SelectField('Gender :', [validators.DataRequired()],\r\n choices=[('', 'Select'), ('F', 'Female'), ('M', 'Male')], default='')\r\n email = StringField('Email :', [validators.Length(min=1, max=150), validators.DataRequired()])\r\n contact_no = IntegerField('Contact number :', [validators.DataRequired()])\r\n regions = RadioField('Regions in charge :', choices=[('N', 'North'), ('S', 'South'), ('E', 'East'), ('W', 'West')],\r\n default='F')\r\n remarks = TextAreaField('Remarks :', [validators.Optional()])\r\n\r\n def validate_contact_no(form, contact_no):\r\n length = str(contact_no.data)\r\n if len(length) > 8 or len(length) < 8:\r\n raise ValidationError('Phone number should be 8 numbers')\r\n if not length.isdigit():\r\n raise ValidationError('Only digits are allowed')\r\n\r\n\r\nclass deliverymen_status_update(Form):\r\n name = StringField('name', [validators.data_required()])\r\n number = IntegerField('Phone_number',[validators.data_required()])\r\n level = IntegerField('Level', [validators.number_range(min=1, max=50), validators.DataRequired()])\r\n door_number = IntegerField('Door_number', [validators.DataRequired()])\r\n postal = IntegerField('Postal_code', [validators.number_range(min=1, max=999999), validators.DataRequired()])\r\n\r\n def validate_number(form, number):\r\n length = str(number.data)\r\n if len(length) > 8 or len(length) < 8:\r\n raise ValidationError('Phone number should be 8 numbers')\r\n if not length.isdigit():\r\n raise ValidationError('Only digits are allowed')\r\n\r\n def validate_postal(form, postal):\r\n if not str(postal.data).isdigit():\r\n raise ValidationError('Only digits are allowed')\r\n if len(str(postal.data)) < 6 or len(str(postal.data)) > 6:\r\n raise ValidationError('Postal code is only 6 digits long')\r\n\r\n\r\nclass CreateUserForm(Form):\r\n date = DateField(\"Date (YYYY-MM-DD)\", format='%Y-%m-%d', default=datetime.now())\r\n cust_ic = StringField(\"Customer IC\", [validators.DataRequired()])\r\n cust_no = StringField(\"Customer Number\", [validators.DataRequired()])\r\n temp = FloatField(\"Temperature (°C)\", [\r\n validators.NumberRange(max=37.5, message=\"Temperature is above 37.5°C, customer not allowed to enter\"),\r\n validators.DataRequired()])\r\n time_enter = TimeField(\"Time - Enter (HH:MM)\", format='%H:%M', default=datetime.now())\r\n time_leave = TimeField(\"Time - Leave (HH:MM)\", format='%H:%M', default=datetime.strptime(\"23:59\", \"%H:%M\"))\r\n\r\n def validate_cust_ic(form, cust_ic):\r\n if not cust_ic.data.startswith((\"S\", \"T\")):\r\n raise ValidationError(\"IC must start with S or T\")\r\n if not cust_ic.data[1:7].isdigit():\r\n raise ValidationError(\"IC must be in digits excluding first and last letters\")\r\n if not cust_ic.data[-1].isalpha():\r\n raise ValidationError(\"IC must end with an alphabet\")\r\n if len(cust_ic.data) != 9:\r\n raise ValidationError(\"Length of IC must be 9 characters\")\r\n\r\n def validate_cust_no(form, cust_no):\r\n if not cust_no.data.isdigit():\r\n raise ValidationError(\"Customer's number must be all digits\")\r\n if len(cust_no.data) != 8:\r\n raise ValidationError(\"Customer's number must only have 8 digits\")\r\n\r\n\r\nclass SearchUserForm(Form):\r\n search_date = DateField(\"Date (YYYY-MM-DD)\", format='%Y-%m-%d', default=datetime.now())\r\n search_cust = StringField(\"Customer IC\")\r\n\r\n def validate_search_cust(form, search_cust):\r\n if not search_cust.data.startswith((\"S\", \"T\")):\r\n raise ValidationError(\"IC must start with S or T\")\r\n if not search_cust.data[1:7].isdigit():\r\n raise ValidationError(\"IC must be in digits excluding first and last letters\")\r\n if not search_cust.data[-1].isalpha():\r\n raise ValidationError(\"IC must end with an alphabet\")\r\n if len(search_cust.data) != 9:\r\n raise ValidationError(\"Length of IC must be 9 characters\")\r\n" }, { "alpha_fraction": 0.5014625787734985, "alphanum_fraction": 0.5031341314315796, "avg_line_length": 31.79452133178711, "blob_id": "6e7e3fc887071474759c21b2daef0252e83cfb30", "content_id": "b4745d8c0f7b687073602da6f331a74afa6f2842", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2393, "license_type": "no_license", "max_line_length": 110, "num_lines": 73, "path": "/templates/Outlet_South.html", "repo_name": "frake17/SSP_project", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n{% block title %} Outlet_South{% endblock %}\n\n{% block content %}\n<h1 class=\"display-4\">Self collection in the South</h1>\n<!-- Nav tabs -->\n<ul class=\"nav nav-tabs\">\n <li class=\"nav-item\">\n <a class=\"nav-link\" href=\"/All_Deliveries\">Delivery</a>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link active\" data-toggle=\"tab\" href=\"/All_Self_collection\">Self-collection</a>\n </li>\n <li class=\"nav-item dropdown\">\n <a class=\"nav-link dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\" id=\"navbardrop\">\n Deliverymen\n </a>\n <div class=\"dropdown-menu\">\n <a class=\"dropdown-item\" href=\"/Create_Deliverymen\">Create Deliverymen</a>\n <a class=\"dropdown-item\" href=\"/Display_Deliverymen\">Display Deliverymen</a>\n </div>\n </li>\n</ul>\n<br>\n<ul class=\"navbar-nav\">\n <li class=\"nav-item dropdown\">\n <a class=\"nav-link dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\" id=\"navbardrop1\">\n Outlets Regions\n </a>\n <div class=\"dropdown-menu\">\n <a class=\"dropdown-item\" href=\"/Outlet_North\">North</a>\n <a class=\"dropdown-item\" href=\"/Outlet_South\">South</a>\n <a class=\"dropdown-item\" href=\"/Outlet_East\">East</a>\n <a class=\"dropdown-item\" href=\"/Outlet_West\">West</a>\n </div>\n </li>\n</ul>\n<br>\n<table class=\"table table-striped\">\n <thead>\n <tr>\n <th>No.</th>\n <th>Name</th>\n <th>Contact No.</th>\n <th>Items</th>\n <th>Outlets</th>\n <th>Date & timing</th>\n <th>Status</th>\n <th>Remarks</th>\n </tr>\n </thead>\n <tbody>\n {% for order in order_list %}\n <tr>\n <td>{{order.get_id()}}</td>\n <td>{{order.get_name()}}</td>\n <td>{{order.get_number()}}</td>\n <td>\n {% for item in order.get_item() %}\n {{item}} x {{order.get_item().get(item)}}\n {% endfor %}\n </td>\n <td>{{order.get_location()}}</td>\n <td>{{order.get_date()}}, {{order.get_time()}}</td>\n <td>{{order.get_status()}}</td>\n <td><a class=\"btn btn-warning\" href=\"/updateSelfCollection/{{order.get_id()}}\">Update</a></td>\n\n </tr>\n {% endfor %}\n </tbody>\n</table>\n\n{% endblock %}" }, { "alpha_fraction": 0.6328698992729187, "alphanum_fraction": 0.6330358982086182, "avg_line_length": 33.03248596191406, "blob_id": "26985e9a195ef2f43e155db0b3a5e2f64d2891c6", "content_id": "af08b0913b59a149cdc031397a197d16db47c784", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24095, "license_type": "no_license", "max_line_length": 119, "num_lines": 708, "path": "/zhiching.py", "repo_name": "frake17/SSP_project", "src_encoding": "UTF-8", "text": "import shelve\n\nfrom flask import Flask, render_template, request, redirect, url_for, session, Blueprint\n\nimport User\nfrom Forms import CreateDeliverymen, \\\n self_collection_update, deliverymen_status_update, deliverymen_profile_update\n\nqing = Flask(__name__)\nqing.secret_key = 'any_random_string'\nqing.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\nqing.config[\"SESSION_PERMANENT\"] = False\nqing = Blueprint('qing', __name__, template_folder='templates', static_folder='static')\n\n\[email protected]('/orders', methods=['GET', 'POST'])\ndef orders():\n db = shelve.open('storage.db', 'r')\n try:\n collect_dict = db['confirmed_collect']\n delivery_dict = db['confirmed_delivery']\n delivery_man_dict = db['Deliverymen']\n except:\n return redirect(url_for('home'))\n\n collect_list = []\n delivery_list = []\n delivery_man = []\n for key in collect_dict:\n order_collect = collect_dict.get(key)\n collect_list.append(order_collect)\n\n for key in delivery_dict:\n order_delivery = delivery_dict.get(key)\n delivery_list.append(order_delivery)\n\n for key in delivery_man_dict:\n man = delivery_man_dict.get(key)\n delivery_man.append(man)\n return render_template('orders.html', collect=collect_list, deliver=delivery_list, man=delivery_man)\n\n\[email protected]('/Dest_West', methods=[\"POST\", \"GET\"])\ndef Dest_West():\n deliverymen_dict = {}\n order_dict = {}\n db = shelve.open('storage.db', 'r')\n try:\n deliverymen_dict = db['Deliverymen']\n order_dict = db['confirmed_delivery']\n except:\n print('smth')\n db.close()\n\n order_list = []\n deliverymen_list = []\n for key in deliverymen_dict:\n deliverymen = deliverymen_dict.get(key)\n if deliverymen.get_regions() == 'W':\n deliverymen_list.append(deliverymen)\n\n for key in order_dict:\n order_deliver = order_dict.get(key)\n if order_deliver.get_location() == 'West':\n order_list.append(order_deliver)\n\n return render_template('Dest_West.html', deliveryman_list=deliverymen_list, order_list=order_list)\n\n\[email protected]('/Dest_North')\ndef Dest_North():\n deliverymen_dict = {}\n order_dict = {}\n db = shelve.open('storage.db', 'r')\n try:\n deliverymen_dict = db['Deliverymen']\n order_dict = db['confirmed_delivery']\n except:\n print('smth')\n db.close()\n\n order_list = []\n deliverymen_list = []\n for key in deliverymen_dict:\n deliverymen = deliverymen_dict.get(key)\n if deliverymen.get_regions() == 'N':\n deliverymen_list.append(deliverymen)\n\n for key in order_dict:\n order_deliver = order_dict.get(key)\n if order_deliver.get_location() == 'North':\n order_list.append(order_deliver)\n return render_template('Dest_North.html', deliveryman_list=deliverymen_list, order_list=order_list)\n\n\[email protected]('/Dest_South')\ndef Dest_South():\n order_dict = {}\n deliverymen_dict = {}\n db = shelve.open('storage.db', 'r')\n try:\n deliverymen_dict = db['Deliverymen']\n order_dict = db['confirmed_delivery']\n except:\n print('smth')\n db.close()\n\n order_list = []\n deliverymen_list = []\n for key in deliverymen_dict:\n deliverymen = deliverymen_dict.get(key)\n if deliverymen.get_regions() == 'S':\n deliverymen_list.append(deliverymen)\n\n for key in order_dict:\n order_deliver = order_dict.get(key)\n if order_deliver.get_location() == 'South':\n order_list.append(order_deliver)\n return render_template('Dest_South.html', deliveryman_list=deliverymen_list, order_list=order_list)\n\n\[email protected]('/Dest_East', methods=[\"POST\", \"GET\"])\ndef Dest_East():\n deliverymen_dict = {}\n order_dict = {}\n db = shelve.open('storage.db', 'r')\n try:\n deliverymen_dict = db['Deliverymen']\n order_dict = db['confirmed_delivery']\n except:\n print('smth')\n db.close()\n\n order_list = []\n deliverymen_list = []\n for key in deliverymen_dict:\n deliverymen = deliverymen_dict.get(key)\n if deliverymen.get_regions() == 'E':\n deliverymen_list.append(deliverymen)\n\n for key in order_dict:\n order_deliver = order_dict.get(key)\n if order_deliver.get_location() == 'East':\n order_list.append(order_deliver)\n\n return render_template('Dest_East.html', deliveryman_list=deliverymen_list, order_list=order_list)\n\n\[email protected]('/All_Deliveries')\ndef All_Deliveries():\n order_dict = {}\n try:\n db = shelve.open('storage.db', 'r')\n order_dict = db['confirmed_delivery']\n except:\n print('not created')\n\n order_list = []\n for key in order_dict:\n order_deliver = order_dict.get(key)\n order_list.append(order_deliver)\n return render_template('All_Deliveries.html', order_list=order_list)\n\n\[email protected]('/All_Self_collection')\ndef All_Self_collection():\n order_dict = {}\n try:\n db = shelve.open('storage.db', 'r')\n order_dict = db['confirmed_collect']\n except:\n print('not created')\n\n order_list = []\n for key in order_dict:\n order_collect = order_dict.get(key)\n order_list.append(order_collect)\n return render_template('All_Self_collection.html', order_list=order_list)\n\n\[email protected]('/Create_Deliverymen', methods=['GET', 'POST'])\ndef Create_Deliverymen():\n count = 1\n create_Deliverymen_form = CreateDeliverymen(request.form)\n if request.method == 'POST' and create_Deliverymen_form.validate():\n deliverymen_dict = {}\n db = shelve.open('storage.db', 'c')\n try:\n deliverymen_dict = db[\"Deliverymen\"]\n while count in deliverymen_dict:\n count += 1\n except:\n print(\"Error in retrieving Users from storage.db.\")\n\n deliverymen = User.Deliverymen(create_Deliverymen_form.first_name.data, create_Deliverymen_form.last_name.data,\n create_Deliverymen_form.email.data, create_Deliverymen_form.gender.data,\n create_Deliverymen_form.contact_no.data, create_Deliverymen_form.regions.data,\n create_Deliverymen_form.remarks.data)\n\n deliverymen_dict[deliverymen.get_Deliverymen_id()] = deliverymen\n db['Deliverymen'] = deliverymen_dict\n deliverymen_login = {}\n try:\n deliverymen_login = db[\"Deliverymen_login\"]\n except:\n print(\"Error in retrieving Deliverymen from storage.db\")\n\n deliverymen_login[create_Deliverymen_form.email.data] = deliverymen.get_Deliverymen_id()\n db[\"Deliverymen_login\"] = deliverymen_login\n db.close()\n\n session['Deliverymen_created'] = deliverymen.get_first_name() + ' ' + deliverymen.get_last_name()\n return redirect(url_for('qing.Display_Deliverymen'))\n\n return render_template('Create_Deliverymen.html', form=create_Deliverymen_form)\n\n\[email protected]('/Display_Deliverymen', defaults={'id': None})\[email protected]('/Display_Deliverymen/<int:id>')\ndef Display_Deliverymen(id):\n users_dict = {}\n order_list = {}\n db = shelve.open('storage.db', 'r')\n try:\n users_dict = db['Deliverymen']\n assign_dict = db['assignDeliverymen']\n if id is not None:\n order_list = assign_dict.get(id)\n\n except:\n print(\"Error in displaying Users from storage.db.\")\n db.close()\n\n users_list = []\n for key in users_dict:\n user = users_dict.get(key)\n users_list.append(user)\n\n return render_template('Display_Deliverymen.html', count=len(users_list), users_list=users_list,\n order_list=order_list)\n\n\[email protected]('/updateDeliverymen/<int:id>/', methods=['GET', 'POST'])\ndef update_Deliverymen(id):\n update_Deliverymen_form = CreateDeliverymen(request.form)\n if request.method == 'POST' and update_Deliverymen_form.validate():\n users_dict = {}\n db = shelve.open('storage.db', 'w')\n users_dict = db['Deliverymen']\n\n user = users_dict.get(id)\n user.set_first_name(update_Deliverymen_form.first_name.data)\n user.set_last_name(update_Deliverymen_form.last_name.data)\n user.set_gender(update_Deliverymen_form.gender.data)\n user.set_email(update_Deliverymen_form.email.data)\n user.set_contact_no(update_Deliverymen_form.contact_no.data)\n user.set_regions(update_Deliverymen_form.regions.data)\n user.set_remarks(update_Deliverymen_form.remarks.data)\n\n db['Deliverymen'] = users_dict\n db.close()\n\n session['Deliverymen_updated'] = user.get_first_name() + ' ' + user.get_last_name()\n\n return redirect(url_for('qing.Display_Deliverymen'))\n else:\n users_dict = {}\n db = shelve.open('storage.db', 'r')\n users_dict = db['Deliverymen']\n db.close()\n\n user = users_dict.get(id)\n update_Deliverymen_form.first_name.data = user.get_first_name()\n update_Deliverymen_form.last_name.data = user.get_last_name()\n update_Deliverymen_form.gender.data = user.get_gender()\n update_Deliverymen_form.email.data = user.get_email()\n update_Deliverymen_form.contact_no.data = user.get_contact_no()\n update_Deliverymen_form.regions.data = user.get_regions()\n update_Deliverymen_form.remarks.data = user.get_remarks()\n\n return render_template('updateDeliverymen.html', form=update_Deliverymen_form)\n\n\[email protected]('/deleteDeliverymen/<int:id>', methods=['POST'])\ndef delete_Deliverymen(id):\n users_dict = {}\n db = shelve.open('storage.db', 'w')\n users_dict = db['Deliverymen']\n deliveryman_login = db['Deliverymen_login']\n\n user = users_dict.pop(id)\n deliveryman_login.pop(user.get_email())\n\n db['Deliverymen'] = users_dict\n db.close()\n\n session['Deliverymen_deleted'] = user.get_first_name() + ' ' + user.get_last_name()\n\n return redirect(url_for('qing.Display_Deliverymen'))\n\n\[email protected]('/deleteOrders/<int:id>/<int:deliverymen_id>', methods=['POST'])\ndef deleteOrders(id, deliverymen_id):\n orders_dict = {}\n db = shelve.open('storage.db', 'w')\n orders_dict = db['assignDeliverymen']\n deleteOrders = orders_dict.get(deliverymen_id)\n deleteOrders.pop(id)\n db['assignDeliverymen'] = orders_dict\n return redirect(url_for('qing.ordersAssigned', id=deliverymen_id))\n\n\[email protected]('/orders_assigned/<int:id>', methods=['POST'])\ndef orders_assigned(id):\n db = shelve.open('storage.db', 'c')\n assign_dict = db['assignDeliverymen']\n order_list = assign_dict.get(id)\n\n\[email protected]('/Deliveryman_North/')\ndef Deliveryman_North():\n deliverymen_dict = {}\n order_dict = {}\n db = shelve.open('storage.db', 'r')\n try:\n deliverymen_dict = db['Deliverymen']\n order_dict = db['confirmed_delivery']\n except:\n print('error')\n db.close()\n\n order_list = []\n deliverymen_list = []\n for key in deliverymen_dict:\n deliverymen = deliverymen_dict.get(key)\n if deliverymen.get_regions() == 'N':\n deliverymen_list.append(deliverymen)\n\n for key in order_dict:\n order_deliver = order_dict.get(key)\n if order_deliver.get_location() == 'North':\n order_list.append(order_deliver)\n\n return render_template('Deliveryman_North.html', users_list=deliverymen_list, order_list=order_list,\n count=len(deliverymen_list))\n\n\[email protected]('/Deliveryman_South/')\ndef Deliveryman_South():\n deliverymen_dict = {}\n order_dict = {}\n db = shelve.open('storage.db', 'r')\n try:\n deliverymen_dict = db['Deliverymen']\n order_dict = db['confirmed_delivery']\n except:\n print('error')\n db.close()\n\n order_list = []\n deliverymen_list = []\n for key in deliverymen_dict:\n deliverymen = deliverymen_dict.get(key)\n if deliverymen.get_regions() == 'S':\n deliverymen_list.append(deliverymen)\n\n for key in order_dict:\n order_deliver = order_dict.get(key)\n if order_deliver.get_location() == 'South':\n order_list.append(order_deliver)\n\n return render_template('Deliveryman_South.html', users_list=deliverymen_list, order_list=order_list,\n count=len(deliverymen_list))\n\n\[email protected]('/Deliveryman_East/')\ndef Deliveryman_East():\n deliverymen_dict = {}\n order_dict = {}\n db = shelve.open('storage.db', 'r')\n try:\n deliverymen_dict = db['Deliverymen']\n order_dict = db['confirmed_delivery']\n except:\n print('error')\n db.close()\n\n order_list = []\n deliverymen_list = []\n for key in deliverymen_dict:\n deliverymen = deliverymen_dict.get(key)\n if deliverymen.get_regions() == 'E':\n deliverymen_list.append(deliverymen)\n\n for key in order_dict:\n order_deliver = order_dict.get(key)\n if order_deliver.get_location() == 'East':\n order_list.append(order_deliver)\n\n return render_template('Deliveryman_East.html', users_list=deliverymen_list, order_list=order_list,\n count=len(deliverymen_list))\n\n\[email protected]('/Deliveryman_West/')\ndef Deliveryman_West():\n deliverymen_dict = {}\n order_dict = {}\n db = shelve.open('storage.db', 'r')\n try:\n deliverymen_dict = db['Deliverymen']\n order_dict = db['confirmed_delivery']\n except:\n print('error')\n db.close()\n\n order_list = []\n deliverymen_list = []\n for key in deliverymen_dict:\n deliverymen = deliverymen_dict.get(key)\n if deliverymen.get_regions() == 'W':\n deliverymen_list.append(deliverymen)\n\n for key in order_dict:\n order_deliver = order_dict.get(key)\n if order_deliver.get_location() == 'West':\n order_list.append(order_deliver)\n\n return render_template('Deliveryman_West.html', users_list=deliverymen_list, order_list=order_list,\n count=len(deliverymen_list))\n\n\[email protected]('/assign/<NSEW>/<int:id>/<int:orderid>', methods=[\"POST\", \"GET\"])\ndef assign(NSEW, id, orderid):\n users_dict = {}\n order_dict = {}\n order_list = []\n db = shelve.open('storage.db', 'c')\n users_dict = db['Deliverymen']\n order_dict = db['confirmed_delivery']\n\n print(order_dict)\n assign_dict = {}\n try:\n assign_dict = db['assignDeliverymen']\n\n if id in assign_dict:\n order_list = assign_dict.get(id)\n print(order_list)\n\n except:\n print('No database')\n deliverymen = users_dict.get(id)\n current_order = order_dict.get(orderid)\n print('**', current_order)\n current_order.set_status('assign')\n order_list.append(current_order)\n print('***', order_list)\n assign_dict[deliverymen.get_Deliverymen_id()] = order_list\n db['assignDeliverymen'] = assign_dict\n db['confirmed_delivery'] = order_dict\n db.close()\n session['OrdersID_assigned'] = deliverymen.get_Deliverymen_id()\n session['Orders_assigned'] = deliverymen.get_first_name() + deliverymen.get_last_name()\n if NSEW == 'North':\n return redirect(url_for('qing.Dest_North'))\n elif NSEW == 'South':\n return redirect(url_for('qing.Dest_South'))\n elif NSEW == 'East':\n return redirect(url_for('qing.Dest_East'))\n elif NSEW == 'West':\n return redirect(url_for('qing.Dest_West'))\n\n\[email protected]('/updateSelfCollection/<int:id>/', methods=['GET', 'POST'])\ndef updateSelfCollection(id):\n updateSelfCollection_form = self_collection_update(request.form)\n if request.method == 'POST':\n users_dict = {}\n db = shelve.open('storage.db', 'w')\n print(updateSelfCollection_form.name.data, updateSelfCollection_form.status.data)\n users_dict = db['confirmed_collect']\n user = users_dict.get(id)\n updateSelfCollection_form.name.data = user.get_name()\n updateSelfCollection_form.number.data = user.get_number()\n user.set_name(updateSelfCollection_form.name.data)\n user.set_phone(updateSelfCollection_form.number.data)\n user.set_status(updateSelfCollection_form.status.data)\n\n db['confirmed_collect'] = users_dict\n db.close()\n\n return redirect(url_for('qing.All_Self_collection'))\n\n else:\n users_dict = {}\n db = shelve.open('storage.db', 'r')\n users_dict = db['confirmed_collect']\n db.close()\n\n user = users_dict.get(id)\n print(users_dict)\n print(user.get_name(), user.get_number())\n updateSelfCollection_form.name.data = user.get_name()\n updateSelfCollection_form.number.data = user.get_number()\n print(updateSelfCollection_form.name.data)\n print(updateSelfCollection_form.number.data)\n\n return render_template('updateSelfCollection.html', form=updateSelfCollection_form)\n\n\[email protected]('/ordersAssigned/<int:id>/', methods=['GET', 'POST'])\ndef ordersAssigned(id):\n index = 0\n db = shelve.open('storage.db', 'r')\n assign_deliverymen = {}\n ordersAssigned_list = []\n try:\n assign_deliverymen = db['assignDeliverymen']\n if id in assign_deliverymen:\n ordersAssigned_list = assign_deliverymen.get(id)\n else:\n ordersAssigned_list = []\n except:\n print('anything')\n return render_template(url_for('qing.Display_Deliverymen'))\n deliverymen_id = id\n return render_template('ordersAssigned.html', order_list=ordersAssigned_list, count=len(ordersAssigned_list),\n deliverymen_id=deliverymen_id, index=index)\n\n\[email protected]('/Outlet_North')\ndef Outlet_North():\n order_dict = {}\n db = shelve.open('storage.db', 'r')\n try:\n order_dict = db['confirmed_collect']\n except:\n print('not created')\n\n order_list = []\n for key in order_dict:\n order_collected = order_dict.get(key)\n if order_collected.get_general_location() == 'North':\n order_list.append(order_collected)\n\n return render_template('Outlet_North.html', order_list=order_list)\n\n\[email protected]('/Outlet_South')\ndef Outlet_South():\n order_dict = {}\n db = shelve.open('storage.db', 'r')\n try:\n order_dict = db['confirmed_collect']\n except:\n print('not created')\n db.close()\n\n order_list = []\n for key in order_dict:\n order_collected = order_dict.get(key)\n if order_collected.get_general_location() == 'South':\n order_list.append(order_collected)\n return render_template('Outlet_South.html', order_list=order_list)\n\n\[email protected]('/Outlet_East')\ndef Outlet_East():\n order_dict = {}\n db = shelve.open('storage.db', 'r')\n try:\n order_dict = db['confirmed_collect']\n except:\n print('not created')\n db.close()\n\n order_list = []\n for key in order_dict:\n order_collected = order_dict.get(key)\n if order_collected.get_general_location() == 'East':\n order_list.append(order_collected)\n\n return render_template('Outlet_East.html', order_list=order_list)\n\n\[email protected]('/Outlet_West')\ndef Outlet_West():\n order_dict = {}\n db = shelve.open('storage.db', 'r')\n location_db = shelve.open(('location.db', 'c'))\n try:\n order_dict = db['confirmed_collect']\n location = db['Locations']\n except:\n print('not created')\n db.close()\n\n order_list = []\n for key in order_dict:\n order = order_dict.get(key)\n if order.get_general_location() == 'West':\n order_list.append(order)\n\n return render_template('Outlet_West.html', order_list=order_list)\n\n\[email protected]('/deliverymen_update_status/<int:id>/', methods=['GET', 'POST'])\ndef deliverymen_update_status(id):\n deliverymen_update_status_form = deliverymen_status_update(request.form)\n if request.method == 'POST':\n users_dict = {}\n db = shelve.open('storage.db', 'w')\n print(deliverymen_update_status_form.name.data, deliverymen_update_status_form.status.data)\n users_dict = db['confirmed_delivered']\n user = users_dict.get(id)\n deliverymen_update_status_form.name.data = user.get_name()\n deliverymen_update_status_form.phone.data = user.get_phone()\n user.set_name(deliverymen_update_status_form.name.data)\n user.set_phone(deliverymen_update_status_form.phone.data)\n user.set_status(deliverymen_update_status_form.status.data)\n\n db['confirmed_delivered'] = users_dict\n db.close()\n\n return redirect(url_for('deliverymen_update_status.html', form=deliverymen_update_status_form))\n\n else:\n users_dict = {}\n db = shelve.open('storage.db', 'r')\n users_dict = db['confirmed_collect']\n db.close()\n\n user = users_dict.get(id)\n print(users_dict)\n print(user.get_name(), user.get_number())\n deliverymen_update_status_form.name.data = user.get_name()\n deliverymen_update_status_form.data = user.get_phone()\n print(deliverymen_update_status_form.name.data)\n print(deliverymen_update_status_form.number.data)\n\n return render_template('updateSelfCollection.html', form=deliverymen_update_status_form)\n\n\[email protected]('/deliverymen_update_profile/<int:id>/', methods=['GET', 'POST'])\ndef deliverymen_update_profile(id):\n deliverymen_update_profile_form = deliverymen_profile_update(request.form)\n if request.method == 'POST' and deliverymen_update_profile_form.validate():\n users_dict = {}\n db = shelve.open('storage.db', 'w')\n users_dict = db['Deliverymen']\n\n user = users_dict.get(id)\n user.set_first_name(deliverymen_update_profile_form.first_name.data)\n user.set_last_name(deliverymen_update_profile_form.last_name.data)\n user.set_gender(deliverymen_update_profile_form.gender.data)\n user.set_email(deliverymen_update_profile_form.email.data)\n user.set_contact_no(deliverymen_update_profile_form.contact_no.data)\n user.set_regions(deliverymen_update_profile_form.regions.data)\n user.set_remarks(deliverymen_update_profile_form.remarks.data)\n\n db['Deliverymen'] = users_dict\n db.close()\n\n session['Deliverymen_Profile_updated'] = user.get_first_name() + ' ' + user.get_last_name()\n\n return redirect(url_for('qing.DeliverymenProfile'))\n else:\n users_dict = {}\n db = shelve.open('storage.db', 'r')\n users_dict = db['Deliverymen']\n db.close()\n\n user = users_dict.get(id)\n deliverymen_update_profile_form.first_name.data = user.get_first_name()\n deliverymen_update_profile_form.last_name.data = user.get_last_name()\n deliverymen_update_profile_form.gender.data = user.get_gender()\n deliverymen_update_profile_form.email.data = user.get_email()\n deliverymen_update_profile_form.contact_no.data = user.get_contact_no()\n deliverymen_update_profile_form.regions.data = user.get_regions()\n deliverymen_update_profile_form.remarks.data = user.get_remarks()\n\n return render_template('deliverymen_update_profile.html', form=deliverymen_update_profile_form)\n\n\[email protected]('/deliverymen_orders')\ndef deliverymen_orders():\n email = session.get('current')\n db = shelve.open('storage.db', 'r')\n deliverymen_login = db[\"Deliverymen_login\"]\n assign_orders = db['assignDeliverymen']\n current_id = deliverymen_login.get(email)\n print(current_id)\n orders_list = assign_orders.get(current_id)\n print(orders_list)\n return render_template('ordersAssigned(deliveryman).html', orders_list=orders_list)\n\n\[email protected]('/DeliverymenProfile', methods=['GET', 'POST'])\ndef DeliverymenProfile():\n email = session.get('current')\n db = shelve.open('storage.db', 'r')\n deliverymen_login = db[\"Deliverymen_login\"]\n Deliverymen_dict = db['Deliverymen']\n current_id = deliverymen_login.get(email)\n Deliverymen_list = []\n Deliverymen = Deliverymen_dict.get(current_id)\n Deliverymen_list.append(Deliverymen)\n return render_template('DeliverymenProfile.html', users_list=Deliverymen_list)\n" }, { "alpha_fraction": 0.4124700129032135, "alphanum_fraction": 0.4124700129032135, "avg_line_length": 28.85714340209961, "blob_id": "eeeb9cf34f007cfe6deb4a03e07673f578b32290", "content_id": "319e9b6be3189603acb29963e61d5732795510d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 417, "license_type": "no_license", "max_line_length": 99, "num_lines": 14, "path": "/static/js/filter.js", "repo_name": "frake17/SSP_project", "src_encoding": "UTF-8", "text": "$(document).ready(function () {\n\n $('#filters :checkbox').click(function () {\n if ($('input:checkbox:checked').length) {\n $('.shop-item').hide();\n $('input:checkbox:checked').each(function () {\n $('.shop-item[data-' + $(this).prop('name') + '*=\"' + $(this).val() + '\"]').show();\n });\n } else {\n $(\".shop-item\").show();\n }\n });\n\n});" }, { "alpha_fraction": 0.5507900714874268, "alphanum_fraction": 0.5575620532035828, "avg_line_length": 35.875, "blob_id": "252877233724e673b244eb9ee2a817016213aef6", "content_id": "3c9c765c5233e719ea2752f905403a350a6839f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 886, "license_type": "no_license", "max_line_length": 94, "num_lines": 24, "path": "/templates/restock_summary.html", "repo_name": "frake17/SSP_project", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n{% block title %}Home{% endblock %}\n\n{% block head%}\n<link href=\"../../static/css/css.css\" rel=\"stylesheet\">\n{% endblock %}\n\n{% block content %}\n<div class=\"fluid-container\">\n <h1 style=\"text-align: center;\">Order summary</h1>\n <div class=\"summary\">\n <h2>Current order</h2>\n <p><span style=\"font-weight: bold;\">Email: </span>{{current.get_email()}}</p>\n <p><span style=\"font-weight: bold;\">Order quantity: </span>{{current.get_order()}}</p>\n <h2>All orders</h2>\n {% for item in item_list %}\n <p><span style=\"font-weight: bold;\">Order Id: </span>{{item.get_id()}}</p>\n <p><span style=\"font-weight: bold;\">Email: </span> {{item.get_email()}}</p>\n <p><span style=\"font-weight: bold;\">Order quantity: </span> {{item.get_order()}}</p>\n <br>\n {% endfor %}\n </div>\n</div>\n{% endblock %}\n\n" }, { "alpha_fraction": 0.620192289352417, "alphanum_fraction": 0.6221153736114502, "avg_line_length": 25, "blob_id": "3f23b1def775cf507b4b021d06276b893a13b097", "content_id": "a694245cacce112951429e9263a64cc575e20523", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1040, "license_type": "no_license", "max_line_length": 67, "num_lines": 40, "path": "/Location.py", "repo_name": "frake17/SSP_project", "src_encoding": "UTF-8", "text": "class Location:\n count_id = 0\n\n def __init__(self, neighbourhood, address, area, availability):\n Location.count_id += 1\n self.__location_id = Location.count_id\n self.__neighbourhood = neighbourhood\n self.__address = address\n self.__area = area\n self.__availability = availability\n\n def get_location_id(self):\n return self.__location_id\n\n def get_neighbourhood(self):\n return self.__neighbourhood\n\n def get_address(self):\n return self.__address\n\n def get_area(self):\n return self.__area\n\n def get_availability(self):\n return self.__availability\n\n def set_location_id(self, location_id):\n self.__location_id = location_id\n\n def set_neighbourhood(self, neighbourhood):\n self.__neighbourhood = neighbourhood\n\n def set_address(self, address):\n self.__address = address\n\n def set_area(self, area):\n self.__area = area\n\n def set_availability(self, availability):\n self.__availability = availability\n" }, { "alpha_fraction": 0.5855910181999207, "alphanum_fraction": 0.586650550365448, "avg_line_length": 31.38725471496582, "blob_id": "f8c1b61e76a940abbbcc7940c73d3ad2cbbf6c05", "content_id": "a858ed7cb8470d8fd4baae4d41c1bc33fcddbe92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6607, "license_type": "no_license", "max_line_length": 112, "num_lines": 204, "path": "/alicia.py", "repo_name": "frake17/SSP_project", "src_encoding": "UTF-8", "text": "import shelve\n\nfrom flask import Flask, render_template, request, redirect, url_for, session, Blueprint\n\nimport User\nfrom Forms import CreateUserForm, SearchUserForm\n\nUPLOAD_FOLDER = 'static/img/uploaded'\nALLOWED_EXTENSIONS = {'png'}\n\nalicia = Flask(__name__)\nalicia.secret_key = 'any_random_string'\nalicia.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\nalicia.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\nalicia.config[\"SESSION_PERMANENT\"] = False\nalicia = Blueprint('alicia', __name__, template_folder='templates')\n\n\[email protected]('/temp_record', methods=['GET', 'POST'])\ndef create_user():\n create_user_form = CreateUserForm(request.form)\n\n locations_dict = {}\n db = shelve.open('location.db', 'r')\n locations_dict = db['Locations']\n db.close()\n\n locations_list = []\n for key in locations_dict:\n location = locations_dict.get(key)\n locations_list.append(location)\n\n if request.method == 'POST' and create_user_form.validate():\n users_dict = {}\n count_dict = {}\n db = shelve.open('storage.db', 'c')\n\n try:\n users_dict = db['Users_temp']\n count_dict = db['Count']\n except:\n print(\"Error in retrieving Users from storage.db.\")\n\n user = User.Temp(request.form['location'], create_user_form.date.data,\n create_user_form.cust_ic.data, create_user_form.cust_no.data,\n create_user_form.temp.data,\n create_user_form.time_enter.data, create_user_form.time_leave.data, 'in')\n users_dict[user.get_user_id()] = user\n db['Users_temp'] = users_dict\n\n session['user_created'] = user.get_cust_ic()\n\n print(request.form['location'], count_dict)\n if request.form['location'] in count_dict:\n count = count_dict.get(request.form['location'])\n count += 1\n count_dict[request.form['location']] = count\n else:\n count_dict[request.form['location']] = 1\n\n db['Count'] = count_dict\n\n db.close()\n\n return redirect(url_for('alicia.create_user'))\n return render_template('temp_record.html', form=create_user_form, locations_list=locations_list)\n\n\[email protected]('/temp_search_user', methods=['GET', 'POST'])\ndef search_user():\n search_user_form = SearchUserForm(request.form)\n search_list = []\n count = 0\n db = shelve.open('location.db', 'r')\n locations_dict = db['Locations']\n db.close()\n db = shelve.open('storage.db', 'c')\n\n locations_list = []\n for key in locations_dict:\n location = locations_dict.get(key)\n locations_list.append(location)\n\n if request.method == \"POST\":\n users_dict = {}\n\n try:\n users_dict = db['Users_temp']\n db.close()\n\n except IOError:\n print(\"An error occurred trying to read from storage.db\")\n\n except:\n print(\"An unknown error has occurred\")\n\n if request.form['btn'] == \"Retrieve\":\n for key in users_dict:\n search = users_dict.get(key)\n if request.form['location'] == search.get_outlet():\n if search_user_form.search_date.data == search.get_date():\n search_list.append(search)\n\n count = 0\n for a in search_list:\n if a.get_status() == \"in\":\n count += 1\n\n elif request.form['btn'] == \"Search\":\n for key in users_dict:\n search = users_dict.get(key)\n if search_user_form.search_cust.data == search.get_cust_ic():\n search_list.append(search)\n\n return render_template('temp_search_user.html', form=search_user_form, search_list=search_list, count=count,\n locations_list=locations_list)\n\n\[email protected]('/temp_updateUser/<int:id>/', methods=['GET', 'POST'])\ndef update_user(id):\n update_user_form = CreateUserForm(request.form)\n if request.method == 'POST' and update_user_form.validate():\n users_dict = {}\n\n try:\n db = shelve.open('storage.db', 'w')\n users_dict = db['Users_temp']\n\n except IOError:\n print(\"An error occurred trying to write in storage.db\")\n\n except:\n print(\"An unknown error has occurred\")\n\n user = users_dict.get(id)\n user.set_date(update_user_form.date.data)\n user.set_cust_ic(update_user_form.cust_ic.data)\n user.set_cust_no(update_user_form.cust_no.data)\n user.set_temp(update_user_form.temp.data)\n user.set_time_enter(update_user_form.time_enter.data)\n user.set_time_leave(update_user_form.time_leave.data)\n user.set_status(\"left\")\n\n db['Users_temp'] = users_dict\n db.close()\n\n session['user_updated'] = user.get_cust_ic()\n\n return redirect(url_for('alicia.search_user'))\n\n else:\n users_dict = {}\n try:\n db = shelve.open('storage.db', 'r')\n users_dict = db['Users_temp']\n db.close()\n\n except IOError:\n print(\"An error occurred trying to read from storage.db\")\n\n except:\n print(\"An unknown error has occurred\")\n\n user = users_dict.get(id)\n update_user_form.date.data = user.get_date()\n update_user_form.cust_ic.data = user.get_cust_ic()\n update_user_form.cust_no.data = user.get_cust_no()\n update_user_form.temp.data = user.get_temp()\n update_user_form.time_enter.data = user.get_time_enter()\n update_user_form.time_leave.data = user.get_time_leave()\n user.get_status()\n\n return render_template('temp_updateUser.html', form=update_user_form)\n\n\[email protected]('/temp_chart')\ndef temp_chart():\n locations_dict = {}\n locations_db = shelve.open('location.db', 'r')\n locations_dict = locations_db['Locations']\n locations_db.close()\n\n locations_label = []\n for line in locations_dict:\n location = locations_dict.get(line)\n locations_label.append(location.get_address())\n print(locations_label)\n\n count_dict = {}\n count_db = shelve.open('storage.db', 'r')\n count_dict = count_db['Count']\n print(count_dict)\n count_db.close()\n\n for location in locations_label:\n if location not in count_dict:\n count = 0\n count_dict[location] = count\n\n count_data = []\n for k in count_dict:\n count_data.append(count_dict[k])\n\n return render_template('chart.html', locations_label=locations_label, count_data=count_data)\n" }, { "alpha_fraction": 0.3333333432674408, "alphanum_fraction": 0.3333333432674408, "avg_line_length": 7, "blob_id": "0960b36102e12afbd2ab213b463c5ead607fe0b1", "content_id": "c98c039fd3396ef269e1ac85afaebeddf7a100ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9, "license_type": "no_license", "max_line_length": 7, "num_lines": 1, "path": "/README.md", "repo_name": "frake17/SSP_project", "src_encoding": "UTF-8", "text": "'# SSP' \n" }, { "alpha_fraction": 0.4142581820487976, "alphanum_fraction": 0.4192127585411072, "avg_line_length": 34.27184295654297, "blob_id": "9142e76cea3a4c8ac9e99309bd011200d9549e68", "content_id": "5c70f24719c2539de8c355cb49a8ca5f0979bfe3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 3633, "license_type": "no_license", "max_line_length": 120, "num_lines": 103, "path": "/templates/retrieveUsers(admin).html", "repo_name": "frake17/SSP_project", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n{% block title %}Retrieve Users{% endblock %}\n\n{% block content %}\n{% if 'user_deleted' in session %}\n<div class=\"alert alert-danger alert-dismissible\">\n <button class=\"close\" data-dismiss=\"alert\" type=\"button\">&times;</button>\n {{ session.pop('user_deleted', None) }} was deleted.\n</div>\n{% endif %}\n<h1 class=\"display-4\">Retrieve Users</h1>\n\n<div>\n {% if count == 0 %}\n <p>There are no users.</p>\n {% elif count == 1 %}\n <p>There is 1 user.</p>\n {% else %}\n <p>There are {{ count }} users.</p>\n {% endif %}\n <ul style=\"float:right; padding-right:116px;\" class=\"navbar-nav ml-auto mr-1\"><li class=\"nav-item dropdown\">\n <a class=\"nav-link dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\" id=\"user\">\n Sort by\n </a>\n <div class=\"dropdown-menu\">\n\n <a class=\"dropdown-item\" href=#>Latest login activity</a>\n <a class=\"dropdown-item\" href=#>Oldest login activity</a>\n <a class=\"dropdown-item\" href=#>New user</a>\n <a class=\"dropdown-item\" href=#>Old user</a>\n\n </div>\n </li></ul>\n</div>\n\n<div>\n <table class=\"table table-striped\">\n <thead>\n <tr>\n <th>First Name</th>\n <th>Last Name</th>\n <th>Email</th>\n <th>Last login</th>\n <th></th>\n <th></th>\n\n </tr>\n </thead>\n <tbody>\n {% for user in users_list %}\n\n <tr>\n <td>{{ user.get_first_name() }}</td>\n <td>{{ user.get_last_name() }}</td>\n <td>{{ user.get_email() }}</td>\n <td>26 May 2021</td>\n <td><button class=\"btn btn-warning\" data-toggle=\"modal\"\n type=\"button\">\n Disable\n </button></td>\n <td>\n <form action=\"{{url_for('elly.delete_user', email=user.get_email())}}\" method=\"POST\">\n <button class=\"btn btn-danger\" data-target=\"#myModal_{{user.get_user_id()}}\" data-toggle=\"modal\"\n type=\"button\">\n Delete\n </button>\n\n <!-- The Modal -->\n <div class=\"modal\" id=\"myModal_{{user.get_user_id()}}\">\n <div class=\"modal-dialog\">\n <div class=\"modal-content\">\n\n <!-- Modal Header -->\n <div class=\"modal-header\">\n <h4 class=\"modal-title\">Delete Confirmation</h4>\n <button class=\"close\" data-dismiss=\"modal\" type=\"button\">&times;</button>\n </div>\n\n <!-- Modal body -->\n <div class=\"modal-body\">\n Are you sure you want to delete {{user.get_first_name()}} {{user.get_last_name()}}?\n </div>\n\n <!-- Modal footer -->\n <div class=\"modal-footer\">\n <input class=\"btn btn-danger\" type=\"submit\" value=\"Delete\">\n <button class=\"btn btn-secondary\" data-dismiss=\"modal\" type=\"button\">Cancel</button>\n </div>\n\n </div>\n </div>\n </div>\n\n </form>\n\n </td>\n\n </tr>\n {% endfor %}\n </tbody>\n </table>\n</div>\n{% endblock %}\n" }, { "alpha_fraction": 0.5739790201187134, "alphanum_fraction": 0.5753180384635925, "avg_line_length": 22.46073341369629, "blob_id": "e87f5522446ed176d67536f1dd1996c1dc8dedf7", "content_id": "9cde7924059481047d1d30c7944d06b750e1b1ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4481, "license_type": "no_license", "max_line_length": 93, "num_lines": 191, "path": "/User.py", "repo_name": "frake17/SSP_project", "src_encoding": "UTF-8", "text": "class User:\n count_id = 0\n\n def __init__(self, first_name, last_name, email, password):\n User.count_id += 1\n self.__user_id = User.count_id\n self.__first_name = first_name\n self.__last_name = last_name\n self.__email = email\n self.__password = password\n\n def get_user_id(self):\n return self.__user_id\n\n def get_first_name(self):\n return self.__first_name\n\n def get_last_name(self):\n return self.__last_name\n\n def get_email(self):\n return self.__email\n\n def get_password(self):\n return self.__password\n\n def set_user_id(self, user_id):\n self.__user_id = user_id\n\n def set_first_name(self, first_name):\n self.__first_name = first_name\n\n def set_last_name(self, last_name):\n self.__last_name = last_name\n\n def set_email(self, email):\n self.__email = email\n\n def set_password(self, password):\n self.__password = password\n\n\nclass Login:\n def __init__(self, email, password):\n self.__email = email\n self.__password = password\n\n def get_email(self):\n return self.__email\n\n def get_password(self):\n return self.__password\n\n def set_email(self, email):\n self.__email = email\n\n def set_password(self, password):\n self.__password = password\n\n\nclass Deliverymen:\n count_id = 0\n\n def __init__(self, first_name, last_name, email, gender, contact_no, regions, remarks):\n Deliverymen.count_id += 1\n self.__Deliverymen_id = Deliverymen.count_id\n self.__first_name = first_name\n self.__last_name = last_name\n self.__gender = gender\n self.__email = email\n self.__contact_no = contact_no\n self.__regions = regions\n self.__remarks = remarks\n\n def get_Deliverymen_id(self):\n return self.__Deliverymen_id\n\n def get_first_name(self):\n return self.__first_name\n\n def get_last_name(self):\n return self.__last_name\n\n def get_gender(self):\n return self.__gender\n\n def get_email(self):\n return self.__email\n\n def get_contact_no(self):\n return self.__contact_no\n\n def get_regions(self):\n return self.__regions\n\n def get_remarks(self):\n return self.__remarks\n\n def set_Deliverymen_id(self, Deliverymen_id):\n self.__Deliverymen_id = Deliverymen_id\n\n def set_first_name(self, first_name):\n self.__first_name = first_name\n\n def set_last_name(self, last_name):\n self.__last_name = last_name\n\n def set_gender(self, gender):\n self.__gender = gender\n\n def set_email(self, email):\n self.__email = email\n\n def set_contact_no(self, contact_no):\n self.__contact_no = contact_no\n\n def set_regions(self, regions):\n self.__regions = regions\n\n def set_remarks(self, remarks):\n self.__remarks = remarks\n\n\nclass Temp:\n count_id = 0\n\n def __init__(self, outlet, date, cust_ic, cust_no, temp, time_enter, time_leave, status):\n User.count_id += 1\n self.__user_id = User.count_id\n self.__outlet = outlet\n self.__date = date\n self.__cust_ic = cust_ic\n self.__cust_no = cust_no\n self.__temp = temp\n self.__time_enter = time_enter\n self.__time_leave = time_leave\n self.__status = status\n\n def set_user_id(self, user_id):\n self.__user_id = user_id\n\n def set_outlet(self, outlet):\n self.__outlet = outlet\n\n def set_date(self, date):\n self.__date = date\n\n def set_cust_ic(self, cust_ic):\n self.__cust_ic = cust_ic\n\n def set_cust_no(self, cust_no):\n self.__cust_no = cust_no\n\n def set_temp(self, temp):\n self.__temp = temp\n\n def set_time_enter(self, time_enter):\n self.__time_enter = time_enter\n\n def set_time_leave(self, time_leave):\n self.__time_leave = time_leave\n\n def set_status(self, status):\n self.__status = status\n\n def get_user_id(self):\n return self.__user_id\n\n def get_outlet(self):\n return self.__outlet\n\n def get_date(self):\n return self.__date\n\n def get_cust_ic(self):\n return self.__cust_ic\n\n def get_cust_no(self):\n return self.__cust_no\n\n def get_temp(self):\n return self.__temp\n\n def get_time_enter(self):\n return self.__time_enter\n\n def get_time_leave(self):\n return self.__time_leave\n\n def get_status(self):\n return self.__status\n" }, { "alpha_fraction": 0.547292172908783, "alphanum_fraction": 0.5494851469993591, "avg_line_length": 22.101322174072266, "blob_id": "56f985235f76ddb8dfd3524cadb5e668a22de7ef", "content_id": "9f30f960aca566df24c52150d41e05629021473c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10488, "license_type": "no_license", "max_line_length": 117, "num_lines": 454, "path": "/item.py", "repo_name": "frake17/SSP_project", "src_encoding": "UTF-8", "text": "class Stock_item:\n count_id = 0\n quantity = 0\n\n def __init__(self, stock_name, price, origin, weight, dietary, ingre, description, amt_of_stock, category, brand,\n unit, stock_unit):\n self.__amount = 0\n self.__id = Stock_item.count_id\n self.__stock_name = stock_name\n self.__price = price\n self.__origin = origin\n self.__weight = weight\n self.__dietary = dietary\n self.__ingredients = ingre\n self.__description = description\n self.__amt_of_stock = amt_of_stock\n self.__stock_left = amt_of_stock\n self.__category = category\n self.__total = 0\n self.__brand = brand\n self.__unit = unit\n self.__default_suppliers = ''\n self.__stock_unit = stock_unit\n self.__per_box = 0\n self.__per_box_working = 0\n\n def get_per_box(self):\n return self.__per_box\n\n def get_stock_unit(self):\n return self.__stock_unit\n\n def get_default_suppliers(self):\n return self.__default_suppliers\n\n def get_unit(self):\n return self.__unit\n\n def get_id(self):\n return int(self.__id)\n\n def get_stock_name(self):\n return self.__stock_name\n\n def get_total(self):\n self.__total = self.__amount * int(self.__price)\n return self.__total\n\n def get_origin(self):\n return self.__origin\n\n def get_dietary(self):\n return self.__dietary\n\n def get_weight(self):\n return self.__weight\n\n def get_ingredients(self):\n return self.__ingredients\n\n def get_description(self):\n return self.__description\n\n def get_amt_of_stock(self):\n return self.__amt_of_stock\n\n def get_stock_left(self):\n return int(self.__stock_left)\n\n def get_percentage(self):\n print(self.__stock_left, self.__amt_of_stock)\n percentage = (int(self.__stock_left) / int(self.__amt_of_stock)) * 100\n return int(round(percentage))\n\n def get_cat(self):\n return self.__category\n\n def get_base_price(self):\n return self.__price\n\n def get_category(self):\n return self.__category\n\n def get_brand(self):\n return self.__brand\n\n def set_brand(self, brand):\n self.__brand = brand\n\n def set_stock_name(self, stock_name):\n self.__stock_name = stock_name\n\n def set_base_price(self, price):\n self.__price = price\n\n def set_origin(self, origin):\n self.__origin = origin\n\n def set_dietary(self, dietary):\n self.__dietary = dietary\n\n def set_weight(self, weight):\n self.__weight = weight\n\n def set_ingredients(self, ingredients):\n self.__ingredients = ingredients\n\n def set_description(self, description):\n self.__description = description\n\n def set_amt_of_stock(self, amt_of_stock):\n self.__amt_of_stock = amt_of_stock\n\n def set_stock_left(self, stock_left):\n self.__stock_left = stock_left\n\n def set_id(self, id):\n self.__id = id\n\n def set_cat(self, cat):\n self.__category = cat\n\n def set_unit(self, unit):\n self.__unit = unit\n\n def set_amount_empty(self):\n self.__amount = 0\n\n def set_default_supplier(self, supplier):\n self.__default_suppliers = supplier\n\n def set_stock_unit(self, stock_unit):\n self.__stock_unit = stock_unit\n\n def set_per_box(self, per_box):\n self.__per_box = per_box\n\n def add_amount(self):\n self.__amount += 1\n\n def minus(self):\n self.__amount -= 1\n\n def get_amount(self):\n return self.__amount\n\n def decrease_stock(self):\n value = float(self.__stock_left)\n if self.__stock_unit == 'Kg' or self.__stock_unit == 'L':\n value -= self.__weight\n self.__stock_left = value\n elif self.__stock_unit == 'boxes':\n stock_in_box = self.__per_box_working\n stock_in_box += 1/int(self.__per_box)\n if stock_in_box >= 1:\n print('test')\n self.__stock_left -= 1\n stock_in_box -= 1\n self.__per_box_working = stock_in_box\n self.__per_box_working = stock_in_box\n\n def increase_stock(self, amt):\n self.__stock_left += int(amt)\n if self.__stock_left > self.__amt_of_stock:\n self.__amt_of_stock = self.__stock_left\n\n\nclass Restock:\n count_id = 0\n\n def __init__(self, email, order_number):\n Restock.count_id += 1\n self.__id = Restock.count_id\n self.__email = email\n self.__order_number = order_number\n\n def get_id(self):\n return self.__id\n\n def get_email(self):\n return self.__email\n\n def get_order(self):\n return self.__order_number\n\n def set_email(self, email):\n self.__email = email\n\n def set_order(self, order):\n self.__order_number = order\n\n def set_id(self, id):\n self.__id = id\n\n\nclass Order_delivery:\n count_id = 0\n\n def __init__(self, name, number, postal, address, level, door_no, card_no, exp_date, cvv, card_type, location,\n remarks):\n Order_delivery.count_id += 1\n self.__id = Order_delivery.count_id\n self.__name = name\n self.__phone_no = number\n self.__postal = postal\n self.__address = address\n self.__level = level\n self.__door_no = door_no\n self.__card_no = card_no\n self.__exp_Date = exp_date\n self.__cvv = cvv\n self.__card = card_type\n self.__location = location\n self.__date = \"\"\n self.__remark = remarks\n self.__status = 'unassigned'\n self.__items = \"\"\n\n def get_name(self):\n return self.__name\n\n def get_remark(self):\n return self.__remark\n\n def get_location(self):\n return self.__location\n\n def get_phone(self):\n return self.__phone_no\n\n def get_postal(self):\n return self.__postal\n\n def get_address(self):\n return self.__address\n\n def get_level(self):\n return self.__level\n\n def get_door(self):\n return self.__door_no\n\n def get_card_no(self):\n return self.__card_no\n\n def get_exp_date(self):\n return self.__exp_Date\n\n def get_cvv(self):\n return self.__cvv\n\n def get_id(self):\n return self.__id\n\n def get_card(self):\n return self.__card\n\n def get_date(self):\n return self.__date\n\n def get_status(self):\n return self.__status\n\n def get_item(self):\n return self.__items\n\n def set_card(self, card):\n self.__card = card\n\n def set_id(self, id):\n self.__id = id\n\n def set_date(self, date):\n self.__date = date\n\n def set_name(self, name):\n self.__name = name\n\n def set_phone(self, phone):\n self.__phone_no = phone\n\n def set_postal(self, postal):\n self.__postal = postal\n\n def set_address(self, address):\n self.__address = address\n\n def set_level(self, level):\n self.__level = level\n\n def set_door_no(self, door):\n self.__door_no = door\n\n def set_exp(self, exp):\n self.__exp_Date = exp\n\n def set_ccv(self, cvv):\n self.__cvv = cvv\n\n def set_card_no(self, no):\n self.__card_no = no\n\n def set_location(self, location):\n self.__location = location\n\n def set_remark(self, remark):\n self.__remark = remark\n\n def set_status(self, status):\n self.__status = status\n\n def set_item(self, item):\n self.__items = item\n\n\nclass Order_self:\n count_id = 0\n\n def __init__(self, name, number, card_no, exp, cvv, card_type):\n Order_self.count_id += 1\n self.__id = Order_self.count_id\n self.__name = name\n self.__number = number\n self.__card_no = card_no\n self.__exp = exp\n self.__cvv = cvv\n self.__date = \"\"\n self.__location = \"\"\n self.__time = \"\"\n self.__card = card_type\n self.__status = 'not collected'\n self.__items = \"\"\n self.__general_location = ''\n\n def get_general_location(self):\n return self.__general_location\n\n def get_name(self):\n return self.__name\n\n def get_number(self):\n return self.__number\n\n def get_card_no(self):\n return self.__card_no\n\n def get_exp(self):\n return self.__exp\n\n def get_date(self):\n return self.__date\n\n def get_location(self):\n return self.__location\n\n def get_time(self):\n return self.__time\n\n def get_id(self):\n return self.__id\n\n def get_cvv(self):\n return self.__cvv\n\n def get_card(self):\n return self.__card\n\n def get_status(self):\n return self.__status\n\n def get_item(self):\n return self.__items\n\n def set_date(self, date):\n self.__date = date\n\n def set_location(self, location):\n self.__location = location\n\n def set_time(self, time):\n self.__time = time\n\n def set_card(self, card):\n self.__card = card\n\n def set_id(self, id):\n self.__id = id\n\n def set_name(self, name):\n self.__name = name\n\n def set_phone(self, phone):\n self.__number = phone\n\n def set_ccv(self, cvv):\n self.__cvv = cvv\n\n def set_card_no(self, no):\n self.__card_no = no\n\n def set_status(self, status):\n self.__status = status\n\n def set_item(self, item):\n self.__items = item\n\n def set_general_location(self, location):\n self.__general_location = location\n\n\nclass Supplier:\n def __init__(self, name, email, phone, location):\n self.__id = 1\n self.__name = name\n self.__email = email\n self.__phone = phone\n self.__location = location\n self.__supplier_for_stock = \"\"\n\n def get_id(self):\n return self.__id\n\n def get_name(self):\n return self.__name\n\n def get_email(self):\n return self.__email\n\n def get_phone(self):\n return self.__phone\n\n def get_location(self):\n return self.__location\n\n def get_stock(self):\n return self.__supplier_for_stock\n\n def set_stock(self, stock):\n self.__supplier_for_stock = stock\n\n def set_id(self, id):\n self.__id = id\n\n def set_name(self, name):\n self.__name = name\n\n def set_number(self, number):\n self.__number = number\n\n def set_email(self, email):\n self.__email = email\n\n def set_location(self, location):\n self.__location = location\n" }, { "alpha_fraction": 0.592268705368042, "alphanum_fraction": 0.5933226943016052, "avg_line_length": 34.06993103027344, "blob_id": "ed472b8abcec203c46769cd4a49b683d6cd8c0aa", "content_id": "080b6fd7592139fb03151c45e7775752b3445974", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 35104, "license_type": "no_license", "max_line_length": 120, "num_lines": 1001, "path": "/kin.py", "repo_name": "frake17/SSP_project", "src_encoding": "UTF-8", "text": "import os\nimport shelve\nfrom datetime import timedelta, datetime\n\nfrom flask import Flask, render_template, request, redirect, url_for, session, flash, Blueprint, current_app\n\nimport item\nfrom Forms import Item, Order, self_collect, Supplier, self_collection_update\n\nUPLOAD_FOLDER = 'static/img/uploaded'\nALLOWED_EXTENSIONS = {'png'}\n\nkin = Flask(__name__)\nkin.secret_key = 'any_random_string'\nkin.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\nkin.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\nkin.config[\"SESSION_PERMANENT\"] = False\nkin = Blueprint('kin', __name__, template_folder='templates', static_folder='static')\n\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\[email protected]('/stock', defaults={'sort': None}, methods=['GET', 'POST'])\[email protected]('/stock/<sort>', methods=['GET', 'POST'])\ndef stock(sort):\n item_dict = {}\n low_on_stock = []\n percentage = 20\n db = shelve.open('storage.db', 'c')\n try:\n item_dict = db['item']\n percentage = db['percentage']\n except:\n print(\"Error in retrieving Users from storage.db.\")\n\n if request.method == 'POST':\n percentage = int(request.form['percentage'])\n db['percentage'] = percentage\n\n item_list = []\n for key in item_dict:\n items = item_dict.get(key)\n item_list.append(items)\n if items.get_percentage() <= percentage:\n low_on_stock.append(items)\n if sort == 'alphabet':\n item_list.sort(key=lambda x: x.get_stock_name())\n elif sort == 'LTH':\n item_list.sort(key=lambda x: x.get_stock_left())\n elif sort == 'HTL':\n item_list.sort(key=lambda x: x.get_stock_left(), reverse=True)\n db['low_stock_list'] = low_on_stock\n\n db.close()\n return render_template('stock.html', item_list=item_list, percentage=percentage, low_on_stock=low_on_stock,\n count=len(low_on_stock))\n\n\[email protected]('/shop_admin', defaults={'sort': None})\[email protected]('/shop_admin/<sort>')\ndef shop(sort):\n items_dict = {}\n try:\n db = shelve.open('storage.db', 'r')\n items_dict = db['item']\n db.close()\n except:\n print(\"Error in retrieving Users from storage.db.\")\n\n item_list = []\n for key in items_dict:\n items = items_dict.get(key)\n item_list.append(items)\n if sort == 'alphabet':\n item_list.sort(key=lambda x: x.get_stock_name())\n elif sort == 'Low_to_high_price':\n item_list.sort(key=lambda x: x.get_base_price())\n elif sort == 'High_to_low_price':\n item_list.sort(key=lambda x: x.get_base_price(), reverse=True)\n elif sort == 'brand_AtoZ':\n item_list.sort(key=lambda x: x.get_brand())\n elif sort == 'brand_ZtoA':\n item_list.sort(key=lambda x: x.get_brand(), reverse=True)\n return render_template('shop_admin.html', item_list=item_list)\n\n\[email protected]('/shop_cus', defaults={'sort': None})\[email protected]('/shop_cus/<sort>')\ndef shop_cus(sort):\n items_dict = {}\n try:\n db = shelve.open('storage.db', 'r')\n items_dict = db['item']\n db.close()\n except:\n print(\"Error in retrieving Users from storage.db.\")\n\n item_list = []\n for key in items_dict:\n items = items_dict.get(key)\n item_list.append(items)\n\n if sort == 'alphabet':\n item_list.sort(key=lambda x: x.get_stock_name())\n elif sort == 'Low_to_high_price':\n item_list.sort(key=lambda x: x.get_base_price())\n elif sort == 'High_to_low_price':\n item_list.sort(key=lambda x: x.get_base_price(), reverse=True)\n elif sort == 'brand_AtoZ':\n item_list.sort(key=lambda x: x.get_brand())\n elif sort == 'brand_ZtoA':\n item_list.sort(key=lambda x: x.get_brand(), reverse=True)\n return render_template('shop_cus.html', item_list=item_list)\n\n\[email protected]('/shop_display/<int:id>')\ndef display(id):\n db = shelve.open('storage.db', 'r')\n item_dict = db['item']\n current_item = item_dict.get(id)\n db.close()\n return render_template('shop_item_display.html', item=current_item)\n\n\[email protected]('/cart/<int:product_id>', methods=['POST', 'GET']) # done with {user:{id:item}}\ndef add_to_cart(product_id):\n cart_dict = {}\n email_cart_dict = {}\n db = shelve.open('storage.db', 'c')\n try:\n email = session.get('current')\n except:\n print('no email in session')\n return url_for('login')\n\n try:\n email_cart_dict = db['Cart']\n if email in email_cart_dict:\n cart_dict = email_cart_dict.get(email)\n except:\n print('das')\n\n shop_dict = db['item']\n\n item_list = [] # get object of stocks\n for key in shop_dict:\n user = shop_dict.get(key)\n item_list.append(user)\n\n for item in item_list: # adding to cart\n id = item.get_id()\n if id in cart_dict:\n item_cart = cart_dict.get(product_id)\n if item.get_stock_left() >= (item_cart.get_amount() + 1):\n print('***', item.get_stock_left(), item.get_stock_name())\n item_cart.add_amount()\n session['cart_added'] = item_cart.get_stock_name()\n break\n else:\n session['not_enough'] = item_cart.get_stock_name()\n else:\n if id == product_id:\n if item.get_stock_left() >= 1:\n item.add_amount()\n cart_dict[item.get_id()] = item\n session['cart_added'] = item.get_stock_name()\n break\n else:\n session['not_enough'] = item.get_stock_name()\n\n email_cart_dict[email] = cart_dict\n db['Cart'] = email_cart_dict\n db.close()\n\n return redirect(url_for('kin.shop_cus'))\n\n\[email protected]('/add/<int:product_id>')\ndef add_cart_item(product_id):\n cart_dict = {}\n email_cart_dict = {}\n item_dict = {}\n db = shelve.open('storage.db', 'c')\n email = session.get('current')\n\n try:\n email_cart_dict = db['Cart']\n item_dict = db['item']\n if email in email_cart_dict:\n cart_dict = email_cart_dict.get(email)\n except:\n print('das')\n\n stock_item = item_dict.get(product_id)\n item = cart_dict.get(product_id)\n if stock_item.get_stock_left() > item.get_amount():\n item.add_amount()\n else:\n session['not_enough'] = item.get_stock_name()\n print('not enough stock')\n email_cart_dict[email] = cart_dict\n db['Cart'] = email_cart_dict\n db.close()\n\n return redirect(url_for('kin.cart'))\n\n\[email protected]('/minus/<int:product_id>')\ndef minus_cart_item(product_id):\n cart_dict = {}\n email_cart_dict = {}\n db = shelve.open('storage.db', 'c')\n email = session.get('current')\n\n try:\n email_cart_dict = db['Cart']\n if email in email_cart_dict:\n cart_dict = email_cart_dict.get(email)\n except:\n print('das')\n\n item = cart_dict.get(product_id)\n if item.get_amount() > 0:\n item.minus()\n\n if item.get_amount() == 0:\n cart_dict.pop(product_id)\n\n email_cart_dict[email] = cart_dict\n db['Cart'] = email_cart_dict\n db.close()\n\n return redirect(url_for('kin.cart'))\n\n\[email protected]('/cart')\ndef cart():\n cart_list = {}\n email_cart_dict = {}\n db = shelve.open('storage.db', 'c')\n item_list = []\n total = 0\n try:\n email = session.get('current')\n email_cart_dict = db['Cart']\n cart_list = email_cart_dict.get(email)\n for key in cart_list:\n user = cart_list.get(key)\n price = user.get_total()\n total += int(price)\n item_list.append(user)\n except:\n print('error')\n session['empty_cart'] = 'cart is empty'\n return redirect(url_for('kin.shop_cus'))\n session['Total_price'] = total\n\n return render_template('cart.html', item_list=item_list, price=total)\n\n\[email protected]('/clear_cart')\ndef clear_cart():\n email = session.get('current')\n db = shelve.open('storage.db', 'c')\n try:\n email_cart_dict = db['Cart']\n email_cart_dict[email] = {}\n db['Cart'] = email_cart_dict\n except:\n print('email not in dict')\n\n return redirect(url_for('kin.shop_cus'))\n\n\[email protected]('/delivery', methods=['POST', 'GET'])\ndef delivery_date():\n total = session.get('Total_price', None)\n date_now = datetime.now()\n max_date = date_now + timedelta(60)\n if total > 100:\n total = total\n else:\n total = total + 3\n if request.method == 'POST':\n date = request.form['date']\n input_date = datetime(int(date.split('-')[0]), int(date.split('-')[1]), int(date.split('-')[2]))\n if input_date > max_date:\n session['invalid_date'] = date + ' is invalid. Please choose another date'\n redirect(url_for('kin.delivery_date'))\n elif input_date < date_now:\n session['invalid_date'] = date + ' is invalid. Please choose another date'\n redirect(url_for('kin.delivery_date'))\n else:\n session['date'] = date\n return redirect(url_for('kin.delivery_order_details'))\n session['Total_price'] = total\n return render_template('delivery_date.html', total=total)\n\n\[email protected]('/self-collect', methods=['POST', 'GET'])\ndef collect_date_location():\n total = session.get('Total_price', None)\n db = shelve.open('location.db', 'c')\n locations_dict = db['Locations']\n locations_list = []\n for key in locations_dict:\n location = locations_dict.get(key)\n locations_list.append(location)\n date_now = datetime.now()\n max_date = date_now + timedelta(30)\n date_now_hour = date_now.hour\n\n if request.method == 'POST':\n date = request.form['date']\n input_date = datetime(int(date.split('-')[0]), int(date.split('-')[1]), int(date.split('-')[2]))\n time = request.form['time']\n input_hour = time[0]\n print(input_date, max_date)\n if input_date > max_date:\n session['invalid_date'] = date + ' is invalid. Please choose another date'\n redirect(url_for('kin.collect_date_location'))\n elif input_date == date_now:\n if input_hour <= date_now.hour:\n session['invalid_time'] = input_hour + ' is invalid. Please choose another timing'\n redirect(url_for('kin.collect_date_location'))\n elif input_date < date_now:\n session['invalid_date'] = date + ' is invalid. Please choose another date'\n redirect(url_for('kin.collect_date_location'))\n else:\n location = request.form['location']\n session['date'] = date\n session['time'] = time\n session['location'] = location\n return redirect(url_for('kin.self_collect_order_details'))\n session['Total_price'] = total\n return render_template('self_collect_details.html', total=total, stores=locations_list)\n\n\[email protected]('/order', methods=['GET', 'POST'])\ndef delivery_order_details():\n count = 1\n date = session.get('date', None)\n create_order = Order(request.form)\n if request.method == 'POST' and create_order.validate():\n users_dict = {}\n db = shelve.open('storage.db', 'c')\n try:\n users_dict = db['orders_delivery']\n while count in users_dict:\n count += 1\n except:\n print('Error in retrieving users from db')\n\n order_item = item.Order_delivery(create_order.name.data, create_order.number.data, create_order.postal.data,\n create_order.address.data, create_order.level.data,\n create_order.door_number.data, create_order.card_number.data,\n create_order.exp_date.data, create_order.cvv.data, create_order.card_type.data,\n create_order.general_location.data, create_order.remarks.data)\n order_item.set_card(create_order.card_type.data)\n order_item.set_id(count) # To set new Id\n order_item.set_date(date)\n session['current_id_delivery'] = count\n users_dict[order_item.get_id()] = order_item\n db['orders_delivery'] = users_dict\n db.close()\n\n return redirect(url_for('kin.delivery_summary'))\n return render_template('order_details_delivery.html', form=create_order)\n\n\[email protected]('/order_self', methods=['POST', 'GET'])\ndef self_collect_order_details():\n count = 1\n create_order_self = self_collect(request.form)\n date = session.get('date', None)\n location = session.get('location', None)\n time = session.get('time', None)\n if request.method == 'POST' and create_order_self.validate():\n users_dict = {}\n location_dict = {}\n db_location = shelve.open('location.db', 'c')\n db = shelve.open('storage.db', 'c')\n try:\n users_dict = db['orders_self']\n location_dict = db_location['Locations']\n while count in users_dict:\n count += 1\n except:\n print('error')\n order_item = item.Order_self(create_order_self.name.data, create_order_self.number.data,\n create_order_self.card_number.data,\n create_order_self.exp_date.data, create_order_self.cvv.data,\n create_order_self.card_type.data)\n order_item.set_date(date)\n order_item.set_location(location)\n for key in location_dict:\n location_loop = location_dict.get(key)\n if location_loop.get_neighbourhood() + ', ' + location_loop.get_address() == location:\n general_location = location_loop.get_area()\n order_item.set_general_location(general_location)\n order_item.set_time(time)\n order_item.set_id(count)\n session['current_id_self'] = count\n users_dict[order_item.get_id()] = order_item\n db['orders_self'] = users_dict\n db.close()\n\n return redirect(url_for('kin.self_collect_summary'))\n\n return render_template('order_details_collect.html', form=create_order_self)\n\n\[email protected]('/summary')\ndef delivery_summary():\n email = session.get('current')\n total = session.get('Total_price')\n order_list = {} # store order\n item_dict = {} # get dict of stocks\n item_list = [] # for displaying in html\n\n db = shelve.open('storage.db', 'c')\n order_list = db['orders_delivery']\n item_dict = db['item']\n email_cart_dict = db['Cart']\n cart_dict = email_cart_dict.get(email)\n\n for key in order_list: # for displaying in html\n user = order_list.get(key)\n item_list.append(user)\n\n # for key in cart_dict:\n # item = cart_dict.get(key)\n # for i in range(item.get_amount()):\n # item.decrease_stock()\n # item.set_amount_empty()\n # item_dict[item.get_id()] = item\n\n current_id = session.get('current_id_delivery')\n current = order_list.get(current_id)\n current.set_item(cart_dict)\n\n db['item'] = item_dict\n db.close()\n\n return render_template('Order_delivery_confirmation.html', item_list=item_list, current=current, total=total)\n\n\[email protected]('/summary_self')\ndef self_collect_summary():\n email = session.get('current')\n total = session.get('Total_price')\n order_list = {} # store order\n item_dict = {} # get dict of stocks\n item_list = [] # for displaying in html (delete once intergrate with qing)\n\n db = shelve.open('storage.db', 'c')\n order_list = db['orders_self']\n item_dict = db['item']\n email_cart_dict = db['Cart']\n cart_dict = email_cart_dict.get(email)\n\n for key in order_list: # for displaying in html (delete once intergrate with qing)\n user = order_list.get(key)\n item_list.append(user)\n\n # for key in cart_dict:\n # item = cart_dict.get(key)\n # for i in range(item.get_amount()):\n # item.decrease_stock()\n # item.set_amount_empty()\n # item_dict[item.get_id()] = item\n\n current_id = session.get('current_id_self', None)\n current = order_list.get(current_id)\n current.set_item(cart_dict)\n\n db['item'] = item_dict\n db.close()\n\n return render_template('Order_collect_confirmation.html', item_list=item_list, current=current, total=total)\n\n\[email protected]('/summary_restock')\ndef restock_summary():\n order_list = {}\n clear_dict = {}\n item_dict = {}\n item_list = []\n db = shelve.open('storage.db', 'c')\n order_list = db['restock']\n db['Cart'] = clear_dict\n item_dict = db['item']\n\n for key in order_list:\n user = order_list.get(key)\n item_list.append(user)\n\n for key in item_dict:\n item = item_dict.get(key)\n item.set_amount_empty()\n db['item'] = item_dict\n\n current_id = session.get('current_id_restock', None)\n current = order_list.get(current_id)\n\n return render_template('restock_summary.html', item_list=item_list, current=current)\n\n\[email protected]('/Delete_order/<delivery_collect>/<int:id>')\ndef delete_order(delivery_collect, id):\n db = shelve.open('storage.db', 'c')\n if delivery_collect == 'delivery':\n order_dict = db['orders_delivery']\n order_dict.pop(id)\n db['orders_delivery'] = order_dict\n else:\n order_dict = db['orders_self']\n order_dict.pop(id)\n db['orders_self'] = order_dict\n db.close()\n return redirect(url_for('kin.shop_cus'))\n\n\[email protected]('/sent_order/<delivery_collect>/<int:id>')\ndef sent_order(delivery_collect, id):\n email = session.get('current')\n db = shelve.open('storage.db', 'c')\n email_cart_dict = db['Cart']\n item_dict = db['item']\n cart_dict = email_cart_dict.get(email)\n order_item = {}\n confirmed_delivery = {}\n confirmed_collect = {}\n try:\n confirmed_delivery = db['confirmed_delivery']\n confirmed_collect = db['confirmed_collect']\n except:\n print('No confirmed orders yet')\n for key in cart_dict:\n item = cart_dict.get(key)\n order_item[item.get_stock_name()] = item.get_amount()\n\n if delivery_collect == 'delivery':\n orders_delivery = db['orders_delivery']\n current_order = orders_delivery.get(id)\n current_order.set_item(order_item)\n confirmed_delivery[id] = current_order\n db['confirmed_delivery'] = confirmed_delivery\n db['orders_delivery'] = orders_delivery\n else:\n orders_collect = db['orders_self']\n current_order = orders_collect.get(id)\n current_order.set_item(order_item)\n confirmed_collect[id] = current_order\n db['confirmed_collect'] = confirmed_collect\n db['orders_self'] = orders_collect\n\n for key in cart_dict:\n item = cart_dict.get(key)\n for i in range(item.get_amount()):\n item.decrease_stock()\n item.set_amount_empty()\n item_dict[item.get_id()] = item\n\n email_cart_dict.pop(email)\n db['Cart'] = email_cart_dict\n db['item'] = item_dict\n db.close()\n return redirect(url_for('kin.shop_cus'))\n\n\[email protected]('/edit_delivery_order/<int:id>/<RSD>', methods=['POST', 'GET'])\ndef edit_order(id ,RSD):\n db = shelve.open('storage.db', 'c')\n update_order = Order(request.form)\n order_dict = {}\n if request.method == 'POST' and update_order.validate():\n order_dict = db['orders_delivery']\n\n current_order = order_dict.get(id)\n current_order.set_name(update_order.name.data)\n current_order.set_phone(update_order.number.data)\n current_order.set_postal(update_order.postal.data)\n current_order.set_address(update_order.address.data)\n current_order.set_level(update_order.level.data)\n current_order.set_door_no(update_order.door_number.data)\n current_order.set_card(update_order.card_type.data)\n current_order.set_exp(update_order.exp_date.data)\n current_order.set_ccv(update_order.cvv.data)\n current_order.set_card_no(update_order.card_number.data)\n current_order.set_location(update_order.general_location.data)\n current_order.set_remark(update_order.remarks.data)\n\n db['orders_delivery'] = order_dict\n db.close()\n if RSD == 'S':\n return redirect(url_for('kin.self_collect_summary'))\n elif RSD == 'D':\n return redirect(url_for('kin.delivery_summary'))\n elif RSD == 'R':\n return redirect(url_for('kin.restock_summary'))\n\n else:\n order_dict = db['orders_delivery']\n\n current_order = order_dict.get(id)\n update_order.name.data = current_order.get_name()\n update_order.number.data = current_order.get_phone()\n update_order.postal.data = current_order.get_postal()\n update_order.address.data = current_order.get_address()\n update_order.level.data = current_order.get_level()\n update_order.door_number.data = current_order.get_door()\n update_order.card_type.data = current_order.get_card()\n update_order.exp_date.data = current_order.get_exp_date()\n update_order.cvv.data = current_order.get_cvv()\n update_order.card_number.data = current_order.get_card_no()\n update_order.general_location.data = current_order.get_location()\n update_order.remarks.data = current_order.get_remark()\n return render_template('order_details_delivery.html', form=update_order)\n\n\[email protected]('/edit_collect_order/<int:id>', methods=['POST', 'GET'])\ndef edit_collect_order(id):\n db = shelve.open('storage.db', 'c')\n update_order = self_collect(request.form)\n if request.method == 'POST' and update_order.validate():\n order_dict = db['orders_self']\n\n current_order = order_dict.get(id)\n current_order.set_name(update_order.name.data)\n current_order.set_phone(update_order.number.data)\n current_order.set_card_no(update_order.card_number.data)\n current_order.set_date(update_order.exp_date.data)\n current_order.set_ccv(update_order.cvv.data)\n current_order.set_card(update_order.card_type.data)\n\n db['orders_self'] = order_dict\n db.close()\n return redirect(url_for('kin.self_collect_summary'))\n else:\n order_dict = db['orders_self']\n\n current_order = order_dict.get(id)\n update_order.name.data = current_order.get_name()\n update_order.number.data = current_order.get_number()\n update_order.card_number.data = current_order.get_card_no()\n update_order.exp_date.data = current_order.get_exp()\n update_order.cvv.data = current_order.get_cvv()\n update_order.card_type.data = current_order.get_card()\n\n return render_template('order_details_collect.html', form=update_order)\n\n\[email protected]('/create_item/<shop_or_stock>', methods=['GET', 'POST'])\ndef create_item(shop_or_stock):\n count = 1\n create_item_form = Item(request.form)\n if request.method == 'POST' and create_item_form.validate():\n file = request.files['file']\n if file and allowed_file(file.filename):\n users_dict = {}\n db = shelve.open('storage.db', 'c')\n try:\n users_dict = db['item']\n while count in users_dict:\n count += 1\n except:\n print('Error in retrieving users from db')\n\n stock_item = item.Stock_item(create_item_form.stock_name.data,\n create_item_form.price.data, create_item_form.origin.data,\n create_item_form.weight.data, create_item_form.Dietary.data,\n create_item_form.ingredients.data, create_item_form.description.data,\n create_item_form.amt_of_stock.data, create_item_form.category.data,\n create_item_form.brand.data, create_item_form.unit.data,\n create_item_form.stock_unit.data)\n stock_item.set_per_box(create_item_form.subcategory_boxes.data)\n filename = create_item_form.stock_name.data + '.png'\n if filename in current_app.config['UPLOAD_FOLDER']:\n flash('similar stock is already created')\n return redirect(url_for('create_stock'))\n file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))\n\n stock_item.set_id(count)\n users_dict[stock_item.get_id()] = stock_item\n db['item'] = users_dict\n db.close()\n\n session['item_created'] = stock_item.get_stock_name()\n\n if shop_or_stock == 'stock':\n return redirect(url_for('kin.stock',\n filename=filename))\n else:\n return redirect(url_for('kin.shop',\n filename=filename))\n else:\n print('invalid file extension')\n flash('Invalid file extension')\n return render_template('create_item.html', form=create_item_form, shop_or_stock=shop_or_stock)\n\n\[email protected]('/update/<int:id>', methods=['GET', 'POST'])\ndef update_item(id):\n update_item_form = Item(request.form)\n if request.method == 'POST' and update_item_form.validate():\n item_dict = {}\n db = shelve.open('storage.db', 'w')\n item_dict = db['item']\n item = item_dict.get(id)\n\n item.set_stock_name(update_item_form.stock_name.data)\n item.set_base_price(update_item_form.price.data)\n item.set_origin(update_item_form.origin.data)\n item.set_weight(update_item_form.weight.data)\n item.set_dietary(update_item_form.Dietary.data)\n item.set_amt_of_stock(update_item_form.amt_of_stock.data)\n item.set_cat(update_item_form.category.data)\n item.set_ingredients(update_item_form.ingredients.data)\n item.set_description(update_item_form.description.data)\n item.set_brand(update_item_form.brand.data)\n item.set_stock_unit(update_item_form.stock_unit.data)\n file = request.files['file']\n if file.filename != '':\n filename = update_item_form.stock_name.data + '.png'\n file_path = UPLOAD_FOLDER + '/' + filename\n os.remove(file_path)\n file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))\n\n db['item'] = item_dict\n db.close()\n\n session['item_updated'] = item.get_stock_name()\n\n return redirect(url_for('kin.stock'))\n else:\n item_dict = {}\n db = shelve.open('storage.db', 'r')\n item_dict = db['item']\n db.close()\n\n item = item_dict.get(id)\n update_item_form.stock_name.data = item.get_stock_name()\n update_item_form.price.data = item.get_base_price()\n update_item_form.origin.data = item.get_origin()\n update_item_form.weight.data = item.get_weight()\n update_item_form.Dietary.data = item.get_dietary()\n update_item_form.category.data = item.get_category()\n update_item_form.amt_of_stock.data = item.get_amt_of_stock()\n update_item_form.ingredients.data = item.get_ingredients()\n update_item_form.description.data = item.get_description()\n update_item_form.brand.data = item.get_brand()\n update_item_form.stock_unit.data = item.get_stock_unit()\n\n return render_template('update_item.html', form=update_item_form)\n\n\[email protected]('/delete_stock/<int:id>', methods=['GET', 'POST'])\ndef delete_stock(id):\n if request.method == 'POST':\n item_dict = {}\n db = shelve.open('storage.db', 'w')\n item_dict = db['item']\n\n item = item_dict.get(id)\n filename = item.get_stock_name() + '.png'\n filepath = UPLOAD_FOLDER + '/' + filename\n os.remove(filepath)\n\n item = item_dict.pop(id)\n\n db['item'] = item_dict\n db.close()\n\n session['item_deleted'] = item.get_stock_name()\n\n return redirect(url_for('kin.stock'))\n\n\[email protected]('/restock/<int:id>', methods=['GET', 'POST'])\ndef restock(id):\n count = 0\n supplier_dict = {}\n supplier_list = []\n stock_dict = {}\n db = shelve.open('storage.db', 'c')\n stock_dict = db['item']\n current_item = stock_dict.get(id)\n\n try:\n supplier_dict = db['supplier']\n except:\n print('supplier not created')\n for key in supplier_dict:\n item = supplier_dict.get(key)\n supplier_for = item.get_stock()\n supplier_name = item.get_name()\n if supplier_for == current_item.get_stock_name():\n supplier_list.append(item)\n if supplier_name == current_item.get_default_suppliers():\n supplier_index = supplier_list.index(item)\n supplier_list.insert(0, supplier_list.pop(supplier_index))\n if request.method == 'POST':\n supplier = request.form['supplier']\n amount = request.form['amount']\n session['restock_order'] = supplier\n\n for key in stock_dict:\n stock_item = stock_dict.get(key)\n stock_id = stock_item.get_id()\n if id == stock_id:\n stock_item.increase_stock(amount)\n db['item'] = stock_dict\n db.close()\n return redirect(url_for('kin.stock'))\n return render_template('restock.html', id=id, supplier_list=supplier_list,\n length=len(supplier_list))\n\n\[email protected]('/low_stock_bulk_restock', methods=['GET', 'POST'])\ndef low_stock_bulk_restock():\n db = shelve.open('storage.db', 'c')\n low_stock_list = db['low_stock_list']\n item_dict = db['item']\n quantity = request.form['quantity']\n\n for item in low_stock_list:\n item_id = item.get_id()\n item_in_dict = item_dict.get(item_id)\n if item_in_dict.get_default_suppliers() != '':\n item_in_dict.increase_stock(quantity)\n else:\n print(1)\n flash(item_in_dict.get_stock_name() + ' has no default supplier')\n db['item'] = item_dict\n db.close()\n return redirect(url_for('kin.stock'))\n\n\[email protected]('/delete_shop/<int:id>', methods=['GET', 'POST'])\ndef delete_shop(id):\n if request.method == 'POST':\n item_dict = {}\n db = shelve.open('storage.db', 'w')\n item_dict = db['item']\n\n item_dict.pop(id)\n\n db['item'] = item_dict\n db.close()\n\n return redirect(url_for('kin.shop'))\n\n\[email protected]('/create_supplier/<int:id>', methods=['GET', 'POST'])\ndef supplier(id):\n count = 1\n create_supplier = Supplier(request.form)\n if request.method == 'POST' and create_supplier.validate():\n supplier_dict = {}\n item_dict = {}\n db = shelve.open('storage.db', 'c')\n item_dict = db['item']\n\n try:\n supplier_dict = db['supplier']\n while count in supplier_dict:\n count += 1\n except:\n print('error')\n\n supplier_item = item.Supplier(create_supplier.name.data, create_supplier.email.data,\n create_supplier.number.data,\n create_supplier.location.data)\n supplier_item.set_id(count)\n stock_item = item_dict.get(id)\n supplier_item.set_stock(stock_item.get_stock_name())\n supplier_dict[supplier_item.get_id()] = supplier_item\n db['supplier'] = supplier_dict\n db.close()\n return redirect(url_for('kin.stock'))\n return render_template('create_supplier.html', form=create_supplier)\n\n\[email protected]('/suppliers', defaults={'sort': None})\[email protected]('/suppliers/<sort>')\ndef suppliers_list(sort):\n supplier_dict = {}\n item_dict = {}\n db = shelve.open('storage.db', 'r')\n try:\n supplier_dict = db['supplier']\n except:\n session['No_restock_obj'] = 'No restock company are created'\n db.close()\n\n supplier_list = []\n for key in supplier_dict:\n supplier_details = supplier_dict.get(key)\n supplier_list.append(supplier_details)\n\n if sort == 'Supplier_AZ':\n supplier_list.sort(key=lambda x: x.get_name())\n elif sort == 'Supplier_ZA':\n supplier_list.sort(key=lambda x: x.get_name(), reverse=True)\n elif sort == 'For_AZ':\n supplier_list.sort(key=lambda s: s.get_stock())\n elif sort == 'For_ZA':\n supplier_list.sort(key=lambda s: s.get_stock(), reverse=True)\n\n return render_template('suppliers.html', count=len(supplier_list), supplier_list=supplier_list)\n\n\[email protected]('/deleteSupplier/<int:id>', methods=['POST'])\ndef delete_supplier(id):\n supplier_dict = {}\n db = shelve.open('storage.db', 'w')\n supplier_dict = db['supplier']\n\n supplier = supplier_dict.pop(id)\n\n db['supplier'] = supplier_dict\n db.close()\n\n session['deleted_supplier'] = supplier.get_name()\n return redirect(url_for('kin.stock'))\n\n\[email protected]('/updateSupplier/<int:id>', methods=['POST', 'GET'])\ndef update_supplier(id):\n update_supplier = Supplier(request.form)\n if request.method == 'POST' and update_supplier.validate():\n supplier_dict = {}\n db = shelve.open('storage.db', 'c')\n\n try:\n supplier_dict = db['supplier']\n except:\n print('error')\n\n supplier_item = supplier_dict.get(id)\n\n supplier_item.set_name(update_supplier.name.data)\n supplier_item.set_number(update_supplier.number.data)\n supplier_item.set_email(update_supplier.email.data)\n supplier_item.set_location(update_supplier.location.data)\n\n db['supplier'] = supplier_dict\n db.close()\n\n session['updated_supplier'] = supplier_item.get_name()\n\n return redirect(url_for('kin.suppliers_list'))\n else:\n supplier_dict = {}\n db = shelve.open('storage.db', 'c')\n\n try:\n supplier_dict = db['supplier']\n except:\n print('error')\n\n supplier_item = supplier_dict.get(id)\n\n update_supplier.name.data = supplier_item.get_name()\n update_supplier.number.data = supplier_item.get_phone()\n update_supplier.email.data = supplier_item.get_email()\n update_supplier.location.data = supplier_item.get_location()\n\n return render_template('update_supplier.html', form=update_supplier)\n\n\[email protected]('/set_as_default/<int:supplier_id>')\ndef set_default(supplier_id):\n db = shelve.open('storage.db', 'c')\n supplier_dict = db['supplier']\n stock_dict = db['item']\n\n current_supplier = supplier_dict.get(supplier_id)\n for_stock = current_supplier.get_stock()\n\n for key in stock_dict:\n current_item = stock_dict.get(key)\n if current_item.get_stock_name() == for_stock:\n current_item.set_default_supplier(current_supplier.get_name())\n\n db['item'] = stock_dict\n db.close()\n\n session['default_supplier'] = current_supplier.get_name() + ' is set as default for ' + current_supplier.get_stock()\n\n return redirect(url_for('kin.stock'))\n\n\[email protected]('/manage_account')\ndef mananage_account():\n user_list = [1]\n return render_template('Manage_staff_accounts.html', users_list = user_list)" }, { "alpha_fraction": 0.49211710691452026, "alphanum_fraction": 0.49662160873413086, "avg_line_length": 36, "blob_id": "3fab237fc9c5dc99ea533dce3f400406d7651fb4", "content_id": "3bd5996ab8296fe8a44cd9f6d25688bd9434469d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 888, "license_type": "no_license", "max_line_length": 97, "num_lines": 24, "path": "/templates/includes/_navbar_deliveryman.html", "repo_name": "frake17/SSP_project", "src_encoding": "UTF-8", "text": "<nav class=\"navbar navbar-expand-sm bg-info navbar-light justify-content-end font-weight-bold\">\n <!-- Brand -->\n <a class=\"navbar-brand\" href=\"/\"><img src=\"../../static/img/logo.png\" width=\"45\"></a>\n\n <!-- Links -->\n <ul class=\"navbar-nav ml-auto mr-1\">\n <li class=\"nav-item\">\n <a class=\"nav-link\" href=\"/\">Home</a>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link\" href=\"/deliverymen_orders\">Orders</a>\n </li>\n <li class=\"nav-item dropdown\">\n <a class=\"nav-link dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\" id=\"navbardrop2\">\n Deliveryman\n </a>\n <div class=\"dropdown-menu\">\n {% if 'current' in session %}\n <a class=\"dropdown-item\" href=\"/logout\">Log out</a>\n {% endif %}\n </div>\n </li>\n </ul>\n</nav>\n" } ]
16
kruminsch/pervij
https://github.com/kruminsch/pervij
48cfc60baf7e9e807d2bf172b903954fd18b7658
3b2a694fb603452638752ad559eb03fb4366c918
ac77361b6db6c47520431607ba9a5921e4d00f4c
refs/heads/master
2020-05-04T02:22:12.738024
2020-03-25T12:54:03
2020-03-25T12:54:03
178,925,298
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.64211106300354, "alphanum_fraction": 0.6586036086082458, "avg_line_length": 12.375, "blob_id": "56b957f45a7550d9513e4f79d9bcd76ae97eed8e", "content_id": "6038a884e9cbd2c0e855796a791fa5072d629a68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1819, "license_type": "no_license", "max_line_length": 74, "num_lines": 136, "path": "/tetris/src/main.c", "repo_name": "kruminsch/pervij", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** tetris\n** File description:\n** main\n*/\n\n#include \"../include/my.h\"\n#include \"time.h\"\n\n/*\n * ALLOWED FUNCTIONS:\n * malloc\nfree\nwrite\n(f)write\n(f)read\n(f)close\n(f)open\nexit\ngetline\nioctl\nusleep\nsigaction\nsignal\nstat\nlstat\nfstat\nopendir\nreaddir\nclosedir\ngetpwuid\ngetgrgid\ntime\nctime\nreadlink\nperror\nstrerror\ngetcwd\nchdir\nfork\nexecve\naccess\nisatty\nwait\nwaitpid\nwait3\nwait4\nkill\ngetpid\nstrsignal\nstrerror\nlseek\nsigemptyset\nsetcontext\ngetcontext\nnanosleep\npause\nlseek\nsigemptyset\nsetcontext\ngetcontext\nnanosleep\npause\nrand\nsrand\ngetopt\ngetopt-long\nclock*/\n\n//checKing for fatal errors like cannot open dir or no passing files found\n//or malloc...???\nvoid fatal_errors(int ac, char **av)\n{\n\t(void)(ac);\n\t(void)(av);\n\twrite(1, \"i am reading options\\n\", 21);\n\n}\n\nvoid debug(int ac, char **av)\n{\n\n\tfatal_errors(ac, av);\n\t//ONLY if u r in debug mode:\n\twrite(1, \"Press any key to start Tetris\", 29);\n\n}\n\nvoid fill_opt_default(opt_t *options)\n{\n\toptions->level = 1;\n\toptions->debug = 0;\n\toptions->hide_next = 0;\n\toptions->x = 10;\n\toptions->y = 20;\n\toptions->left = 4;\n\toptions->right = 5;\n\toptions->drop = 2;\n\toptions->turn = 3;\n\toptions->pause = ' ';\n\toptions->quit = 'q';\n\n\n}\n\n//we have to use getopt and getopt_long functions\nvoid fill_options(opt_t *options, int ac, char **av)\n{\n (void)(ac);\n (void)(av); \n options->level = 2;\n options->quit = 97;\n\n\n}\n\nint main(int ac, char **av)\n{\n char *input = malloc(sizeof(char));\n opt_t options;\n fill_opt_default(&options);\n fill_options(&options, ac, av);\n debug(ac, av);\n //ONLY ifu r in debug mode:\n read(0, input, 1);\n initscr();\n start_color();\n init_pair(2, COLOR_CYAN, COLOR_BLUE);\n keypad(stdscr, TRUE);\n nodelay(stdscr, TRUE);\n disp(options);\n endwin();\n free(input);\n return (0);\n}\n" }, { "alpha_fraction": 0.5404040217399597, "alphanum_fraction": 0.558080792427063, "avg_line_length": 12.199999809265137, "blob_id": "c5bf23d611620cc070a4af042cbc838fcf009fce", "content_id": "693cc261bfdfe2058ae9746a67534f1167595fdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 396, "license_type": "no_license", "max_line_length": 62, "num_lines": 30, "path": "/tetris/Makefile", "repo_name": "kruminsch/pervij", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## dante\n## File description:\n## makefile\n##\n\nNAME =\ttetris\n\nSRC =\t./src/main.c\t\t\t\\\n\t\t./src/disp.c\n\nOBJ\t=\t$(SRC:.c=.o)\n\nall: \t$(NAME)\n\n$(NAME):\t$(OBJ)\n\t\tgcc -o $(NAME) $(OBJ) -lncurses\n\nCFLAGS += -g3 -Werror -Wextra -Wall -ansi -pedantic -std=gnu11\n\nclean:\n\t\trm -f $(OBJ)\n\nfclean: clean\n\t\trm -f $(NAME)\n\nre:\t\tfclean all\n\n.PHONY:\t\tclean all fclean re\n" }, { "alpha_fraction": 0.6505848169326782, "alphanum_fraction": 0.6681286692619324, "avg_line_length": 17, "blob_id": "5823e9c6c05fa1c7aaa38cbf076b74584264f2a9", "content_id": "4b694afb3994fc673659bd552215ca07acaaad69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 684, "license_type": "no_license", "max_line_length": 63, "num_lines": 38, "path": "/include/my.h", "repo_name": "kruminsch/pervij", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** Solo stumper\n** File description:\n** my.h\n*/\n\n#ifndef MY_H\n#define MY_H\n\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <fcntl.h>\n#include <string.h>\n#include <arpa/inet.h>\n\nint my_strlen(char const *str);\nint my_strcmp(char const *s1, char const *s2);\nchar **my_str_to_word_array(char const *src);\nint my_putstr(char const *str);\nvoid my_putchar(char c);\nint make_word(char *word, char const *src, int pos, int w_len);\n\nstruct um_array{\n\tstruct um_array *prev;\n\tu_int32_t num;\n\tu_int32_t *plates;\n\tu_int32_t len;\n\tstruct um_array *next;\n};\ntypedef struct um_array um_t;\n\n\n\n#endif /* !MY_H */\n" }, { "alpha_fraction": 0.3984375, "alphanum_fraction": 0.4326171875, "avg_line_length": 16.65517234802246, "blob_id": "3aca0a45db1fb59c735cb86f54be630116e6037b", "content_id": "385041e2d6e5993e95c3566fc9edf3eed1a911e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1024, "license_type": "no_license", "max_line_length": 66, "num_lines": 58, "path": "/tetris/lib/strcmp_new.c", "repo_name": "kruminsch/pervij", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** Str_compar\n** File description:\n** For minishell\n*/\n\n#include \"../include/my.h\"\n#include \"../include/mysh.h\"\n#include <stdio.h>\n\nint strcmp_mysh(char const *s1, char const *s2)\n{\n int i = 0;\n\n while (s1[i] && s2[i]) {\n if (s1[i] == s2[i])\n i = i + 1;\n else\n return (0);\n }\n if ((s1[i] == '\\n' || s1[i] == '\\0') && s2[i] == '\\0')\n return (1);\n else\n return (0);\n}\n\nint strcmp_n(char const *s1, char const *s2)\n{\n int i = 0;\n\n while (s1[i] && s2[i])\n {\n if (s1[i] == s2[i])\n ++i;\n else\n return (0);\n }\n if (s1[i] == '\\0' && s2[i] == '=')\n return (1);\n else\n return (0);\n}\n\nchar **make_path(env_t *env_list)\n{\n char **path;\n env_t *tmp;\n\n tmp = env_list;\n while ((strcmp_mysh(tmp->name, \"PATH\")) == 0 && tmp != NULL) {\n tmp = tmp->next;\n }\n if (tmp == NULL)\n return (NULL);\n path = my_path_2(tmp->var_it);\n return (path);\n}\n" }, { "alpha_fraction": 0.5188838839530945, "alphanum_fraction": 0.5408681035041809, "avg_line_length": 26.511627197265625, "blob_id": "5c2eff385f429057457e3eb372ea7776fa7b98af", "content_id": "c87117c4b3207189afca0ed514d746a8ad0a9904", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3568, "license_type": "no_license", "max_line_length": 108, "num_lines": 129, "path": "/108trigo/108trigo", "repo_name": "kruminsch/pervij", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport sys\nimport math\nimport os\nimport random\n\ndef identity_matrix(n):\n mat_arr = []\n for i in range(n):\n arr = []\n for j in range(n):\n arr.append(1 if j == i else 0)\n mat_arr.append(arr)\n return mat_arr\n\ndef matrix_mult(matrix1, matrix2):\n mat_arr = []\n for i in range(len(matrix1)):\n arr = []\n for j in range(len(matrix2[0])):\n a = 0\n for k in range(len(matrix1[0])):\n a += matrix1[i][k] * matrix2[k][j]\n arr.append(a)\n mat_arr.append(arr)\n return mat_arr\n\ndef pow_matrix(matrix, n):\n mat_arr = matrix\n for i in range(n - 1):\n mat_arr = matrix_mult(mat_arr, matrix)\n return mat_arr\n\n\ndef div_matrix(matrix, k):\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n matrix[i][j] /= k\n return matrix\n\n\ndef add_matrix(matrix1, matrix2):\n mat_arr = []\n for i in range(len(matrix1)):\n arr = []\n for j in range(len(matrix1[0])):\n arr.append(matrix1[i][j] + matrix2[i][j])\n mat_arr.append(arr)\n return mat_arr\n\n\ndef sub_matrix(matrix1, matrix2):\n mat_arr = []\n for i in range(len(matrix1)):\n arr = []\n for j in range(len(matrix1[0])):\n arr.append(matrix1[i][j] - matrix2[i][j])\n mat_arr.append(arr)\n return mat_arr\n\ndef my_exp(tab):\n mat_arr = identity_matrix(len(tab))\n for i in range(1, 18):\n mat_arr = add_matrix(mat_arr, div_matrix(pow_matrix(tab, i), math.factorial(i)))\n return mat_arr\n\ndef my_cos(tab):\n mat_arr = identity_matrix(len(tab))\n for i in range(1, 17):\n if i % 2 == 0:\n mat_arr = add_matrix(mat_arr, div_matrix(pow_matrix(tab, 2 * i), math.factorial(2 * i)))\n else:\n mat_arr = sub_matrix(mat_arr, div_matrix(pow_matrix(tab, 2 * i), math.factorial(2 * i)))\n return mat_arr\n\ndef my_sin(tab):\n mat_arr = tab\n for i in range(1, 17):\n if i % 2 == 0:\n mat_arr = add_matrix(mat_arr, div_matrix(pow_matrix(tab, 2 * i + 1), math.factorial(2 * i + 1)))\n else:\n mat_arr = sub_matrix(mat_arr, div_matrix(pow_matrix(tab, 2 * i + 1), math.factorial(2 * i + 1)))\n return mat_arr\n\ndef usage():\n print(\"USAGE\")\n print(\"\\t./108trigo fun a0 a1 a2 ...\")\n print(\"DESCRIPTION\")\n print(\"\\tfum\\tfunction to be applied, among at least “EXP”, “COS”, “SIN”, “COSH”and “SINH”\")\n print(\"\\tai\\tcoeficients of the matrix\")\n\ndef error_handling():\n if len(sys.argv) <= 2 or sys.argv[1] not in [\"EXP\", \"COS\", \"SIN\", \"COSH\", \"SINH\"]:\n exit(84)\n try:\n for i in range(2, len(sys.argv)):\n sys.argv[i] = float(sys.argv[i])\n except ValueError:\n exit(84)\n\ndef launch_func(tab):\n args = [\"EXP\", \"COS\", \"SIN\", \"COSH\", \"SINH\"]\n my_tab = [my_exp, my_cos, my_sin]\n for i in range(len(my_tab)):\n if sys.argv[1] == args[i]:\n tab = my_tab[i](tab)\n return tab\n\ndef print_matrix(tab):\n for i in range(len(tab)):\n for j in range(len(tab[i])):\n print(\"%.2f%c\" % (tab[i][j], '\\t' if (j != len(tab[i]) - 1) else '\\n'), end=\"\")\n\nif (len(sys.argv) == 2 and sys.argv[1] == \"-h\"):\n usage()\n exit(0)\ntab = []\nerror_handling()\ni = len(sys.argv) - 2\narr = math.trunc(math.sqrt(i))\nif math.trunc(math.sqrt(i)) ** 2 != i:\n exit(84)\nfor i in range(int(arr)):\n tab.append([])\n for j in range(int(arr)):\n tab[i].append(sys.argv[i * int(arr) + j + 2])\ntab = launch_func(tab)\nprint_matrix(tab)" }, { "alpha_fraction": 0.5063424706459045, "alphanum_fraction": 0.5338266491889954, "avg_line_length": 16.830188751220703, "blob_id": "e1bbe93f1d87952dd6d923e4a79b52939f9ae3d2", "content_id": "a035d3dfd4c0c2062b702465a9f5a3870578ad70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 946, "license_type": "no_license", "max_line_length": 56, "num_lines": 53, "path": "/tetris/src/disp.c", "repo_name": "kruminsch/pervij", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** tetris\n** File description:\n** display\n*/\n\n#include \"../include/my.h\"\n#include \"time.h\"\n\nchar *make_line(char *clock)\n{\n\tint i = 0;\n\tint j = 14;\n\tchar *line = malloc(sizeof(char) * 6);\n\n for(;i < 5; ++i, ++j) {\n\t\tline[i] = clock[j];\n\t}\n\tline[5] = '\\0';\n\treturn (line);\n}\n\n//put these 2 fts together, please (make_line and timer)\nchar *timer(time_t start)\n{\n time_t timenow = time(NULL) - start;\n char *clock;\n clock = ctime(&timenow);\n return (make_line(clock));\n \n\n}\n\nint disp(opt_t options)\n{\n int a = -12;\n (void)(options);\n char key;\n time_t start = time(NULL);\n char *clock;\n do {\n\tclock = timer(start);\n mvprintw(8, 10, \"%s\\n\", clock);\n curs_set(0);\n noecho();\n //getmaxyx(stdscr, 20, 20);\n refresh();\n mvprintw(10,10,\"THIS IS MY GAME\\n\");\n } while ((key = getch() != options.quit));\n free(clock);\n return (a);\n}\n\n" }, { "alpha_fraction": 0.4814443290233612, "alphanum_fraction": 0.5025075078010559, "avg_line_length": 16.491228103637695, "blob_id": "f9f94c56ece6883ec9dd5810761349f26e1e73aa", "content_id": "20094704204d4a0ae3c47570dec8d27ee5b14347", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 997, "license_type": "no_license", "max_line_length": 57, "num_lines": 57, "path": "/lists.c", "repo_name": "kruminsch/pervij", "src_encoding": "UTF-8", "text": "#include \"./include/my.h\"\n\nvoid show_list(um_t *ptr)\n{\n um_t *tmp;\n tmp = ptr;\n while (tmp != NULL) {\n\t printf(\"%u\\n\", tmp->num);\n\t for(u_int32_t i = 0; i < tmp->len; ++i)\n\t\t printf(\"%u\", tmp->plates[i]);\n\t write(1, \"\\n\", 1);\n\n\t //write(1, \"\\n\", 1);\n\t tmp = tmp->next;\n }\n return;\n} \n\n\n\nint put_elem(um_t **list, u_int32_t num, u_int32_t nmemb)\n{\n//\tnt put_trail_elem(list_t **ptr_num, int num)\n//{\n um_t *new_um;\n um_t *last = *list;\n\n new_um = malloc(sizeof(*new_um));\n new_um->num = num;\n new_um->plates = calloc(nmemb, sizeof(u_int32_t));\n new_um->len = nmemb;\n new_um->next = NULL;\n if (*list == NULL) {\n *list = new_um;\n new_um->prev = NULL;\n return (0);\n }\n while (last->next != NULL)\n last = last->next;\n last->next = new_um;\n new_um->prev = last;\n return (0);\n}\n\n\n\nint main(int ac, char **av)\n{\n\tum_t *list;\n\tlist = NULL;\n\n\tfor (u_int32_t i = 0; i < 3; ++i) \n\t\tput_elem(&list, i, i + 12);\n show_list(list);\t\n\n\n}\n" }, { "alpha_fraction": 0.6349206566810608, "alphanum_fraction": 0.6547619104385376, "avg_line_length": 12.621622085571289, "blob_id": "bed6e393779634a1b666e4d41b7289cbd7a50fb3", "content_id": "182aec3da0e058ee9cbfdf81b130df4c49ae96e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 504, "license_type": "no_license", "max_line_length": 25, "num_lines": 37, "path": "/tetris/include/my.h", "repo_name": "kruminsch/pervij", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPool_Day09_2019\n** File description:\n** My_MY-H\n*/\n\n#ifndef MY_H\n#define MY_H\n\n#include <unistd.h>\n#include <stdlib.h>\n#include <curses.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <ncurses.h>\n#include <string.h>\n#include <getopt.h>\n\nstruct opt {\n\tint level;\n\tint left;\n\tint right;\n\tint turn;\n\tint drop;\n\tint quit;\n\tint pause;\n\tint x;\n\tint y;\n\tint hide_next;\n\tint debug;\n};\ntypedef struct opt opt_t;\nint disp(opt_t options);\n\n#endif /* !MY_H */\n" }, { "alpha_fraction": 0.5045454502105713, "alphanum_fraction": 0.5090909004211426, "avg_line_length": 9.428571701049805, "blob_id": "78fcce4f4491ab99460921da7afbe5fad8d7494d", "content_id": "9846a4d2f76c85b6db3b5b249d283760e9003510", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 220, "license_type": "no_license", "max_line_length": 28, "num_lines": 21, "path": "/Makefile", "repo_name": "kruminsch/pervij", "src_encoding": "UTF-8", "text": "\nSRC\t=\tum_main.c\t\t\t\t\\\n\n\nOBJ\t=\t$(SRC:.c=.o)\t\t\t\t\\\n\nNAME\t=\tc.um\n\nall:\t\t$(NAME)\n\n$(NAME):\t$(OBJ)\n\t\tgcc -g3 -o $(NAME) $(OBJ)\n\nclean:\n\t\trm -f $(OBJ)\n\nfclean: \tclean\n\t\trm $(NAME)\n\nre:\t\tfclean all\n\n.PHONY:\t\tall clean fclean re\n" }, { "alpha_fraction": 0.43118786811828613, "alphanum_fraction": 0.48874935507774353, "avg_line_length": 16.216217041015625, "blob_id": "2c181703061570a9bd5ad2c60faaaef401796fad", "content_id": "048a811405fa2caf451785738173a2333557828a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1911, "license_type": "no_license", "max_line_length": 44, "num_lines": 111, "path": "/um_main.c", "repo_name": "kruminsch/pervij", "src_encoding": "UTF-8", "text": "/*#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <fcntl.h>\n#include <string.h>\n#include <arpa/inet.h>\n*/\n#include \"../include/my.h\"\n\nint my_strlen(char const *str)\n{\n int n = 0;\n\n while (*(str + n))\n ++n;\n return (n);\n}\n\nvoid my_putchar(char c)\n{\n write(1, &c, 1);\n}\n\nint my_put_base(unsigned int nb, char *base)\n{\n int deep = my_strlen(base);\n int modulo;\n\n if (nb <= deep && nb >= 0 )\n my_putchar(base[nb]);\n if (nb > deep) {\n modulo = nb % deep;\n my_put_base(nb / deep, base);\n my_putchar(base[modulo]);\n }\n return (0);\n}\n\nint convert(u_int32_t num)\n{\n u_int32_t b0;\n u_int32_t b1;\n u_int32_t b2;\n u_int32_t b3;\n u_int32_t res;\n\n b0 = (num & 0x000000ff) << 24u;\n b1 = (num & 0x0000ff00) << 8u;\n b2 = (num & 0x00ff0000) >> 8u;\n b3 = (num & 0xff000000) >> 24u;\n res = b0 | b1 | b2 | b3;\n printf(\"%u\\n\", res);\n my_put_base(res, \"0123456789abcdef\");\n write(1, \"\\n\", 1);\n return (0);\n \n\n}\n\nvoid bin(unsigned n)\n{\n unsigned i;\n for (i = 1 << 31; i > 0; i = i / 2)\n\t (n & i)? printf(\"1\"): printf(\"0\");\n printf(\"\\n\");\n}\n//print numbers big endian:wq\n//\nint boot(char *buf, size_t size)\n{\n //256 is size/4;\n u_int32_t a[256];\n u_int32_t b[256]; \n\n for (int i = 0; i < 256; ++i) {\n memcpy(&a[i], buf, 4);\n\ta[i] = htonl(a[i]);\n buf += 4;\n\tbin(a[i]);\n\t\n\tprintf(\"%u\\n\", a[i]);\n\n\n\n\n\t \n }\n //for (int i = 0; i < 256; ++i) {\n // printf(\"%u\\n\", htonl(a[i]));\n //} \n return (0);\n}\n\nint main(int ac, char **av)\n{\n char *buf;\n struct stat st;\n size_t size;\n int fd;\n \n stat(\"./um.um\", &st);\n size = st.st_size;\n buf = malloc(sizeof(char) * size + 1);\n fd = open(\"./um.um\", O_RDONLY);\n read(fd, buf, size);\n close(fd);\n boot(buf, size);\n return (0);\n}\n" } ]
10
peteramazonian/simulation_project
https://github.com/peteramazonian/simulation_project
7a4fcd6e998039f95d8ba21834a084c92776cbd2
fb545eacd0b41c3bfeb15f72d7a52cefb81653f9
13e32d7743ce3852e3cd796b2d9ca72e41d67199
refs/heads/master
2022-11-04T22:14:42.914943
2020-06-16T20:16:50
2020-06-16T20:16:50
259,943,711
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6018306612968445, "alphanum_fraction": 0.604881763458252, "avg_line_length": 34.4054069519043, "blob_id": "1af8245da922addbc4a68042ace9daac8af7f58d", "content_id": "0e5ef4add43cb116724f9a7e111e6f34ab749cfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1311, "license_type": "no_license", "max_line_length": 126, "num_lines": 37, "path": "/movement.py", "repo_name": "peteramazonian/simulation_project", "src_encoding": "UTF-8", "text": "import time_management\nfrom time_management import add_to_fel\nfrom system_arrival import SystemArrival\nss_list = __import__('service_station').ServiceStation.list\n\n\nclass Movement():\n list = []\n @classmethod\n def check(cls):\n x = len(ss_list)\n if len(cls.list) == x + 1:\n return\n elif len(cls.list) < x + 1:\n raise ValueError(\"Movement objects should be more\")\n else:\n raise ValueError(\"Movement objects are more than needed\")\n\n def __init__(self, moving_time_generator):\n self.time_generator = moving_time_generator\n self.position = len(Movement.list) + 1\n self.name = \"m\" + str(self.position)\n Movement.list.append(self)\n\n # Overriding Python's original __repr__ function\n def __repr__(self):\n return self.name\n\n def move(self, costumer_id):\n if self.position <= len(ss_list):\n event_notice = (\n self.time_generator.generate() + time_management.clock, \"A\" + str(self.position), costumer_id,\n ss_list[self.position - 1].arrival)\n add_to_fel(event_notice)\n else:\n event_notice = (self.time_generator.generate() + time_management.clock, \"D\", costumer_id, SystemArrival.departure)\n add_to_fel(event_notice)\n\n" }, { "alpha_fraction": 0.6245078444480896, "alphanum_fraction": 0.6356627345085144, "avg_line_length": 64.5268783569336, "blob_id": "95894e9d6616b862a94ade5941fd5823f49085c3", "content_id": "4a8e93b3c7eb8c00f29bb394e1ba3667549197c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6096, "license_type": "no_license", "max_line_length": 140, "num_lines": 93, "path": "/logger_multi_run.py", "repo_name": "peteramazonian/simulation_project", "src_encoding": "UTF-8", "text": "import xlsxwriter\nfrom datetime import datetime\n\n\nclass LoggerMR:\n def __init__(self, ss_names, replications):\n self.total_replications = replications\n self.ss_names = ss_names # Setting list of service ServiceStations\n time = datetime.now().strftime(\"%d-%m-%Y--%H-%M-%S\")\n self.wb = xlsxwriter.Workbook('LOG_MR/LOG-' + str(self.total_replications) + 'R--' + time + '.xlsx') # Creating Excel report\n # file in LOG_MR folder in the project directory\n self.ws = self.wb.add_worksheet(\"all logs\") # Creating a sheet inside the Excel file\n # Creating default format object\n self.default_format = self.wb.add_format(dict(font_name='Century Gothic', align='center', valign='vcenter'))\n # Defining a dictionary so it can be edited easily before creating a new format object\n self.header_format_dict = dict(font_name='Century Gothic', align='center', valign='vcenter', bold=True,\n font_color='navy', text_wrap=True, bg_color='silver', border=1)\n # Setting default format and height=14 for first 50 columns in all rows\n self.ws.set_column(0, 50, 14, self.default_format)\n # Freezing first 2 rows and first column\n self.ws.freeze_panes(2, 1)\n # Writing header for first column\n format_tmp = self.wb.add_format(self.header_format_dict) # Creating a temporary format object\n self.ws.merge_range(0, 0, 1, 0, \"Replication\", format_tmp) # Writing first row in merged cell\n # Writing header for column 2\n format_tmp = self.wb.add_format(self.header_format_dict) # Creating a temporary format object\n format_tmp.set_bg_color('#CCFF99') # Changing background color of the format object\n self.ws.write(0, 1, \"System\", format_tmp) # Writing first row\n system_parameters = ['Average Time in System']\n for col_num, cell_name in enumerate(system_parameters): # Writing second row\n self.ws.write(1, col_num + 1, cell_name, format_tmp)\n # Writing header for columns after 5\n # One section for each ServiceStation. It will cover all ServiceStations automatically.\n color_list = ['#FF5050', '#FFFF99'] # Defining a color list to choose in a loop for each\n # ServiceStation so it can be separated easily\n for num, ss in enumerate(self.ss_names):\n format_tmp = self.wb.add_format(self.header_format_dict)\n format_tmp.set_bg_color(color_list[int(num % len(color_list))]) # Setting background color of the\n # format object used for this ServiceStation's header, from the color list\n # Parameters names list. you need to edit this if you want to change what parameters are printed in log file\n # Also you should change ServiceStation's \"final_calculations\" function\n # Order of parameters in ss_parameters and result dict in ServiceStations should be the same\n ss_parameters = ['Total Wait Time', 'Average Queue Delay', 'Average Queue Length', 'Maximum Queue Length',\n 'Servers Efficiency', 'Queue Busy Percentage']\n i = num * len(ss_parameters) + 2 # Choose starting column\n self.ws.merge_range(0, i, 0, i + len(ss_parameters) - 1, ss, format_tmp) # Writing first row in\n # merged cell\n for index, cell_name in enumerate(ss_parameters): # Writing second row\n self.ws.write(1, index + i, cell_name, format_tmp)\n\n self.row = 2 # Setting the starting row to write logs. 3rd row is the row after header.\n self.replication_number = 1\n\n def replication_logger(self, s_list, SystemArrival): # It will write the system evaluation parameters for each replication in a new row\n column = 0\n format_tmp = self.wb.add_format(self.header_format_dict) # Creating a temporary format object\n self.ws.write(self.row, column, self.replication_number, format_tmp)\n self.replication_number += 1\n column += 1\n for key, value in SystemArrival.result.items():\n self.ws.write(self.row, column, value)\n column += 1\n for ss in s_list:\n for key, value in ss.result.items():\n self.ws.write(self.row, column, value)\n column += 1\n self.row += 1\n\n def result_logger(self, ss_names, result): # It will write the system evaluation parameters in a table at the end of the log file\n self.row += 3 # The table starts 3 rows after where log table ends\n column = 4 # The table starts from 5th column\n format_tmp = self.wb.add_format(self.header_format_dict) # Creating a temporary format object\n format_tmp.set_bg_color('#29A8FF') # Changing it's background color to blue\n # Writing the header:\n self.ws.write(self.row, column, 'Scope', format_tmp)\n self.ws.merge_range(self.row, column + 1, self.row, column + 2, \"Parameter Average\", format_tmp)\n self.ws.write(self.row, column + 3, 'Value', format_tmp)\n self.row += 1\n color_list = ['#FF5050', '#FFFF99'] # Used to separate parts with two colors in loop\n for num, ss in enumerate(ss_names): # Writing ServiceStations evaluation parameters\n format_tmp = self.wb.add_format(self.header_format_dict)\n format_tmp.set_bg_color(color_list[int(num % len(color_list))])\n if len(result[num]) > 1:\n self.ws.merge_range(self.row, column, self.row + len(result[num]) - 1, column, ss, format_tmp)\n else:\n self.ws.write(self.row, column, ss, format_tmp)\n for key, value in result[num].items(): # Writing parameters name and value\n self.ws.merge_range(self.row, column + 1, self.row, column + 2, key, format_tmp)\n self.ws.write(self.row, column + 3, value / self.total_replications, format_tmp)\n self.row += 1\n\n def close_file(self): # It will close and save the Excel file in the project directory\n self.wb.close()\n\n\n" }, { "alpha_fraction": 0.6299960017204285, "alphanum_fraction": 0.6404224038124084, "avg_line_length": 66.39639282226562, "blob_id": "1f55cf43c4063a0627c7d65c68e82e48124aab4c", "content_id": "b98ce3826dc35805d5c9020734b8b3755470dbfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7481, "license_type": "no_license", "max_line_length": 120, "num_lines": 111, "path": "/logger_single_run.py", "repo_name": "peteramazonian/simulation_project", "src_encoding": "UTF-8", "text": "import xlsxwriter\nfrom datetime import datetime\n\n\nclass LoggerSR:\n def __init__(self, s_list):\n self.s_list = s_list # Setting list of service ServiceStations\n self.system_arrival = __import__('system_arrival').SystemArrival # Importing SystemArrival class. It\n # should be imported inside init to avoid circular imports\n time = datetime.now().strftime(\"%d-%m-%Y--%H-%M-%S\")\n self.wb = xlsxwriter.Workbook('LOG_SR/LOG-SR--' + time + '.xlsx') # Creating Excel report file in LOG_SR\n # folder in the project directory\n self.ws = self.wb.add_worksheet(\"all logs\") # Creating a sheet inside the Excel file\n # Creating default format object\n self.default_format = self.wb.add_format(dict(font_name='Century Gothic', align='center', valign='vcenter'))\n # Defining a dictionary so it can be edited easily before creating a new format object\n self.header_format_dict = dict(font_name='Century Gothic', align='center', valign='vcenter', bold=True,\n font_color='navy', text_wrap=True, bg_color='silver', border=1)\n # Setting default format and height=14 for first 50 columns in all rows\n self.ws.set_column(0, 50, 14, self.default_format)\n # Freezing first 2 rows and first 3 columns\n self.ws.freeze_panes(2, 3)\n # Writing header for first 3 columns\n format_tmp = self.wb.add_format(self.header_format_dict) # Creating a temporary format object\n self.ws.merge_range(0, 0, 0, 2, \"FEL\", format_tmp) # Writing first row in merged cell\n fel_parameters = [\"Clock\", \"Event Type\", \"Costumer_ID\"]\n for col_num, cell_name in enumerate(fel_parameters): # Writing second row\n self.ws.write(1, col_num, cell_name, format_tmp)\n # Writing header for columns 4-5\n format_tmp = self.wb.add_format(self.header_format_dict) # Creating a temporary format object\n format_tmp.set_bg_color('#CCFF99') # Changing background color of the format object\n self.ws.merge_range(0, 3, 0, 4, \"System\", format_tmp) # Writing first row in merged cell\n system_parameters = [\"Costumers Total Time\", \"Costumers Departured\"]\n for col_num, cell_name in enumerate(system_parameters): # Writing second row\n self.ws.write(1, col_num + 3, cell_name, format_tmp)\n # Writing header for columns after 5\n # One section for each ServiceStation. It will cover all ServiceStations automatically.\n color_list = ['#FF5050', '#FFFF99'] # Defining a color list to choose in a loop for each\n # ServiceStation so it can be separated easily\n for num, ss in enumerate(self.s_list):\n format_tmp = self.wb.add_format(self.header_format_dict)\n format_tmp.set_bg_color(color_list[int(num % len(color_list))]) # Setting background color of the\n # format object used for this ServiceStation's header, from the color list\n # Parameters names list. you need to edit this if you want to change what parameters are printed in log file\n # Also you should change ServiceStation's \"return_printables\" function\n # Order of parameters in ss_parameters and printables list in ServiceStations should be the same\n ss_parameters = ['Available Servers', 'Busy Servers', 'Queue Len', 'Rest in Waiting',\n 'Cumulative Queue Len', 'Max Queue Len', 'Total Service Time', 'Total Service Count',\n 'Queue Delay Cumulative', 'Queue Total Time', 'Servers Total Busy Time',\n 'Servers Total Available Time']\n i = num * len(ss_parameters) + 5 # Choose starting column\n self.ws.merge_range(0, i, 0, i + len(ss_parameters) - 1, ss.name, format_tmp) # Writing first row in\n # merged cell\n for index, cell_name in enumerate(ss_parameters): # Writing second row\n self.ws.write(1, index + i, cell_name, format_tmp)\n\n self.row = 2 # Setting the starting row to write logs. 3rd row is the row after header.\n\n def fel_logger(self, event_notice): # It will write the event notice passed, into in the next blank row\n for col_num, item in enumerate(event_notice[0: -1]):\n self.ws.write(self.row, col_num, item)\n self.variable_logger() # Calling variable_logger function to log cumulative and state variables\n self.row += 1 # Moving to next row\n\n def variable_logger(self): # It will log cumulative and state variables for SystemArrivals and ServiceStations in\n # columns after 3 (where fel ends)\n column = 3\n # Writing System variables\n self.ws.write(self.row, column, self.system_arrival.costumers_total_time)\n column += 1\n self.ws.write(self.row, column, self.system_arrival.costumers_departured)\n column += 1\n # Writing ServiceStation variables\n for ss in self.s_list:\n for item in ss.return_printables():\n self.ws.write(self.row, column, item)\n column += 1\n\n def result_logger(self): # It will write the system evaluation parameters in a table at the end of the log file\n self.row += 3 # The table starts 3 rows after where log table ends\n column = 4 # The table starts from 5th column\n format_tmp = self.wb.add_format(self.header_format_dict) # Creating a temporary format object\n format_tmp.set_bg_color('#29A8FF') # Changing it's background color to blue\n # Writing the header:\n self.ws.write(self.row, column, 'Scope', format_tmp)\n self.ws.merge_range(self.row, column + 1, self.row, column + 2, \"Parameter\", format_tmp)\n self.ws.write(self.row, column + 3, 'Value', format_tmp)\n self.row += 1\n color_list = ['#FF5050', '#FFFF99'] # Used to separate parts with two colors in loop\n for num, ss in enumerate(self.s_list): # Writing ServiceStations evaluation parameters\n format_tmp = self.wb.add_format(self.header_format_dict)\n format_tmp.set_bg_color(color_list[int(num % len(color_list))])\n result = ss.result # ss.result is calculated in final_calculations method in ServiceStations at the end\n # of simulation\n self.ws.merge_range(self.row, column, self.row + len(result) - 1, column, ss.name, format_tmp)\n for key, value in result.items(): # Writing parameters name and value\n self.ws.merge_range(self.row, column + 1, self.row, column + 2, key, format_tmp)\n self.ws.write(self.row, column + 3, value, format_tmp)\n self.row += 1\n # Writing ServiceStations evaluation parameters:\n result = self.system_arrival.result # SystemArrival.result is calculated in final_calculations method in\n # SystemArrival at the end of simulation\n format_tmp = self.wb.add_format(self.header_format_dict)\n self.ws.write(self.row, column, \"System\", format_tmp) # Writing the scope column\n for key, value in result.items(): # Writing parameters name and value\n self.ws.merge_range(self.row, column + 1, self.row, column + 2, key, format_tmp)\n self.ws.write(self.row, column + 3, value, format_tmp)\n self.row += 1\n\n def close_file(self): # It will close and save the Excel file in the project directory\n self.wb.close()\n" }, { "alpha_fraction": 0.4419770836830139, "alphanum_fraction": 0.4469914138317108, "avg_line_length": 28.70212745666504, "blob_id": "6fc7eed14d2f251ea5e7e3ef2643adf6b4b9f831", "content_id": "e49d514b52da86728424755f3a8313eab6be8c27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1396, "license_type": "no_license", "max_line_length": 90, "num_lines": 47, "path": "/number_generator.py", "repo_name": "peteramazonian/simulation_project", "src_encoding": "UTF-8", "text": "import random\nfrom math import exp\n\n\nclass NumberGenerator:\n class Discrete(random.Random):\n def __init__(self, x: tuple, fx: tuple, **kwargs):\n self.x = None\n self.fx_list = fx\n self.x_list = x\n if len(self.x_list) != len(self.fx_list):\n raise ValueError(\"x_list and fx_list should have same number of elements\")\n for key, value in kwargs.items():\n if key == \"seed\":\n setattr(self, \"x\", value)\n super().__init__(self.x)\n\n def generate(self):\n rnd = self.random()\n for i in range(self.fx_list.__len__()):\n if rnd < sum(self.fx_list[:i + 1]):\n return self.x_list[i]\n\n class Static:\n def __init__(self, x=0):\n self.x = x\n\n def generate(self):\n return self.x\n\n class Poisson(random.Random):\n def __init__(self, mean=1, **kwargs):\n self.x = None\n self.mean = mean\n self.e = exp(-1 * mean)\n for key, value in kwargs.items():\n if key == \"seed\":\n setattr(self, \"x\", value)\n super().__init__(self.x)\n\n def generate(self):\n n = -1\n p = 1\n while p > self.e:\n p = p * self.random()\n n += 1\n return n\n" }, { "alpha_fraction": 0.5328089594841003, "alphanum_fraction": 0.5546067357063293, "avg_line_length": 42.617645263671875, "blob_id": "910cd320bbac4c4390d79dfaeee759f89feab8b4", "content_id": "9e75b022f198bdc4c6610283fdae0321f773fd67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4450, "license_type": "no_license", "max_line_length": 118, "num_lines": 102, "path": "/main_single_run.py", "repo_name": "peteramazonian/simulation_project", "src_encoding": "UTF-8", "text": "from service_station import ServiceStation\nfrom system_arrival import SystemArrival\nfrom movement import Movement\nfrom time_generator import TimeGenerator\nfrom number_generator import NumberGenerator\nimport time_management\nfrom logger_single_run import LoggerSR\n\n\n# Its our simulation's main file.\n# Here we import classes and functions from other project files.\n# Then we need to make objects from our classes and set attributes.\n# These objects are used to setup the system in a modular way.\n# You can make as many service stations as you need with their own attributes, then arrange the whole system together.\n\n# ---------------------------------------------------------------------\n# Creating SystemArrival objects\n# ---------------------------------------------------------------------\n\n# -------- First SystemArrival object --------\nt_generator = TimeGenerator.Exponential(3) # Creating its TimeGenerator\nn_generator = NumberGenerator.Static(1) # Creating its NumberGenerator\nief1 = SystemArrival(\"ief1\", t_generator, n_generator) # Creating first SystemArrival object\ndel n_generator, t_generator\n\n# -------- Second SystemArrival object --------\nt_generator = TimeGenerator.Exponential(5) # Creating its TimeGenerator\nn_generator = NumberGenerator.Discrete((1, 2, 3, 4), (0.2, 0.3, 0.3, 0.2)) # Creating its NumberGenerator\nief2 = SystemArrival(\"ief2\", t_generator, n_generator) # Creating first SystemArrival object\ndel n_generator, t_generator\n\n# -------- Third SystemArrival object --------\nt_generator = TimeGenerator.Uniform(0, 120) # Creating its TimeGenerator\nn_generator = NumberGenerator.Poisson(30) # Creating its NumberGenerator\nief3 = SystemArrival(\"ief3\", t_generator, n_generator) # Creating first SystemArrival object\ndel n_generator, t_generator\n\n# ---------------------------------------------------------------------\n# Creating ServiceStation objects\n# ---------------------------------------------------------------------\n\n# -------- First ServiceStation object --------\nt_generator = TimeGenerator.DoubleTriangular(1, 2, 4, 1, 2, 3) # Creating its TimeGenerator\nss1 = ServiceStation(\"ss1\", t_generator, 5) # Creating first ServiceStation object\ndel t_generator\n\n# -------- Second ServiceStation object --------\nt_generator = TimeGenerator.Uniform(0.5, 2) # Creating its TimeGenerator\nss2 = ServiceStation(\"ss2\", t_generator, 2) # Creating first ServiceStation object\ndel t_generator\n\n# -------- Third ServiceStation object --------\nt_generator = TimeGenerator.Triangular(10, 20, 30) # Creating its TimeGenerator\nss3 = ServiceStation(\"ss3\", t_generator, 30) # Creating first ServiceStation object\ndel t_generator\n\n# ---------------------------------------------------------------------\n# Creating Movement objects\n# ---------------------------------------------------------------------\n\nm1 = Movement(TimeGenerator.Static(0))\nm2 = Movement(TimeGenerator.Exponential(0.5))\nm3 = Movement(TimeGenerator.Exponential(0.5))\nm4 = Movement(TimeGenerator.Exponential(1))\n\nMovement.check()\n\n# ---------------------------------------------------------------------\n# Creating Loggers\n# ---------------------------------------------------------------------\n# time_management.logger_set_list(ServiceStation.list)\nlogger = LoggerSR(ServiceStation.list)\n\n# ---------------------------------------------------------------------\n# Creating Preliminary FEL\n# ---------------------------------------------------------------------\nief1.set_first_arrival(0)\nief2.set_first_arrival(0)\nief3.set_single_arrival(60)\nss1.set_rest_times([50, 110, 230, 290])\nss2.set_rest_times([50, 110, 230, 290])\n\n# ---------------------------------------------------------------------\n# Set Duration\n# ---------------------------------------------------------------------\nes = 300\ntime_management.set_end_of_simulation(es)\n\n# ---------------------------------------------------------------------\n# RUN!\n# ---------------------------------------------------------------------\ntry:\n while True:\n logger.fel_logger(time_management.advance_time())\nexcept time_management.SimulationDone:\n for ss in ServiceStation.list:\n ss.final_calculations()\n SystemArrival.final_calculations()\n logger.fel_logger((es, \"ES\", 0))\n logger.result_logger()\n print(\"Simulation DONE!\")\nlogger.close_file()\n\n" }, { "alpha_fraction": 0.5361694693565369, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 41.511451721191406, "blob_id": "1a4f0b7cf23f851017047ab8c9fd7b80f6c8d95a", "content_id": "ca1b538fd4624cf0bf43ba3cf75654bd52d91244", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5571, "license_type": "no_license", "max_line_length": 112, "num_lines": 131, "path": "/main_multi_run.py", "repo_name": "peteramazonian/simulation_project", "src_encoding": "UTF-8", "text": "import sys\nimport importlib\nfrom service_station import ServiceStation\nfrom system_arrival import SystemArrival\nfrom movement import Movement\nfrom time_generator import TimeGenerator\nfrom number_generator import NumberGenerator\nimport time_management\nfrom logger_multi_run import LoggerMR\n\n\nreplications = 100\nresult = []\nss_names = ['ss1', 'ss2', 'ss3']\nlogger = LoggerMR(ss_names, replications)\ni = 0\nwhile i < replications:\n importlib.reload(sys.modules['service_station'])\n importlib.reload(sys.modules['system_arrival'])\n importlib.reload(sys.modules['movement'])\n importlib.reload(sys.modules['time_management'])\n\n from service_station import ServiceStation\n from system_arrival import SystemArrival\n from movement import Movement\n\n # Its our simulation's main file.\n # Here we import classes and functions from other project files.\n # Then we need to make objects from our classes and set attributes.\n # These objects are used to setup the system in a modular way.\n # You can make as many service stations as you need with their own attributes, then arrange the whole system\n\n # ---------------------------------------------------------------------\n # Creating SystemArrival objects\n # ---------------------------------------------------------------------\n\n # -------- First SystemArrival object --------\n t_generator = TimeGenerator.Exponential(3) # Creating its TimeGenerator\n n_generator = NumberGenerator.Static(1) # Creating its NumberGenerator\n ief1 = SystemArrival(\"ief1\", t_generator, n_generator) # Creating first SystemArrival object\n del n_generator, t_generator\n\n # -------- Second SystemArrival object --------\n t_generator = TimeGenerator.Exponential(5) # Creating its TimeGenerator\n n_generator = NumberGenerator.Discrete((1, 2, 3, 4), (0.2, 0.3, 0.3, 0.2)) # Creating its NumberGenerator\n ief2 = SystemArrival(\"ief2\", t_generator, n_generator) # Creating first SystemArrival object\n del n_generator, t_generator\n\n # -------- Third SystemArrival object --------\n t_generator = TimeGenerator.Uniform(0, 120) # Creating its TimeGenerator\n n_generator = NumberGenerator.Poisson(30) # Creating its NumberGenerator\n ief3 = SystemArrival(\"ief3\", t_generator, n_generator) # Creating first SystemArrival object\n del n_generator, t_generator\n\n # ---------------------------------------------------------------------\n # Creating ServiceStation objects\n # ---------------------------------------------------------------------\n\n # -------- First ServiceStation object --------\n t_generator = TimeGenerator.DoubleTriangular(1, 2, 4, 1, 2, 3) # Creating its TimeGenerator\n ss1 = ServiceStation(\"ss1\", t_generator, 5) # Creating first ServiceStation object\n del t_generator\n\n # -------- Second ServiceStation object --------\n t_generator = TimeGenerator.Uniform(0.5, 2) # Creating its TimeGenerator\n ss2 = ServiceStation(\"ss2\", t_generator, 2) # Creating first ServiceStation object\n del t_generator\n\n # -------- Third ServiceStation object --------\n t_generator = TimeGenerator.Triangular(10, 20, 30) # Creating its TimeGenerator\n ss3 = ServiceStation(\"ss3\", t_generator, 30) # Creating first ServiceStation object\n del t_generator\n\n # ---------------------------------------------------------------------\n # Creating Movement objects\n # ---------------------------------------------------------------------\n\n m1 = Movement(TimeGenerator.Static(0))\n m2 = Movement(TimeGenerator.Exponential(0.5))\n m3 = Movement(TimeGenerator.Exponential(0.5))\n m4 = Movement(TimeGenerator.Exponential(1))\n\n Movement.check()\n\n # ---------------------------------------------------------------------\n # Creating Preliminary FEL\n # ---------------------------------------------------------------------\n ief1.set_first_arrival(0)\n ief2.set_first_arrival(0)\n ief3.set_single_arrival(60)\n ss1.set_rest_times([50, 110, 230, 290])\n ss2.set_rest_times([50, 110, 230, 290])\n\n # ---------------------------------------------------------------------\n # Set Duration\n # ---------------------------------------------------------------------\n es = 300\n time_management.set_end_of_simulation(es)\n\n # ---------------------------------------------------------------------\n # RUN!\n # ---------------------------------------------------------------------\n try:\n while True:\n time_management.advance_time()\n except time_management.SimulationDone:\n for ss in ServiceStation.list:\n ss.final_calculations()\n SystemArrival.final_calculations()\n logger.replication_logger(ServiceStation.list, SystemArrival)\n i += 1\n print('#' + str(i) + ' : Simulation DONE!')\n\n if i == 1:\n for ss in ServiceStation.list:\n result.append(ss.result)\n result.append(SystemArrival.result)\n else:\n for j, ss in enumerate(ServiceStation.list):\n for key, value in ss.result.items():\n result[j][key] += value\n for key, value in SystemArrival.result.items():\n result[-1][key] += value\n\n\nss_names.append('System')\nfor num, scope in enumerate(result):\n for key, value in scope.items():\n print(\"%s: %s = %s\" %(ss_names[num], key, round(value / replications, 10)))\nlogger.result_logger(ss_names, result)\nlogger.close_file()\n\n\n" }, { "alpha_fraction": 0.6349874138832092, "alphanum_fraction": 0.638351559638977, "avg_line_length": 50.69565200805664, "blob_id": "3c82209512b301fbdf3c4de74246c0b18a4abeba", "content_id": "78d0cad4502381b2e476193d947e3c6af15a4df1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2378, "license_type": "no_license", "max_line_length": 120, "num_lines": 46, "path": "/time_management.py", "repo_name": "peteramazonian/simulation_project", "src_encoding": "UTF-8", "text": "import bisect\n\n\n# ----------------------------------------------------------------------------------------------------------------\n# In this module we handle anything related to FEL and clock. in another word this module is the engine that makes\n# the code to move.\n# ----------------------------------------------------------------------------------------------------------------\n\n\nfel = [] # It's our simulation's main Future Event List.\nclock = 0 # It is the clock that we are in it right now, trying to handle future events and advance time.\n\n\ndef add_to_fel(event_notice: tuple): # This func will add a given tuple to our FEL, in the right place based on\n # event's clock.\n try:\n bisect.insort_left(fel, event_notice) # Bisect library provides a very efficient algorithm to add an object\n # in the right place in a SORTED list of objects to keep it sorted.\n except TypeError: # It will be used when two tuples are very exactly same except their functions passed.\n # bisect cant compare functions so it will return an error. After all it's some how impossible for two events\n # to be that much same.\n fel.append(event_notice)\n fel.sort(key=lambda x: x[0])\n\n\nclass SimulationDone(Exception): # It's an exception class that will raise the SimulationDone exception when we want.\n pass\n\n\ndef es(*args): # es is short form for End of Simulation. It will throw \"SimulationDone\" Exception when called.\n raise SimulationDone\n\n\ndef set_end_of_simulation(es_time): # It will add an \"es\" event to the fel at clock = es_time\n add_to_fel((es_time, es))\n\n\ndef advance_time(): # This function will check the FEL, and handle the very upcoming event and advances the clock.\n global clock\n tmp = fel[0] # Using tmp and delete the event notice from fel before handling it is necessary when we want to add\n # event notices to the current clock. E.g. when moving time between two parts equals 0\n del fel[0]\n clock = tmp[0] # Sets the clock to current event's clock.\n tmp[-1](tmp[-2]) # Calls the event notice's method which is placed in the last element of the tuple, with passing\n # the one before the last element as it's argument. the argument is mostly the user_ID\n return tmp # It will return the event notice just handled to the main file. it's used to log the event notice.\n" }, { "alpha_fraction": 0.6330845952033997, "alphanum_fraction": 0.6376451253890991, "avg_line_length": 33.4571418762207, "blob_id": "7fbf0b62aa2f2b62324b9a97c2104de22879ee7a", "content_id": "94d3766c84cfbe5a7044ce626934796f377466bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2412, "license_type": "no_license", "max_line_length": 112, "num_lines": 70, "path": "/system_arrival.py", "repo_name": "peteramazonian/simulation_project", "src_encoding": "UTF-8", "text": "import time_management\nfrom time_management import add_to_fel\n\n__id__ = 10000\n\n# TODO new arrivals in fel dont have id?!?\n\n\ndef id_generator():\n global __id__\n __id__ += 1\n return __id__\n\n\nclass SystemArrival:\n list = []\n costumers_inside_dict = {}\n costumers_departured = 0\n costumers_total_time = 0\n result = {}\n\n @classmethod\n def departure(cls, costumer_id):\n cls.costumers_departured += 1\n cls.costumers_total_time += time_management.clock - cls.costumers_inside_dict[costumer_id]\n cls.costumers_inside_dict.pop(costumer_id)\n\n def __init__(self, name, inter_arrival_time_generator, number_of_arrivals_generator):\n self.name = name\n self.time_generator = inter_arrival_time_generator\n self.number_generator = number_of_arrivals_generator\n SystemArrival.list.append(self)\n self.m_list = __import__('movement').Movement.list\n\n # Overriding Python's original __repr__ function\n def __repr__(self):\n return self.name\n\n def set_first_arrival(self, beginning_time):\n event_notice = (\n self.time_generator.generate() + beginning_time, self.name, self.number_generator.generate(),\n self.new_arrival)\n add_to_fel(event_notice)\n\n def new_arrival(self, number_of_arrivals):\n for i in range(number_of_arrivals):\n id_tmp = id_generator()\n SystemArrival.costumers_inside_dict[id_tmp] = time_management.clock\n self.m_list[0].move(id_tmp)\n # generating next arrival event\n event_notice = (\n self.time_generator.generate() + time_management.clock, self.name, self.number_generator.generate(),\n self.new_arrival)\n add_to_fel(event_notice)\n\n def set_single_arrival(self, beginning_time):\n event_notice = (\n self.time_generator.generate() + beginning_time, self.name, self.number_generator.generate(),\n self.new_single_arrival)\n add_to_fel(event_notice)\n\n def new_single_arrival(self, number_of_arrivals):\n for i in range(number_of_arrivals):\n id_tmp = id_generator()\n SystemArrival.costumers_inside_dict[id_tmp] = time_management.clock\n self.m_list[0].move(id_tmp)\n\n @classmethod\n def final_calculations(cls):\n cls.result = dict(average_time_in_system=cls.costumers_total_time / cls.costumers_departured)\n" }, { "alpha_fraction": 0.4601418375968933, "alphanum_fraction": 0.4882269501686096, "avg_line_length": 34.96938705444336, "blob_id": "eb6cf17987d11daa3eef53fd183e90dfacffaa0c", "content_id": "30cbd1dd5cef6619bb94cb3943af9e5e6e22d591", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3525, "license_type": "no_license", "max_line_length": 128, "num_lines": 98, "path": "/time_generator.py", "repo_name": "peteramazonian/simulation_project", "src_encoding": "UTF-8", "text": "\"\"\" Random time generators to be used for inter arrival time or activity time in simulation models.\n\"\"\"\n\nimport random\nfrom math import sqrt, log\n\n\nclass TimeGenerator:\n class Uniform(random.Random):\n def __init__(self, lower_limit=0, upper_limit=1, **kwargs):\n self.x = None\n self.lower_limit = lower_limit\n self.upper_limit = upper_limit\n for key, value in kwargs.items():\n if key == \"seed\":\n setattr(self, \"x\", value)\n super().__init__(self.x)\n\n def generate(self):\n return round(self.random() * (self.upper_limit - self.lower_limit) + self.lower_limit, 3)\n\n class Static():\n def __init__(self, x=0):\n self.x = x\n\n def generate(self):\n return self.x\n\n class Exponential(random.Random):\n def __init__(self, mean=1, **kwargs):\n self.x = None\n self.rate = 1 / mean\n for key, value in kwargs.items():\n if key == \"seed\":\n setattr(self, \"x\", value)\n super().__init__(self.x)\n\n def generate(self):\n rnd = self.random()\n return round(-1 / self.rate * log(rnd), 3)\n\n class Triangular(random.Random):\n def __init__(self, lower_limit=0, mode=.5, upper_limit=1, **kwargs):\n self.x = None\n self.a = lower_limit\n self.b = upper_limit\n self.c = mode\n self.Fc = (self.c - self.a) / (self.b - self.a)\n for key, value in kwargs.items():\n if key == \"seed\":\n setattr(self, \"x\", value)\n super().__init__(self.x)\n\n def generate(self):\n rnd = self.random()\n if rnd < self.Fc:\n return round(self.a + sqrt(rnd * (self.b - self.a) * (self.c - self.a)), 3)\n return round(self.b - sqrt((1 - rnd) * (self.b - self.a) * (self.b - self.c)), 3)\n\n class DoubleTriangular(random.Random):\n def __init__(self, lower_limit_1=0, mode_1=0.5, upper_limit_1=1, lower_limit_2=0, mode_2=.5, upper_limit_2=1, **kwargs):\n self.x = None\n self.a1 = lower_limit_1\n self.b1 = upper_limit_1\n self.c1 = mode_1\n self.a2 = lower_limit_2\n self.b2 = upper_limit_2\n self.c2 = mode_2\n self.Fc1 = (self.c1 - self.a1) / (self.b1 - self.a1)\n self.Fc2 = (self.c2 - self.a2) / (self.b2 - self.a2)\n for key, value in kwargs.items():\n if key == \"seed\":\n setattr(self, \"x\", value)\n super().__init__(self.x)\n\n def generate(self):\n rnd1 = self.random()\n rnd2 = self.random()\n\n if rnd1 < self.Fc1:\n t1 = round(self.a1 + sqrt(rnd1 * (self.b1 - self.a1) * (self.c1 - self.a1)), 3)\n else:\n t1 = round(self.b1 - sqrt((1 - rnd1) * (self.b1 - self.a1) * (self.b1 - self.c1)), 3)\n\n if rnd2 < self.Fc2:\n t2 = round(self.a2 + sqrt(rnd2 * (self.b2 - self.a2) * (self.c2 - self.a2)), 3)\n else:\n t2 = round(self.b2 - sqrt((1 - rnd2) * (self.b2 - self.a2) * (self.b2 - self.c2)), 3)\n\n return t1 + t2\n\n class DT:\n def __init__(self, triangular_obj_1, triangular_obj_2):\n self.t1 = triangular_obj_1\n self.t2 = triangular_obj_2\n\n def generate(self):\n return self.t1.generate() + self.t2.generate()\n" }, { "alpha_fraction": 0.6233356595039368, "alphanum_fraction": 0.6275767087936401, "avg_line_length": 60.072288513183594, "blob_id": "962715df51c0376a2406475ce138a260cc574649", "content_id": "a707fb130d4f9c093ce3de18d5a4eff9d98451e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10139, "license_type": "no_license", "max_line_length": 130, "num_lines": 166, "path": "/service_station.py", "repo_name": "peteramazonian/simulation_project", "src_encoding": "UTF-8", "text": "import time_management\nfrom time_management import add_to_fel, postponed_rest_log_editor\n\n\n# ----------------------------------------------------------------\n# Creating class ServiceStation\n# Our service stations are objects of this class\n# Costumer arrivals, departures, servers leaving for rest and getting back to work are handled here\n# ----------------------------------------------------------------\n# event notices created here are as follow:\n# station departure: (time, Di, costumer_id, method)\n# server rest: (time, Ri, method)\n# server back: (time, Bi, method)\n\nclass ServiceStation:\n list = []\n\n def __init__(self, name, service_time_generator, num_of_servers):\n self.name = name # What you call this station in real world\n self.service_time_generator = service_time_generator # Service_time_generator is an object of TimeGenerator cls\n self.num_of_servers = num_of_servers # Number of servers working in this ServiceStation\n self.available_servers = num_of_servers\n self.busy_servers = 0 # Number of busy servers at the beginning of the simulation. Usually equals to 0\n self.queue_list = [] # List of costumers waiting in queue for this station. queue_list elements:\n # (queue_joined_time, costumer_id)\n self.rest_in_waiting = 0 # When there is a server waiting to finish the serve, then go to rest, this will be\n # equal to 1\n self.server_rest_duration = 10 # How long is each server's rest duration\n self.position = len(ServiceStation.list) + 1\n ServiceStation.list.append(self)\n self.m_list = __import__('movement').Movement.list\n self.result = {}\n # --------------------------------------------------------\n # Variables to measure system evaluation parameters:\n self.q_len_cumulative = 0\n self.q_len_last_clock = 0\n self.q_len_max = 0\n # ---\n self.service_total_time = 0\n self.service_total_count = 0\n # ---\n self.servers_total_busy_t = 0 # Sum of busy servers * time in different periods\n self.servers_busy_last_clock = 0 # Last time the busy servers number changed\n self.servers_total_available_t = 0 # Sum of available servers * time in different periods\n self.servers_available_last_clock = 0 # Last time the available servers number changed\n # ---\n self.queue_delay_cumulative = 0 # Total time costumers waited in queue\n # ---\n # TODO edit this\n self.queue_total_time = 0\n\n # Overriding Python's original __repr__ function\n def __repr__(self):\n return self.name\n\n def return_printables(self):\n return([self.available_servers, self.busy_servers, len(self.queue_list), self.rest_in_waiting,\n self.q_len_cumulative, self.q_len_max, self.service_total_time, self.service_total_count,\n self.queue_delay_cumulative, self.queue_total_time, self.servers_total_busy_t,\n self.servers_total_available_t])\n\n # Handles arrivals to this station.\n def arrival(self, costumer_id):\n if self.busy_servers < self.available_servers: # No waiting in Queue\n self.servers_total_busy_t += self.busy_servers * (time_management.clock - self.servers_busy_last_clock)\n self.servers_busy_last_clock = time_management.clock\n self.busy_servers += 1\n event_duration = self.service_time_generator.generate()\n event_notice = (\n event_duration + time_management.clock, \"D\" + str(self.position), costumer_id, self.departure)\n add_to_fel(event_notice) # Generating departure event for this costumer.\n self.service_total_time += event_duration\n self.service_total_count += 1\n else: # Waiting in queue\n self.q_len_cumulative += len(self.queue_list) * (time_management.clock - self.q_len_last_clock)\n self.queue_total_time += int(bool(len(self.queue_list))) * (time_management.clock - self.q_len_last_clock)\n self.q_len_last_clock = time_management.clock\n self.queue_list.append((time_management.clock, costumer_id)) # Adding costumer to queue\n if len(self.queue_list) > self.q_len_max:\n self.q_len_max = len(self.queue_list)\n\n # Handles all departures from this station. departure will happen when service ends for one costumer.\n def departure(self, costumer_id):\n if not self.rest_in_waiting: # If there is no server waiting to get rest.\n if self.queue_list.__len__() > 0:\n event_duration = self.service_time_generator.generate()\n event_notice = (\n event_duration + time_management.clock, \"D\" + str(self.position), self.queue_list[0][1],\n self.departure)\n add_to_fel(event_notice) # Generating departure event for next costumer waiting in queue.\n self.service_total_time += event_duration\n self.service_total_count += 1\n self.q_len_cumulative += len(self.queue_list) * (time_management.clock - self.q_len_last_clock)\n self.queue_total_time += int(bool(len(self.queue_list))) * (\n time_management.clock - self.q_len_last_clock)\n self.q_len_last_clock = time_management.clock\n self.queue_delay_cumulative += time_management.clock - self.queue_list[0][0]\n del self.queue_list[0] # Deleting the costumer which starts getting service, from queue.\n else:\n self.servers_total_busy_t += self.busy_servers * (time_management.clock - self.servers_busy_last_clock)\n self.servers_busy_last_clock = time_management.clock\n self.busy_servers -= 1\n else: # If there is a server waiting to get rest\n self.servers_total_busy_t += self.busy_servers * (time_management.clock - self.servers_busy_last_clock)\n self.servers_busy_last_clock = time_management.clock\n self.busy_servers -= 1 # The server is no longer busy\n self.rest_in_waiting = 0 # so there is no busy server, waiting to get rest\n event_notice = (time_management.clock, \"R\" + str(self.position), self.server_rest)\n add_to_fel(event_notice) # Generating the new server rest event notice\n # Adding this new event notice to fel is necessary for fel logging\n self.m_list[self.position].move(costumer_id)\n\n # Handles server rest periods. in this model, server rest event notices are initialized in fel.\n def server_rest(self, *args):\n if self.busy_servers < self.available_servers:\n self.servers_total_available_t += self.available_servers * (time_management.clock - self.servers_available_last_clock)\n self.servers_available_last_clock = time_management.clock\n self.available_servers -= 1\n event_notice = (self.server_rest_duration + time_management.clock, \"B\" + str(self.position), self.server_back)\n add_to_fel(event_notice) # Generates event notice for server coming back from rest after 10 mins.\n else:\n self.rest_in_waiting = 1 # It's used in departure() method.\n postponed_rest_log_editor()\n\n # Handles when a server is back from rest and starts serving a new costumer if queue is not empty.\n def server_back(self, *args):\n self.servers_total_available_t += self.available_servers * (time_management.clock - self.servers_available_last_clock)\n self.servers_available_last_clock = time_management.clock\n self.available_servers += 1\n if self.queue_list.__len__() > 0:\n self.servers_total_busy_t += self.busy_servers * (time_management.clock - self.servers_busy_last_clock)\n self.servers_busy_last_clock = time_management.clock\n self.busy_servers += 1\n event_duration = self.service_time_generator.generate()\n event_notice = (\n event_duration + time_management.clock, \"D\" + str(self.position), self.queue_list[0][1],\n self.departure)\n add_to_fel(event_notice) # Generating departure event for next costumer waiting in queue.\n self.service_total_time += event_duration\n self.service_total_count += 1\n self.q_len_cumulative += len(self.queue_list) * (time_management.clock - self.q_len_last_clock)\n self.queue_total_time += int(bool(len(self.queue_list))) * (time_management.clock - self.q_len_last_clock)\n self.q_len_last_clock = time_management.clock\n self.queue_delay_cumulative += time_management.clock - self.queue_list[0][0]\n del self.queue_list[0] # Deleting the costumer which starts getting service, from queue.\n\n def set_rest_times(self, rest_times_list):\n for t in rest_times_list:\n event_notice = (t, \"R\" + str(self.position), self.server_rest)\n add_to_fel(event_notice)\n\n def final_calculations(self):\n self.q_len_cumulative += len(self.queue_list) * (time_management.clock - self.q_len_last_clock)\n self.queue_total_time += int(bool(len(self.queue_list))) * (time_management.clock - self.q_len_last_clock)\n self.servers_total_busy_t += self.busy_servers * (time_management.clock - self.servers_busy_last_clock)\n self.servers_total_available_t += self.available_servers * (\n time_management.clock - self.servers_available_last_clock)\n\n self.result = dict(\n total_wait_time=(self.service_total_time + self.queue_delay_cumulative) / self.service_total_count,\n average_queue_delay=self.queue_delay_cumulative / self.service_total_count,\n average_queue_length=self.q_len_cumulative / time_management.clock,\n maximum_queue_length=self.q_len_max,\n servers_efficiency=self.servers_total_busy_t / self.servers_total_available_t,\n queue_busy_percentage=self.queue_total_time / time_management.clock\n )\n\n" } ]
10
leonsooi/ngskintoolsplus
https://github.com/leonsooi/ngskintoolsplus
bbf56d92eedd850b6f19536debb5da2e9e003d65
8082de3830c499127ff5dda6b1fb967c614c4cd4
bbe310ca241aee12744392b6af62af1f0599ee09
refs/heads/master
2021-01-16T19:14:25.019073
2014-10-04T17:01:54
2014-10-04T17:01:54
33,089,226
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6334365606307983, "alphanum_fraction": 0.644994854927063, "avg_line_length": 33.37956237792969, "blob_id": "9e20b8f721968b51b95c927fe91f52234eba335b", "content_id": "6f6a4901aa440b536f7e2caa92261871e6252066", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4845, "license_type": "no_license", "max_line_length": 106, "num_lines": 137, "path": "/ngSkinToolsPlus/ngSkinToolsPlus/lib/weights.py", "repo_name": "leonsooi/ngskintoolsplus", "src_encoding": "UTF-8", "text": "'''\r\nCreated on Mar 25, 2014\r\n\r\n@author: Leon\r\n'''\r\nimport maya.cmds as mc\r\nimport pymel.core as pm\r\n\r\nimport utils.rigging as rt\r\n\r\nmel = pm.language.Mel()\r\n\r\ndef smoothLayerMask(mll, layerId, intensity=1.0):\r\n '''\r\n '''\r\n mll.setCurrentLayer(layerId)\r\n mll.ngSkinLayerCmd(cpt='mask')\r\n \r\n # if intensity is larger than 1.0, use multiple iterations\r\n while intensity > 1.0:\r\n mll.ngSkinLayerCmd(paintOperation=4, paintIntensity=1.0)\r\n mll.ngSkinLayerCmd(paintFlood=True)\r\n intensity = intensity - 1.0\r\n \r\n mll.ngSkinLayerCmd(paintOperation=4, paintIntensity=intensity)\r\n mll.ngSkinLayerCmd(paintFlood=True)\r\n \r\n \r\ndef relaxLayerWeights(mll, layerId, expand=True, \r\n relaxSteps=33, relaxSize=0.1708, relaxAllAmount=0.5):\r\n '''\r\n relax all weights on layer\r\n verts closest to joints will be masked\r\n expand will expand the mask\r\n '''\r\n infIter = mll.listLayerInfluences(2)\r\n infs = list(infIter)\r\n mesh = mll.getTargetInfo()[0]\r\n mesh = pm.PyNode(mesh)\r\n \r\n # get vert closest to joints\r\n vertIds = []\r\n for inf, infId in infs:\r\n pos = pm.PyNode(inf).getTranslation(space='world')\r\n faceId = mesh.getClosestPoint(pos, space='world')[1]\r\n faceVertIds = mesh.f[faceId].getVertices()\r\n closestVertId = min(faceVertIds, key=lambda vtxId: (mesh.vtx[vtxId].getPosition() - pos).length())\r\n \r\n closestVertIds = [closestVertId]\r\n # expand ids if needed\r\n if expand:\r\n connectedVertices = mesh.vtx[closestVertId].connectedVertices()\r\n closestVertIds += [vtx.index() for vtx in connectedVertices]\r\n \r\n vertIds += closestVertIds\r\n \r\n vertCount = mll.getVertCount()\r\n \r\n # invert vertIds\r\n # just use strings since we're going to pass into ngSkinRelax\r\n vertsToRelax = [mesh.name() + '.vtx[%d]' % id_ for id_ in range(vertCount) if id_ not in vertIds]\r\n \r\n args = {}\r\n args['numSteps']=relaxSteps\r\n args['stepSize']=relaxSize\r\n mel.ngSkinRelax(vertsToRelax,**args)\r\n \r\n # run another relax to clean up any artefacts\r\n # relax all\r\n args = {}\r\n args['numSteps']=int(relaxSteps * relaxAllAmount)\r\n args['stepSize']=relaxSize * relaxAllAmount\r\n mel.ngSkinRelax(mesh.name(),**args)\r\n \r\n \r\n\r\ndef createWeightsListByPolyStrip(outerXfos, innerXfos, mesh, loops=0):\r\n '''\r\n returns weights as a float list\r\n innerVerts will be weighted to 1\r\n loops [int]: number of loops the polyStrip will have\r\n 0 means an instant falloff from inner to outer\r\n 1 means falloff after 50%, etc...\r\n '''\r\n polyStrip, outerVerts, innerVerts = createPolyLoftStrip('temp_weights_', outerXfos, innerXfos, loops)\r\n # bind polystrip to temporary jnts\r\n pm.select(cl=True)\r\n weightBnd = pm.joint(n='temp_weight_bnd')\r\n pm.select(cl=True)\r\n noWeightBnd = pm.joint(n='temp_noWeight_bnd')\r\n sknStrip = pm.skinCluster(weightBnd, noWeightBnd, polyStrip)\r\n # set weights to polystrip\r\n sknStrip.setWeights(innerVerts, [0], [1])\r\n sknStrip.setWeights(outerVerts, [1], [1])\r\n # create temp mesh to transfer weights to\r\n tempMesh = pm.duplicate(mesh)[0]\r\n sknMesh = pm.skinCluster(weightBnd, noWeightBnd, tempMesh)\r\n pm.copySkinWeights(ss=sknStrip, ds=sknMesh, ia='oneToOne', sa='closestPoint', nm=1)\r\n # add weights to a float list\r\n weightsIter = sknMesh.getWeights(tempMesh, 0)\r\n weightsList = list(weightsIter)\r\n # cleanup\r\n pm.delete(polyStrip, tempMesh, weightBnd, noWeightBnd)\r\n return weightsList\r\n \r\n \r\ndef createPolyLoftStrip(name, outerXfos, innerXfos, loops):\r\n '''\r\n name [string]\r\n takes two lists of transforms (as strings),\r\n returns poly mesh lofted between the two loops\r\n also returns two lists of verts (outer and inner)\r\n '''\r\n # create curves\r\n outerCrv = rt.makeCrvThroughObjs(outerXfos, 'temp_outer_crv', False, 3)\r\n mc.closeCurve(outerCrv, preserveShape=0, rpo=True)\r\n innerCrv = rt.makeCrvThroughObjs(innerXfos, 'temp_inner_crv', False, 3)\r\n mc.closeCurve(innerCrv, preserveShape=0, rpo=True)\r\n \r\n outerCrv = pm.PyNode(outerCrv)\r\n innerCrv = pm.PyNode(innerCrv)\r\n \r\n # rebuild crvs so they can be lofted\r\n maxSpans = max(outerCrv.numSpans(), innerCrv.numSpans())\r\n pm.rebuildCurve(outerCrv, rpo=True, spans=maxSpans, kr=2)\r\n pm.rebuildCurve(innerCrv, rpo=True, spans=maxSpans, kr=2)\r\n \r\n # loft crvs\r\n polyStrip = pm.loft(outerCrv, innerCrv, d=1, n=name+'polyStrip_geo', \r\n polygon=1, ch=0, sectionSpans=loops+1)[0]\r\n outerVerts = polyStrip.vtx[0:maxSpans-1]\r\n innerVerts = polyStrip.vtx[maxSpans:]\r\n \r\n # cleanup\r\n pm.delete(outerCrv, innerCrv)\r\n \r\n return polyStrip, outerVerts, innerVerts" }, { "alpha_fraction": 0.6309707164764404, "alphanum_fraction": 0.6328967809677124, "avg_line_length": 30.462499618530273, "blob_id": "abd123db257eb11a7a8c5d21f81dfea9847e85cb", "content_id": "3ea90bf6af9f222923fa47ee8ae667ece5fe45ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5192, "license_type": "no_license", "max_line_length": 93, "num_lines": 160, "path": "/ngSkinToolsPlus/ngSkinToolsPlus/utilities/__init__.py", "repo_name": "leonsooi/ngskintoolsplus", "src_encoding": "UTF-8", "text": "from ngSkinTools.mllInterface import MllInterface\r\nfrom ngSkinTools.importExport import LayerData, Layer, Influence\r\nfrom ngSkinTools.importExport import XmlImporter\r\nimport maya.cmds as cmds\r\n\r\nimport pymel.core as pm\r\n\r\n'''\r\nQuick hacks just to get the job done when needed. Should be modularized properly some time...\r\n'''\r\n\r\n'''\r\nUSEFUL UTILITIES\r\n'''\r\n\r\ndef soloLayer(mll, layerId):\r\n '''\r\n enabled layerId, disables the rest\r\n '''\r\n allLayers = mll.listLayers()\r\n \r\n for curLayerId, _layerName in allLayers:\r\n mll.setLayerEnabled(curLayerId, layerId==curLayerId)\r\n \r\n\r\ndef unifyMask(vertsList, mll, layerId):\r\n '''\r\n average mask weights on vertsList\r\n '''\r\n maskWts = mll.getLayerMask(layerId)\r\n vertsNum = len(vertsList)\r\n vertsWeights = [maskWts[vertId] for vertId in vertsList]\r\n avgWeight = sum(vertsWeights)/vertsNum\r\n for vertId in vertsList:\r\n maskWts[vertId] = avgWeight\r\n mll.setLayerMask(layerId, maskWts)\r\n \r\ndef reverseMask(mll, layerId):\r\n '''\r\n '''\r\n maskWts = mll.getLayerMask(layerId)\r\n revMaskWts = [1-wt for wt in maskWts]\r\n mll.setLayerMask(layerId, revMaskWts)\r\n \r\n \r\n \r\n'''\r\nutilities to print out layer data (for troubleshooting purposes, etc)\r\nalso, if the influence long names have changed\r\nwe can use this to find match influences by shortName, and update the longNames\r\nobviously, it assumes that names are unique!\r\n'''\r\ndef loadXmlFile(filepath):\r\n '''\r\n # example process for importing XML data\r\n filepath = r\"C:\\Users\\Leon\\Documents\\maya\\projects\\Ori\\scenes\\ori_body_weights_v037.xml\"\r\n xml = loadXmlFile(filepath)\r\n from ngSkinTools.importExport import XmlImporter\r\n # create layers from\r\n importer = XmlImporter()\r\n # load layer data\r\n data = importer.process(xml)\r\n '''\r\n f = open(filepath, 'r')\r\n try:\r\n contents = ''.join(f.readlines())\r\n finally:\r\n f.close();\r\n \r\n importer = XmlImporter()\r\n data = importer.process(contents)\r\n return data\r\n\r\ndef findUnmatchedInfluences(data, printOut=True):\r\n '''\r\n parse data and find unmatchable influences\r\n \r\n findUnmatchedInfluences(data)\r\n '''\r\n unmatched = []\r\n for influence in data.getAllInfluences():\r\n if not pm.objExists(influence):\r\n unmatched.append(influence.split('|')[-1])\r\n if printOut:\r\n print unmatched\r\n return unmatched\r\n\r\ndef matchInfluencesByNodeName(data):\r\n '''\r\n match influences by nodeName\r\n assumes all influence names are unique\r\n \r\n matchInfluencesByNodeName(data)\r\n data.saveTo('GEO:CT_body_geo')\r\n '''\r\n for layer in data.layers:\r\n for influence in layer.influences:\r\n oldLongName = influence.influenceName\r\n shortName = oldLongName.split('|')[-1]\r\n newLongName = cmds.ls(shortName, l=True)[0]\r\n influence.influenceName = newLongName\r\n\r\ndef editJson(jsonDict):\r\n for eachLayer in jsonDict[\"layers\"]:\r\n print eachLayer[\"name\"]\r\n for eachInf in eachLayer[\"influences\"]:\r\n print eachInf[\"name\"]\r\n name = eachInf[\"name\"]\r\n shortName = name.split('|')[-1]\r\n print shortName\r\n replacedName = shortName.replace('CT_', 'CT_lips_')\r\n replacedName = shortName.replace('LT_', 'LT_lips_')\r\n replacedName = shortName.replace('RT_', 'RT_lips_')\r\n eachInf[\"name\"] = replacedName\r\n\r\ndef editLayerData(data):\r\n for eachLayer in data.layers:\r\n print eachLayer.name\r\n for eachInfluence in eachLayer.influences:\r\n print eachInfluence.influenceName\r\n oldLongName = eachInfluence.influenceName\r\n oldShortName = oldLongName.split('|')[-1]\r\n print oldShortName\r\n newShortName = oldShortName.replace('T_', 'T_lips_')\r\n print newShortName\r\n newLongName = cmds.ls(newShortName, l=True)[0]\r\n print newLongName\r\n eachInfluence.influenceName = newLongName\r\n\r\ndef selectInfluencesInLayerData(data):\r\n cmds.select(cl=True)\r\n for eachLayer in data.layers:\r\n print eachLayer.name\r\n for eachInfluence in eachLayer.influences:\r\n print eachInfluence.influenceName\r\n cmds.select(eachInfluence.influenceName, add=True)\r\n\r\ndef retModel(jsonDict):\r\n model = LayerData()\r\n \r\n if jsonDict.has_key(\"manualInfluenceOverrides\"):\r\n model.mirrorInfluenceAssociationOverrides = jsonDict['manualInfluenceOverrides']\r\n \r\n for layerData in jsonDict[\"layers\"]:\r\n layer = Layer()\r\n model.addLayer(layer) \r\n layer.enabled = layerData['enabled']\r\n layer.mask = layerData['mask']\r\n layer.name = layerData['name']\r\n layer.opacity = layerData['opacity']\r\n layer.influences = []\r\n\r\n for influenceData in layerData['influences']:\r\n influence = Influence()\r\n layer.addInfluence(influence)\r\n influence.weights = influenceData['weights']\r\n influence.logicalIndex = influenceData['index']\r\n influence.influenceName = influenceData['name']\r\n \r\n return model" }, { "alpha_fraction": 0.563766360282898, "alphanum_fraction": 0.5685339570045471, "avg_line_length": 31.918367385864258, "blob_id": "85b1fab2e251fe557b9f8fd0bfa97e345902c91f", "content_id": "ddc718ff0cdd79b1ca21e3cf1b81d643555c3893", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1678, "license_type": "no_license", "max_line_length": 72, "num_lines": 49, "path": "/ngSkinToolsPlus/ngSkinToolsPlus/utilities/influenceAssociation.py", "repo_name": "leonsooi/ngskintoolsplus", "src_encoding": "UTF-8", "text": "'''\r\nCreated on 01/09/2013\r\n\r\n@author: Leon\r\n'''\r\n\r\nclass InfluenceAssociation():\r\n '''\r\n classdocs\r\n '''\r\n\r\n def __init__(self, srcInfluences, destInfluences, method):\r\n '''\r\n srcInfluences and destInfluences are iterators returned\r\n from mll.listLayerInfluences(layerId, activeInfluences=False)\r\n (activeInfluences should be set to False, in case we\r\n need to match to influences that are currently inactive.)\r\n \r\n method - match by \"name\", \"label\", \"closestJoint\",\r\n \"closestBone\", or \"oneToOne\"\r\n '''\r\n \r\n # create a dictionary with the format -\r\n # {influenceIndex on srcMll : influenceIndex on destMll,...}\r\n self.matchDict = {}\r\n \r\n if method == 'name':\r\n self.matchByName(srcInfluences, destInfluences)\r\n \r\n \r\n def matchByName(self, srcInfluences, destInfluences):\r\n '''\r\n '''\r\n srcDict = {}\r\n for influenceName, influenceIndex in srcInfluences:\r\n srcDict[influenceIndex] = influenceName\r\n \r\n destDict = {}\r\n for influenceName, influenceIndex in destInfluences:\r\n destDict[influenceName] = influenceIndex\r\n \r\n for influenceIndex, influenceName in srcDict.items():\r\n # search for the same name in destDict\r\n if influenceName in destDict.keys():\r\n # index of srcInfluence = index of destInfluence\r\n self.matchDict[influenceIndex] = destDict[influenceName]\r\n \r\n def __getitem__(self, srcIndex):\r\n return self.matchDict[srcIndex]\r\n " }, { "alpha_fraction": 0.4842105209827423, "alphanum_fraction": 0.49590644240379333, "avg_line_length": 21.97058868408203, "blob_id": "40f4cdbe29e2d67619b6df2bc455e58b1858d1c1", "content_id": "6fde10a080adde68f28e4d1d948b8347cf586d38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 855, "license_type": "no_license", "max_line_length": 108, "num_lines": 34, "path": "/ngSkinToolsPlus/ngSkinToolsPlus/utilities/surfaceAssociation.py", "repo_name": "leonsooi/ngskintoolsplus", "src_encoding": "UTF-8", "text": "'''\r\nCreated on 01/09/2013\r\n\r\n@author: Leon\r\n'''\r\nimport pymel.core as pm\r\n\r\nclass SurfaceAssociation():\r\n '''\r\n classdocs\r\n '''\r\n\r\n\r\n def __init__(self, srcMesh, destMesh, method):\r\n '''\r\n Constructor\r\n '''\r\n \r\n # create dictionary with the format -\r\n # {vertexId on srcMesh : ((vertexId1 on destMesh, weight), (vertexId2 on destMesh, weight)...), ...}\r\n self.matchDict = {}\r\n \r\n # convert to PyNodes\r\n srcMesh = pm.PyNode(srcMesh)\r\n destMesh = pm.PyNode(destMesh)\r\n \r\n if method == 'closestComponent':\r\n self.matchByClosestComponent(srcMesh, destMesh)\r\n \r\n \r\n def matchByClosestComponent(self, srcMesh, destMesh):\r\n '''\r\n populate self.matchDict\r\n '''\r\n \r\n\r\n \r\n \r\n " }, { "alpha_fraction": 0.6287015676498413, "alphanum_fraction": 0.6560364365577698, "avg_line_length": 19, "blob_id": "cee052ff6df3ccfb3d0d9ed7c46b4e0c577391f1", "content_id": "0521735ab2727c9dedd7bef8b427ae998dec6c2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 439, "license_type": "no_license", "max_line_length": 65, "num_lines": 21, "path": "/ngSkinToolsPlus/ngSkinToolsPlus/misc/tests.py", "repo_name": "leonsooi/ngskintoolsplus", "src_encoding": "UTF-8", "text": "'''\r\nCreated on Mar 22, 2014\r\n\r\n@author: Leon\r\n'''\r\n\r\nimport maya.cmds as mc\r\n\r\n# assign weights by nearest joint\r\nargs = {}\r\nargs['bnj'] = True\r\nselJnts = ['joint1', 'joint2']\r\nargs['ij'] = '/'.join(selJnts)\r\nargs['intensity'] = 1.0\r\n\r\n# must select mesh or components first\r\n# must select layer or mll.setCurrentLayer(layerId)\r\nmc.ngAssignWeights(**args)\r\n\r\nselJnts = []\r\nmc.ngAssignWeights(bnj=True, ij='/'.join(selJnts), intensity=1.0)" }, { "alpha_fraction": 0.58980393409729, "alphanum_fraction": 0.5964705944061279, "avg_line_length": 29.899999618530273, "blob_id": "d070c93ba7d0ac3513a31bd24820740106fdafb1", "content_id": "916786f1f9c03f27f4298716d8ce3d7211a49bbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2550, "license_type": "no_license", "max_line_length": 147, "num_lines": 80, "path": "/ngSkinToolsPlus/ngSkinToolsPlus/utilities/copyLayers.py", "repo_name": "leonsooi/ngskintoolsplus", "src_encoding": "UTF-8", "text": "'''\r\nCreated on 31/08/2013\r\n\r\n@author: Leon\r\n'''\r\n\r\nfrom ngSkinTools.mllInterface import MllInterface\r\nfrom ngSkinToolsPlus.utilities.influenceAssociation import InfluenceAssociation\r\n\r\nimport re\r\n\r\nclass CopyLayers:\r\n '''\r\n Copy layers across mesh utility\r\n '''\r\n\r\n def __init__(self):\r\n '''\r\n Constructor\r\n '''\r\n self.layerIds = []\r\n self.srcMll = MllInterface\r\n self.destMll = MllInterface\r\n self.copyIds = []\r\n \r\n def setMllInterface(self, srcMll, destMll):\r\n self.srcMll = srcMll\r\n self.destMll = destMll\r\n \r\n def copyLayer(self, layerId):\r\n '''\r\n copies single layer\r\n \r\n example use:\r\n testCopy = CopyLayers()\r\n srcMll = MllInterface()\r\n srcMll.setCurrentMesh('pPlane1')\r\n destMll = MllInterface()\r\n destMll.setCurrentMesh('pPlane3')\r\n \r\n testCopy.setMllInterface(srcMll, destMll)\r\n testCopy.copyLayer(3)\r\n '''\r\n oldName = self.srcMll.getLayerName(layerId)\r\n newLayer = self.destMll.createLayer(self.createUniqueName(oldName))\r\n self.destMll.setLayerMask(newLayer, self.srcMll.getLayerMask(layerId))\r\n \r\n influenceMatcher = InfluenceAssociation(self.srcMll.listLayerInfluences(layerId, True), self.destMll.listLayerInfluences(0, False), \"name\")\r\n \r\n for _, influenceIndex in self.srcMll.listLayerInfluences(layerId):\r\n weights = self.srcMll.getInfluenceWeights(layerId, influenceIndex)\r\n self.destMll.setInfluenceWeights(newLayer, influenceMatcher[influenceIndex], weights)\r\n \r\n self.copyIds.append(layerId)\r\n \r\n \r\n # two procedures copied from DuplicateLayers class\r\n # for getting a unique name for the new layer\r\n def createLayerName(self,oldName):\r\n prefix=\" copy\"\r\n \r\n # copy already? add index\r\n if oldName.endswith(prefix):\r\n return oldName+\"(2)\"\r\n \r\n # indexing exists? increase value\r\n s=re.search('(.*)\\\\((\\\\d+)\\\\)$',oldName)\r\n if s!=None:\r\n return s.group(1)+\"(%d)\"%(int(s.group(2))+1,) \r\n \r\n # nothing? just add default copy prefix then\r\n return oldName+prefix\r\n \r\n def createUniqueName(self,fromName):\r\n layerNames = [l[1] for l in self.destMll.listLayers()]\r\n result = self.createLayerName(fromName)\r\n while result in layerNames:\r\n result = self.createLayerName(result)\r\n \r\n return result" } ]
6
vrinda-90/publish-json
https://github.com/vrinda-90/publish-json
52dd673810ea1e4c98704f490229de25dd62bf9c
cfe89501805d6b959205ba6da620f24ffdb4e9e9
ad930524974b05eb4a6b3062e7db4307bf16b230
refs/heads/master
2023-03-24T15:13:06.790765
2021-03-15T06:14:48
2021-03-15T06:14:48
347,857,302
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6654492616653442, "alphanum_fraction": 0.672023355960846, "avg_line_length": 27.52083396911621, "blob_id": "c0d18827bcee3d965518949e4509c3983812d463", "content_id": "e25f0e5a8ef201fcaea699c2c8f1c356706ad490", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1369, "license_type": "no_license", "max_line_length": 74, "num_lines": 48, "path": "/main.py", "repo_name": "vrinda-90/publish-json", "src_encoding": "UTF-8", "text": "import os\nimport json\nfrom google.cloud import pubsub_v1\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n#add project\nos.environ[\"PROJECT_ID\"] = ''\n\n\n# Publishes a message to a Cloud Pub/Sub topic.\[email protected]('/')\nasync def publish(request):\n record = json.loads(json.dumps(request))\n request_data = json.loads(record)\n print(f'Request_data_json: {request_data}')\n PROJECT_ID = os.environ.get('PROJECT_ID')\n print(f'ProjectId {PROJECT_ID}')\n # Instantiates a Pub/Sub client\n publisher = pubsub_v1.PublisherClient()\n\n topic_name = request_data[\"topic\"]\n message = request_data[\"message\"]\n\n print(f'Request_data_topic: {topic_name}')\n print(f'Request_data_message: {message}')\n\n if not topic_name or not message:\n return ('Missing \"topic\" and/or \"message\" parameter.', 400)\n\n print(f'Publishing message to topic {topic_name}')\n\n # References an existing topic\n topic_path = publisher.topic_path(PROJECT_ID, topic_name)\n print(f'Topic path {topic_path}')\n\n message_json = json.dumps(message)\n message_bytes = message_json.encode('utf-8')\n\n # Publishes a message\n try:\n publish_future = publisher.publish(topic_path, data=message_bytes)\n publish_future.result() # Verify the publish succeeded\n return 'Message published.'\n except Exception as e:\n print(e)\n return e, 500\n" }, { "alpha_fraction": 0.47492626309394836, "alphanum_fraction": 0.6932153105735779, "avg_line_length": 16.384614944458008, "blob_id": "77654087c26ee4af0eec2c040b94e981227ba1be", "content_id": "9c047bf9263b839bd09f39eb9add8867ef057a25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 678, "license_type": "no_license", "max_line_length": 32, "num_lines": 39, "path": "/requirements.txt", "repo_name": "vrinda-90/publish-json", "src_encoding": "UTF-8", "text": "cachetools==4.2.1\ncertifi==2020.12.5\nchardet==4.0.0\nclick==7.1.2\nfastapi==0.63.0\ngoogle-api-core==1.26.1\ngoogle-auth==1.27.1\ngoogle-cloud-pubsub==2.4.0\ngoogleapis-common-protos==1.53.0\ngrpc-google-iam-v1==0.12.3\ngrpcio==1.36.1\nh11==0.12.0\nh2==4.0.0\nhpack==4.0.0\nHypercorn==0.11.2\nhyperframe==6.0.0\nidna==2.10\nlibcst==0.3.17\nmypy-extensions==0.4.3\npackaging==20.9\npriority==1.3.0\nproto-plus==1.14.2\nprotobuf==3.15.5\npyasn1==0.4.8\npyasn1-modules==0.2.8\npydantic==1.8.1\npyparsing==2.4.7\npytz==2021.1\nPyYAML==5.4.1\nrequests==2.25.1\nrsa==4.7.2\nsix==1.15.0\nstarlette==0.13.6\ntoml==0.10.2\ntyping-extensions==3.7.4.3\ntyping-inspect==0.6.0\nurllib3==1.26.3\nuvicorn==0.13.4\nwsproto==1.0.0\n" } ]
2
Juice178/song_visualization
https://github.com/Juice178/song_visualization
6a8c8c9a52156f1253619669b1a19e9f958a17ce
10959a0e8c93f97affa7ddc844a72be759de9ac4
f2de46edaaac0b6d2bf9a27ddf3447fa3e98389e
refs/heads/master
2023-01-28T09:47:40.379587
2020-01-13T14:45:17
2020-01-13T14:45:17
233,381,661
0
0
null
2020-01-12T11:29:08
2020-01-13T14:45:21
2023-01-23T22:22:05
Python
[ { "alpha_fraction": 0.782608687877655, "alphanum_fraction": 0.7922705411911011, "avg_line_length": 51, "blob_id": "c1f37c339036782adcdf29105f7f2770b0047fcf", "content_id": "9ef9be714682263398a58e87cbfeab566eba851f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 207, "license_type": "no_license", "max_line_length": 95, "num_lines": 4, "path": "/README.md", "repo_name": "Juice178/song_visualization", "src_encoding": "UTF-8", "text": "# spotify-song-viualization\n\nA flask app, which fetch music data (the most popular 10 songs of an artist) using Spotify API.\nThis application can be found at (https://spotify-song-viualization.herokuapp.com)" }, { "alpha_fraction": 0.7857142686843872, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 20.5, "blob_id": "3ca04cf0e0726673327764767c6068c5d0d38754", "content_id": "680744ac7d02b9a5ff225fa2c8906d3e8ef253f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 42, "license_type": "no_license", "max_line_length": 33, "num_lines": 2, "path": "/flaskr/plugin/Exceptions.py", "repo_name": "Juice178/song_visualization", "src_encoding": "UTF-8", "text": "class ToJsonException(Exception):\n pass" }, { "alpha_fraction": 0.6351351141929626, "alphanum_fraction": 0.6351351141929626, "avg_line_length": 17.625, "blob_id": "c2ed4f04628921d39f08adc9eb2f76c2811c9f14", "content_id": "66631ca78fa0eb58cb160d36bbbeb4283b202aec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 148, "license_type": "no_license", "max_line_length": 30, "num_lines": 8, "path": "/app.py", "repo_name": "Juice178/song_visualization", "src_encoding": "UTF-8", "text": "from flaskr import create_app\nimport os\n\nenv = os.getenv('env', 'prod')\napp = create_app(env)\n\nif __name__ == \"__main__\":\n app.run(threaded=True)" }, { "alpha_fraction": 0.6257485151290894, "alphanum_fraction": 0.6257485151290894, "avg_line_length": 22.89285659790039, "blob_id": "fe71ac210ddbc340488752691632a13b094bad4b", "content_id": "fef4cc1e7a0dfc810192a3822fc85515b886461a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 668, "license_type": "no_license", "max_line_length": 70, "num_lines": 28, "path": "/flaskr/__init__.py", "repo_name": "Juice178/song_visualization", "src_encoding": "UTF-8", "text": "import os \nfrom flask import Flask\nimport logging\n\ndef create_app(env=\"stg\"):\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_mapping(\n SECRET_KEY='dev',\n DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),\n )\n\n app.logger.setLevel(logging.ERROR)\n\n if env == 'stg':\n app.config.from_pyfile(\"stg.cfg\", silent=False)\n else:\n app.config.from_pyfile(\"prod.cfg\", silent=False)\n\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass \n\n from . import visualize\n app.register_blueprint(visualize.bp)\n app.add_url_rule('/', endpoint=\"index\")\n\n return app" }, { "alpha_fraction": 0.5928224325180054, "alphanum_fraction": 0.5949811339378357, "avg_line_length": 31.805309295654297, "blob_id": "594c326edaab41f6a17eb7d1fd856ccaf6784bd4", "content_id": "7cde35bdc2d3838aff4696f2812e233ceb3365d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3706, "license_type": "no_license", "max_line_length": 144, "num_lines": 113, "path": "/flaskr/visualize.py", "repo_name": "Juice178/song_visualization", "src_encoding": "UTF-8", "text": "from flask import (\n Blueprint, flash,render_template, request\n)\n\nfrom spotipy import SpotifyException\nfrom spotipy.oauth2 import SpotifyClientCredentials, SpotifyOauthError\n\nfrom flaskr.api.spotify import Spotipy\nfrom flaskr.plugin.Exceptions import ToJsonException\n\nimport pandas as pd\nimport logging\n\nbp = Blueprint('viz', __name__)\n\[email protected]('/', methods=(\"GET\", \"POST\"))\ndef get_data():\n \"\"\"\n Works differently depending on a HTTP method\n\n IF GET : Return html file for username, password, artist id inputs\n IF POST : Get data and convert it to a json file, which then is passed to html file\n \"\"\"\n # show a form to enter client id and secret key only when an user loggin for the first time\n is_first_time_login = True\n\n if request.method == 'POST':\n error = None\n\n # Instantiate object only when logged in for the first time\n if is_first_time_login:\n client_id = request.form['client_id']\n client_secret = request.form['client_secret']\n # get an client throught which an user get spotify music data\n sp_client = Spotipy(client_id, client_secret)\n\n artist_id = request.form['artist_id']\n\n try:\n # get top 10 songs of an artist\n top_tracks = sp_client.get_artist_top_tracks(artist_id)\n except SpotifyOauthError as e:\n error = 'Either client id or client secret you entered is wrong.'\n except SpotifyException as e:\n error = e\n is_first_time_login = False\n except Exception as e:\n error = e\n else:\n is_first_time_login = False\n \n if error:\n flash(error)\n else:\n try:\n json_file, artist_name = toJson(sp_client, top_tracks)\n except ToJsonException as e:\n json_file = None\n logging.error(f\"Failed to convert data to JSON \\n{e}\")\n finally:\n return render_template('visualize/index.html', data=json_file, is_first_time_login=is_first_time_login, artist_name=artist_name)\n\n return render_template('visualize/index.html', data=None, is_first_time_login=is_first_time_login, artist_name='')\n\ndef toJson(sp_client, top_tracks):\n \"\"\"\n Convert dictionary to json file\n\n Params\n ______\n sp_client: An instance to get music data \n top_traicks (dict): Information about an artist and his/her songs\n\n Returns\n _______\n json_file(json): Data with 15 columns\n artist_name (str): Artist name corresponding to artist id an user entered\n \"\"\"\n\n # features about a song\n feature_names = [\n 'danceability', 'energy', 'key', 'loudness', 'mode', 'speechiness', \n 'acousticness', 'instrumentalness', 'liveness', 'valence', 'tempo', 'duration_ms'\n ]\n\n rows = []\n\n try:\n for track in top_tracks['tracks']:\n row = []\n \n row.append(track['artists'][0]['name'])\n row.append(track['name'])\n row.append(track['popularity'])\n song_id = track['id']\n\n feature_values = sp_client.get_audio_features(song_id)[0]\n features = [val for key, val in feature_values.items() if key in feature_names]\n\n row.extend(features)\n \n rows.append(row)\n\n columns = ['artist_name', 'song_name', 'popularity']\n columns.extend(feature_names)\n df = pd.DataFrame(rows, columns = columns)\n\n json_file = df.to_json(orient='records')\n\n except Exception as e:\n raise ToJsonException(e)\n\n return json_file, df['artist_name'][0]" }, { "alpha_fraction": 0.7120211124420166, "alphanum_fraction": 0.7133421301841736, "avg_line_length": 36.70000076293945, "blob_id": "6d98e245aec4164a7bdb78b0791bec9a8918e26a", "content_id": "017aeaf830e7bc78eaa7b8e57ab494a9d30d1715", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 757, "license_type": "no_license", "max_line_length": 87, "num_lines": 20, "path": "/flaskr/api/spotify.py", "repo_name": "Juice178/song_visualization", "src_encoding": "UTF-8", "text": "\"\"\"A wrapper class for spotipy\n\"\"\"\n\nfrom spotipy import Spotify, SpotifyException\nfrom spotipy.oauth2 import SpotifyClientCredentials, SpotifyOauthError\n\nclass Spotipy(object):\n def __init__(self, client_id, client_secret):\n self._sp = self.get_client(client_id, client_secret)\n\n def get_client(self, client_id, client_secret):\n client_credentials_manager = SpotifyClientCredentials(client_id, client_secret)\n return Spotify(client_credentials_manager=client_credentials_manager)\n\n def get_artist_top_tracks(self, artist_id):\n artist_uri = f'spotify:artist:{artist_id}'\n return self._sp.artist_top_tracks(artist_uri)\n\n def get_audio_features(self, song_id):\n return self._sp.audio_features(song_id)\n\n\n\n" } ]
6